<?php
declare(strict_types=1);

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

try {
    rvu_support_ensure_tables($pdo);
    $user = rvu_support_require_user($pdo);
    $isAdmin = rvu_support_is_admin($user['role'] ?? '');
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

    if ($method === 'GET') {
        $threadId = isset($_GET['thread_id']) && ctype_digit((string)$_GET['thread_id'])
            ? (int)$_GET['thread_id']
            : 0;
        if ($threadId <= 0) {
            rvu_support_json(['detail' => 'A valid conversation ID is required.'], 400);
        }

        $thread = rvu_support_fetch_thread_basic($pdo, $threadId);
        if (!$thread) {
            rvu_support_json(['detail' => 'Conversation not found.'], 404);
        }
        if (!rvu_support_can_access($user, $thread)) {
            rvu_support_json(['detail' => 'You do not have access to this conversation.'], 403);
        }

        rvu_support_mark_read($pdo, $threadId, $user);

        $sql = "SELECT
            m.id,
            m.thread_id,
            m.sender_user_id,
            m.sender_role,
            m.body,
            m.created_at,
            COALESCE(u.full_name, 'Rockview User') AS sender_name,
            COALESCE(u.profile_picture, '') AS sender_profile_picture,
            (m.sender_user_id = ?) AS sent_by_me,
            COALESCE((
                SELECT json_agg(
                    json_build_object(
                        'id', a.id,
                        'message_id', a.message_id,
                        'media_type', a.media_type,
                        'path', a.file_path,
                        'thumbnail_path', a.thumbnail_path,
                        'original_name', a.original_name,
                        'mime_type', a.mime_type,
                        'size_bytes', a.size_bytes
                    ) ORDER BY a.id
                )
                FROM staff_support_media a
                WHERE a.message_id = m.id
            ), '[]'::json) AS attachments
          FROM staff_support_messages m
          LEFT JOIN users u ON u.id = m.sender_user_id
          WHERE m.thread_id = ?
          ORDER BY m.created_at ASC, m.id ASC";

        $stmt = $pdo->prepare($sql);
        $stmt->execute([(int)$user['id'], $threadId]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($rows as &$row) {
            $row['id'] = (int)$row['id'];
            $row['thread_id'] = (int)$row['thread_id'];
            $row['sender_user_id'] = (int)$row['sender_user_id'];
            $row['sent_by_me'] = in_array($row['sent_by_me'], [true, 1, '1', 't', 'true'], true);
            if (is_string($row['attachments'])) {
                $decoded = json_decode($row['attachments'], true);
                $row['attachments'] = is_array($decoded) ? $decoded : [];
            }
        }
        unset($row);

        rvu_support_json(['data' => $rows]);
    }

    if ($method === 'POST') {
        $input = rvu_support_input();
        $threadId = isset($input['thread_id']) && ctype_digit((string)$input['thread_id'])
            ? (int)$input['thread_id']
            : 0;
        if ($threadId <= 0) {
            rvu_support_json(['detail' => 'A valid conversation ID is required.'], 400);
        }

        $body = rvu_support_clean_text($input['body'] ?? '', 8000, false);
        if ($body === '') {
            rvu_support_json(['detail' => 'Write a message before sending it.'], 400);
        }

        $thread = rvu_support_fetch_thread_basic($pdo, $threadId);
        if (!$thread) {
            rvu_support_json(['detail' => 'Conversation not found.'], 404);
        }
        if (!rvu_support_can_access($user, $thread)) {
            rvu_support_json(['detail' => 'You do not have access to this conversation.'], 403);
        }
        if (strtolower((string)$thread['status']) === 'resolved') {
            rvu_support_json(['detail' => 'This conversation is resolved. Reopen it before sending another message.'], 409);
        }

        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare(
                "INSERT INTO staff_support_messages (
                    thread_id, sender_user_id, sender_role, body
                 ) VALUES (?, ?, ?, ?)
                 RETURNING id"
            );
            $stmt->execute([
                $threadId,
                (int)$user['id'],
                (string)($user['role'] ?? ''),
                $body,
            ]);
            $messageId = (int)$stmt->fetchColumn();

            $nextStatus = $isAdmin ? 'waiting_staff' : 'waiting_admin';
            $readColumn = $isAdmin ? 'admin_last_read_at' : 'staff_last_read_at';
            $update = $pdo->prepare(
                "UPDATE staff_support_threads
                 SET status = ?, updated_at = CURRENT_TIMESTAMP, $readColumn = CURRENT_TIMESTAMP
                 WHERE id = ?"
            );
            $update->execute([$nextStatus, $threadId]);
            $pdo->commit();

            $row = rvu_support_message_row($pdo, $messageId, $user);
            rvu_support_json(['data' => $row], 201);
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            throw $e;
        }
    }

    rvu_support_json(['detail' => 'Method not allowed.'], 405);
} 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);
}
