<?php
// api/chat_media.php
// Authenticated upload/delete endpoint for Firebase chat attachments.

if (ob_get_level() === 0) ob_start();
ini_set('display_errors', '0');
ini_set('html_errors', '0');
error_reporting(E_ALL);

function rvu_chat_media_bootstrap_error(string $message, int $status = 500): never {
    while (ob_get_level() > 0) @ob_end_clean();
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['detail' => $message], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    require_once __DIR__ . '/../config/database.php';
    require_once __DIR__ . '/chat_media_common.php';
} catch (Throwable $e) {
    rvu_chat_media_bootstrap_error('Chat media backend could not start: ' . $e->getMessage());
}

rvu_chat_media_cors();
if (strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
    while (ob_get_level() > 0) @ob_end_clean();
    http_response_code(204);
    exit;
}

try {
    rvu_ensure_chat_media_table($pdo);
    $user = rvu_chat_media_require_user($pdo);
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

    if ($method === 'POST') {
        $chatId = trim((string)($_POST['chat_id'] ?? ''));
        if ($chatId === '' || strlen($chatId) > 180 || !preg_match('/^[A-Za-z0-9._:-]+$/', $chatId)) {
            rvu_chat_media_json(['detail' => 'A valid chat_id is required.'], 422);
        }

        if (!isset($_FILES['file']) || !is_array($_FILES['file'])) {
            rvu_chat_media_json(['detail' => 'Choose a file to upload.'], 422);
        }

        $upload = $_FILES['file'];
        $error = (int)($upload['error'] ?? UPLOAD_ERR_NO_FILE);
        if ($error !== UPLOAD_ERR_OK) {
            $messages = [
                UPLOAD_ERR_INI_SIZE => 'The file exceeds the server upload_max_filesize limit.',
                UPLOAD_ERR_FORM_SIZE => 'The file is larger than the form allows.',
                UPLOAD_ERR_PARTIAL => 'The file upload was interrupted.',
                UPLOAD_ERR_NO_FILE => 'No file was selected.',
                UPLOAD_ERR_NO_TMP_DIR => 'The server temporary upload directory is missing.',
                UPLOAD_ERR_CANT_WRITE => 'The server could not write the uploaded file.',
                UPLOAD_ERR_EXTENSION => 'A PHP extension blocked the upload.',
            ];
            rvu_chat_media_json(['detail' => $messages[$error] ?? 'The file could not be uploaded.'], 422);
        }

        $tmp = (string)($upload['tmp_name'] ?? '');
        if ($tmp === '' || !is_uploaded_file($tmp)) {
            rvu_chat_media_json(['detail' => 'The uploaded file could not be verified.'], 422);
        }

        $originalName = rvu_chat_media_clean_filename((string)($upload['name'] ?? 'attachment'));
        $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
        if ($extension === '') {
            rvu_chat_media_json(['detail' => 'The selected file must have a recognized file extension.'], 422);
        }

        $size = (int)($upload['size'] ?? 0);
        if ($size <= 0) {
            rvu_chat_media_json(['detail' => 'The selected file is empty.'], 422);
        }

        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = strtolower((string)$finfo->file($tmp));
        $classification = rvu_chat_media_classify($extension, $mime);
        $mediaType = (string)$classification['type'];
        $maxSize = (int)$classification['max'];
        if ($size > $maxSize) {
            $mb = (int)floor($maxSize / 1024 / 1024);
            rvu_chat_media_json(['detail' => "This $mediaType file is too large. Maximum size is {$mb} MB."], 422);
        }

        $year = gmdate('Y');
        $month = gmdate('m');
        $relativeDir = 'uploads/chat_media/' . $year . '/' . $month;
        $uploadDir = __DIR__ . '/../' . $relativeDir;
        if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true) && !is_dir($uploadDir)) {
            throw new RuntimeException('The chat media upload directory could not be created.');
        }

        $token = bin2hex(random_bytes(32));
        $storedName = 'chat_' . gmdate('Ymd_His') . '_' . bin2hex(random_bytes(10)) . '.' . $extension;
        $relativePath = $relativeDir . '/' . $storedName;
        $destination = $uploadDir . DIRECTORY_SEPARATOR . $storedName;

        if (!move_uploaded_file($tmp, $destination)) {
            throw new RuntimeException('The server could not save the uploaded file.');
        }
        @chmod($destination, 0640);

        try {
            $stmt = $pdo->prepare("INSERT INTO chat_media_uploads (
                access_token, chat_id, sender_user_id, sender_email,
                original_name, stored_name, relative_path, mime_type,
                extension, media_type, size_bytes
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id, created_at");
            $stmt->execute([
                $token,
                $chatId,
                (int)$user['id'],
                $user['email'] ?? null,
                $originalName,
                $storedName,
                $relativePath,
                $mime,
                $extension,
                $mediaType,
                $size,
            ]);
            $created = $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (Throwable $dbError) {
            @unlink($destination);
            throw $dbError;
        }

        rvu_chat_media_json([
            'message' => 'Attachment uploaded successfully.',
            'media' => [
                'id' => (int)$created['id'],
                'token' => $token,
                'chat_id' => $chatId,
                'file_name' => $originalName,
                'file_type' => $mediaType,
                'mime_type' => $mime,
                'size_bytes' => $size,
                'file_url' => rvu_chat_media_download_url($token, true),
                'download_url' => rvu_chat_media_download_url($token, false),
                'created_at' => $created['created_at'],
            ],
        ], 201);
    }

    if ($method === 'DELETE') {
        $raw = file_get_contents('php://input');
        $input = json_decode($raw ?: '{}', true);
        if (!is_array($input)) $input = [];
        $token = strtolower(trim((string)($input['token'] ?? $_GET['token'] ?? '')));
        if (!preg_match('/^[a-f0-9]{64}$/', $token)) {
            rvu_chat_media_json(['detail' => 'A valid media token is required.'], 422);
        }

        $stmt = $pdo->prepare("SELECT id, sender_user_id, relative_path FROM chat_media_uploads
                               WHERE access_token = ? AND deleted_at IS NULL LIMIT 1");
        $stmt->execute([$token]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) rvu_chat_media_json(['detail' => 'Attachment not found.'], 404);

        $allowed = (int)$row['sender_user_id'] === (int)$user['id']
            || rvu_chat_media_role_is_admin((string)($user['role'] ?? ''));
        if (!$allowed) {
            rvu_chat_media_json(['detail' => 'You cannot delete this attachment.'], 403);
        }

        $pdo->prepare("UPDATE chat_media_uploads SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?")
            ->execute([(int)$row['id']]);
        rvu_chat_media_delete_file((string)$row['relative_path']);
        rvu_chat_media_json(['message' => 'Attachment deleted.']);
    }

    rvu_chat_media_json(['detail' => 'Unsupported request.'], 405);
} catch (Throwable $e) {
    rvu_chat_media_json(['detail' => 'Chat media server error: ' . $e->getMessage()], 500);
}
