<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/support_common.php';

function rvu_support_collect_uploads(string $field): array
{
    if (!isset($_FILES[$field])) return [];
    $file = $_FILES[$field];
    if (!is_array($file['name'] ?? null)) {
        return [[
            'name' => $file['name'] ?? '',
            'type' => $file['type'] ?? '',
            'tmp_name' => $file['tmp_name'] ?? '',
            'error' => $file['error'] ?? UPLOAD_ERR_NO_FILE,
            'size' => $file['size'] ?? 0,
        ]];
    }
    $result = [];
    $count = count($file['name']);
    for ($i = 0; $i < $count; $i++) {
        $result[] = [
            'name' => $file['name'][$i] ?? '',
            'type' => $file['type'][$i] ?? '',
            'tmp_name' => $file['tmp_name'][$i] ?? '',
            'error' => $file['error'][$i] ?? UPLOAD_ERR_NO_FILE,
            'size' => $file['size'][$i] ?? 0,
        ];
    }
    return $result;
}

try {
    rvu_support_ensure_tables($pdo);
    $user = rvu_support_require_user($pdo);
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
    if ($method !== 'POST') {
        rvu_support_json(['detail' => 'Only POST is supported for support attachments.'], 405);
    }

    $messageId = isset($_POST['message_id']) && ctype_digit((string)$_POST['message_id'])
        ? (int)$_POST['message_id']
        : 0;
    if ($messageId <= 0) {
        rvu_support_json(['detail' => 'A valid message ID is required.'], 400);
    }

    $messageStmt = $pdo->prepare(
        'SELECT m.id, m.thread_id, m.sender_user_id, t.author_id, t.status
         FROM staff_support_messages m
         INNER JOIN staff_support_threads t ON t.id = m.thread_id
         WHERE m.id = ?
         LIMIT 1'
    );
    $messageStmt->execute([$messageId]);
    $message = $messageStmt->fetch(PDO::FETCH_ASSOC);
    if (!$message) {
        rvu_support_json(['detail' => 'Message not found.'], 404);
    }

    $isAdmin = rvu_support_is_admin($user['role'] ?? '');
    $canAccess = $isAdmin || (int)$message['author_id'] === (int)$user['id'];
    if (!$canAccess) {
        rvu_support_json(['detail' => 'You do not have access to this conversation.'], 403);
    }
    if ((int)$message['sender_user_id'] !== (int)$user['id']) {
        rvu_support_json(['detail' => 'Attachments can only be added to your own message.'], 403);
    }

    $existingStmt = $pdo->prepare('SELECT COUNT(*) FROM staff_support_media WHERE message_id = ?');
    $existingStmt->execute([$messageId]);
    $existingCount = (int)$existingStmt->fetchColumn();

    $images = rvu_support_collect_uploads('images');
    $files = rvu_support_collect_uploads('files');
    $uploads = [];
    foreach ($images as $file) $uploads[] = ['kind' => 'image', 'file' => $file];
    foreach ($files as $file) $uploads[] = ['kind' => 'file', 'file' => $file];

    if (!$uploads) {
        rvu_support_json(['detail' => 'Select at least one attachment.'], 400);
    }
    if ($existingCount + count($uploads) > 5) {
        rvu_support_json(['detail' => 'A message can contain at most 5 attachments.'], 400);
    }

    $dir = rvu_support_upload_dir();
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $saved = [];

    $allowedImages = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
    ];
    $allowedFiles = [
        'application/pdf' => 'pdf',
        'text/plain' => 'txt',
        'application/msword' => 'doc',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
        'application/vnd.ms-excel' => 'xls',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
    ];

    foreach ($uploads as $item) {
        $file = $item['file'];
        $kind = $item['kind'];
        if ((int)$file['error'] !== UPLOAD_ERR_OK) {
            rvu_support_json(['detail' => 'An attachment could not be uploaded.'], 400);
        }
        $size = (int)$file['size'];
        if ($size <= 0 || $size > 10 * 1024 * 1024) {
            rvu_support_json(['detail' => 'Each attachment must be between 1 byte and 10 MB.'], 400);
        }

        $tmp = (string)$file['tmp_name'];
        $mime = (string)$finfo->file($tmp);
        $original = rvu_support_safe_filename((string)$file['name']);
        $extension = strtolower(pathinfo($original, PATHINFO_EXTENSION));
        $mediaType = 'file';
        $safeExtension = '';

        if ($kind === 'image') {
            if (!isset($allowedImages[$mime])) {
                rvu_support_json(['detail' => 'Pictures must be JPEG, PNG or WebP.'], 400);
            }
            $mediaType = 'image';
            $safeExtension = $allowedImages[$mime];
        } else {
            if (!isset($allowedFiles[$mime])) {
                // Office documents are sometimes reported as application/zip by local PHP builds.
                if (in_array($mime, ['application/zip', 'application/octet-stream'], true)
                    && in_array($extension, ['doc', 'docx', 'xls', 'xlsx', 'pdf', 'txt'], true)) {
                    $safeExtension = $extension;
                } else {
                    rvu_support_json(['detail' => 'Documents must be PDF, TXT, DOC, DOCX, XLS or XLSX.'], 400);
                }
            } else {
                $safeExtension = $allowedFiles[$mime];
            }
        }

        $token = bin2hex(random_bytes(18));
        $fileName = 'support_' . $messageId . '_' . $token . '.' . $safeExtension;
        $absolute = $dir . DIRECTORY_SEPARATOR . $fileName;
        if (!move_uploaded_file($tmp, $absolute)) {
            throw new RuntimeException('Unable to save an attachment.');
        }

        $relative = 'uploads/support/' . $fileName;
        $thumbRelative = null;
        if ($mediaType === 'image') {
            $thumbName = 'support_' . $messageId . '_' . $token . '_thumb.' . $safeExtension;
            $thumbAbsolute = $dir . DIRECTORY_SEPARATOR . $thumbName;
            if (rvu_support_make_thumbnail($absolute, $thumbAbsolute, $mime)) {
                $thumbRelative = 'uploads/support/' . $thumbName;
            }
        }

        $stmt = $pdo->prepare(
            "INSERT INTO staff_support_media (
                message_id, media_type, file_path, thumbnail_path,
                original_name, mime_type, size_bytes
             ) VALUES (?, ?, ?, ?, ?, ?, ?)
             RETURNING id"
        );
        $stmt->execute([
            $messageId,
            $mediaType,
            $relative,
            $thumbRelative,
            $original,
            $mime,
            $size,
        ]);
        $id = (int)$stmt->fetchColumn();
        $saved[] = [
            'id' => $id,
            'message_id' => $messageId,
            'media_type' => $mediaType,
            'path' => $relative,
            'thumbnail_path' => $thumbRelative ?? '',
            'original_name' => $original,
            'mime_type' => $mime,
            'size_bytes' => $size,
        ];
    }

    $pdo->prepare('UPDATE staff_support_threads SET updated_at = CURRENT_TIMESTAMP WHERE id = ?')
        ->execute([(int)$message['thread_id']]);

    rvu_support_json(['data' => $saved], 201);
} catch (PDOException $e) {
    rvu_support_json(['detail' => 'Support database error: ' . $e->getMessage()], 500);
} catch (Throwable $e) {
    rvu_support_json(['detail' => 'Support server error: ' . $e->getMessage()], 500);
}
