<?php
require_once __DIR__ . '/bootstrap.php';
// endpoints/support.php

$auth   = requireAuth();
$userId = $auth['user_id'];
$db     = Database::getInstance();

// GET /support/tickets
if ($method === 'GET' && strpos($uri, '/support/tickets') !== false && !preg_match('#/ticket/\d+#', $uri)) {
    $tickets = $db->fetchAll(
        "SELECT t.*, (SELECT COUNT(*) FROM ticket_messages WHERE ticket_id=t.id) as msg_count
         FROM tickets t WHERE t.user_id=? ORDER BY t.updated_at DESC",
        [$userId]
    );
    jsonSuccess(['tickets' => $tickets]);
}

// POST /support/ticket/create
if ($method === 'POST' && strpos($uri, '/support/ticket/create') !== false) {
    $subject  = sanitize($input['subject'] ?? '');
    $message  = sanitize($input['message'] ?? '');
    $priority = sanitize($input['priority'] ?? 'medium');

    if (!$subject || !$message) jsonError('Subject and message are required.');
    if (!in_array($priority, ['low','medium','high'])) $priority = 'medium';

    $ticketNo = 'TKT-' . strtoupper(substr(md5(uniqid()), 0, 8));

    $ticketId = $db->insert(
        "INSERT INTO tickets (user_id, ticket_no, subject, priority) VALUES (?,?,?,?)",
        [$userId, $ticketNo, $subject, $priority]
    );

    $db->insert(
        "INSERT INTO ticket_messages (ticket_id, sender, message) VALUES (?,?,?)",
        [$ticketId, 'user', $message]
    );

    jsonSuccess(['ticket_id' => $ticketId, 'ticket_no' => $ticketNo], 'Ticket created. We will respond within 24 hours.');
}

// GET /support/ticket/{id}
if ($method === 'GET' && preg_match('#/support/ticket/(\d+)$#', $uri, $m)) {
    $ticketId = (int)$m[1];
    $ticket   = $db->fetch("SELECT * FROM tickets WHERE id=? AND user_id=?", [$ticketId, $userId]);
    if (!$ticket) jsonError('Ticket not found.', 404);
    $messages = $db->fetchAll("SELECT * FROM ticket_messages WHERE ticket_id=? ORDER BY created_at ASC", [$ticketId]);
    jsonSuccess(['ticket' => $ticket, 'messages' => $messages]);
}

// POST /support/ticket/{id}/reply
if ($method === 'POST' && preg_match('#/support/ticket/(\d+)/reply$#', $uri, $m)) {
    $ticketId = (int)$m[1];
    $message  = sanitize($input['message'] ?? '');
    if (!$message) jsonError('Message is required.');

    $ticket = $db->fetch("SELECT * FROM tickets WHERE id=? AND user_id=?", [$ticketId, $userId]);
    if (!$ticket) jsonError('Ticket not found.', 404);
    if ($ticket['status'] === 'closed') jsonError('This ticket is closed.');

    $db->insert("INSERT INTO ticket_messages (ticket_id, sender, message) VALUES (?,?,?)", [$ticketId, 'user', $message]);
    $db->query("UPDATE tickets SET status='open', updated_at=NOW() WHERE id=?", [$ticketId]);

    jsonSuccess([], 'Reply sent.');
}
