<?php
/**
 * سودانا — Support Tickets API v21
 * إدارة تذاكر الدعم — المستخدمون والموظفون
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE

$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$b      = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $_GET['action'] ?? ($b['action'] ?? 'create');
$isStaff = !empty($u['user_type']) && in_array($u['user_type'], ['admin','staff','moderator']);

// ── CREATE ──────────────────────────────────────────────────
if ($action === 'create') {
    if (!check_rate_limit('ticket_'.$u['id'], 5, 86400))
        Kernel::fail('rate_limit', 'الحد الأقصى 5 تذاكر يومياً', 429);

    $category    = $b['category']    ?? 'other';
    $priority    = in_array($b['priority']??'', ['low','normal','high','urgent']) ? $b['priority'] : 'normal';
    $subject     = mb_substr(trim($b['subject'] ?? ''), 0, 300);
    $description = mb_substr(trim($b['description'] ?? ''), 0, 3000);
    $relType     = $b['related_type'] ?? null;
    $relId       = isset($b['related_id']) ? (int)$b['related_id'] : null;

    if (!$subject || mb_strlen($subject) < 5)
        Kernel::fail('subject_required', 'العنوان 5 أحرف على الأقل', 400);
    if (!$description || mb_strlen($description) < 15)
        Kernel::fail('description_required', 'الوصف 15 حرفاً على الأقل', 400);

    db()->prepare(
        'INSERT INTO support_tickets (user_id, category, priority, subject, description, related_type, related_id, status)
         VALUES (?,?,?,?,?,?,?,"open")'
    )->execute([$u['id'], $category, $priority, $subject, $description, $relType, $relId]);

    $ticketId = (int)db()->lastInsertId();

    // Notify staff
    try {
        $staffTokens = db()->query("SELECT DISTINCT d.fcm_token FROM user_devices d JOIN staff_members s ON s.user_id=d.user_id WHERE s.is_active=1 LIMIT 5")->fetchAll();
        foreach ($staffTokens as $t) {
            if ($t['fcm_token']) send_push($t['fcm_token'], "🎫 تذكرة {$priority}", $subject, ['tab'=>'support','ticket_id'=>(string)$ticketId]);
        }
    } catch (Throwable $ignored) {}

    $sla = match($priority) { 'urgent'=>'4 ساعات','high'=>'8 ساعات',default=>'24 ساعة' };

    json_response([
        'success'   => true,
        'ticket_id' => $ticketId,
        'status'    => 'open',
        'message'   => "تم فتح تذكرة الدعم #$ticketId. سنرد خلال $sla.",
        'sla'       => $sla,
    ]);
}

// ── LIST ────────────────────────────────────────────────────
if ($action === 'list') {
    if ($isStaff) {
        // Staff sees all open tickets
        $filter = $_GET['filter'] ?? 'open';
        $st = db()->prepare(
            "SELECT t.*, u.name AS user_name FROM support_tickets t
             JOIN users u ON u.id=t.user_id
             WHERE t.status " . ($filter==='all' ? "!= 'deleted'" : "IN ('open','in_progress','escalated')")
             . " ORDER BY FIELD(t.priority,'urgent','high','normal','low'), t.created_at ASC LIMIT 50"
        );
        $st->execute();
    } else {
        $st = db()->prepare('SELECT t.*, sr.message AS last_reply FROM support_tickets t LEFT JOIN support_ticket_replies sr ON sr.id=(SELECT MAX(id) FROM support_ticket_replies WHERE ticket_id=t.id) WHERE t.user_id=? ORDER BY t.created_at DESC LIMIT 20');
        $st->execute([$u['id']]);
    }
    json_response(['success'=>true,'tickets'=>$st->fetchAll()]);
}

// ── REPLY ───────────────────────────────────────────────────
if ($action === 'reply') {
    $ticketId = (int)($b['ticket_id'] ?? 0);
    $message  = mb_substr(trim($b['message'] ?? ''), 0, 2000);
    if (!$ticketId || !$message)
        Kernel::fail('missing_fields', '', 400);

    $ticket = db()->prepare('SELECT * FROM support_tickets WHERE id=? LIMIT 1');
    $ticket->execute([$ticketId]);
    $tk = $ticket->fetch();
    if (!$tk) Kernel::fail('not_found', '', 404);
    if (!$isStaff && $tk['user_id'] !== $u['id'])
        Kernel::fail('access_denied', '', 403);

    db()->prepare('INSERT INTO support_ticket_replies (ticket_id, user_id, message, is_staff) VALUES (?,?,?,?)')
       ->execute([$ticketId, $u['id'], $message, (int)$isStaff]);

    // First response time tracking
    if ($isStaff && !$tk['first_response_at']) {
        db()->prepare("UPDATE support_tickets SET first_response_at=NOW(), status='in_progress', assigned_to=? WHERE id=?")
           ->execute([$u['id'], $ticketId]);
    }

    // Reopen if user replies to resolved
    if (!$isStaff && $tk['status'] === 'resolved') {
        db()->prepare("UPDATE support_tickets SET status='open' WHERE id=?")->execute([$ticketId]);
    }

    // FCM
    $notifyUserId = $isStaff ? $tk['user_id'] : ($tk['assigned_to'] ?? null);
    if ($notifyUserId) {
        $token = get_user_token($notifyUserId);
        if ($token) send_push($token, '💬 رد جديد على تذكرتك', mb_substr($message,0,60), ['ticket_id'=>(string)$ticketId]);
    }

    json_response(['success'=>true,'message'=>'تم إرسال ردك']);
}

// ── RESOLVE (staff) ─────────────────────────────────────────
if ($action === 'resolve') {
    if (!$isStaff) Kernel::fail('not_staff', '', 403);
    $ticketId  = (int)($b['ticket_id'] ?? 0);
    $resolution= mb_substr(trim($b['resolution'] ?? ''), 0, 1000);

    db()->prepare("UPDATE support_tickets SET status='resolved', resolved_at=NOW(), resolution=? WHERE id=?")
       ->execute([$resolution ?: 'تم حل المشكلة', $ticketId]);

    $ticket = db()->prepare('SELECT user_id FROM support_tickets WHERE id=? LIMIT 1');
    $ticket->execute([$ticketId]);
    $tk = $ticket->fetch();
    if ($tk) {
        $token = get_user_token($tk['user_id']);
        if ($token) send_push($token, '✅ تذكرتك حُلّت', 'تم حل مشكلتك. قيّم تجربتك!', ['ticket_id'=>(string)$ticketId]);
        save_notification($tk['user_id'], 'ticket_resolved', 'تذكرة محلولة ✅', $resolution ?: 'تم حل المشكلة');
    }

    json_response(['success'=>true,'message'=>'تم تسجيل الحل وإخطار المستخدم']);
}

// ── ESCALATE (staff) ────────────────────────────────────────
if ($action === 'escalate') {
    if (!$isStaff) Kernel::fail('not_staff', '', 403);
    $ticketId = (int)($b['ticket_id'] ?? 0);
    db()->prepare("UPDATE support_tickets SET status='escalated', priority='urgent', sla_breach=1 WHERE id=?")->execute([$ticketId]);

    // Notify admin
    try {
        $admin = db()->query("SELECT d.fcm_token FROM user_devices d WHERE d.user_id IN (SELECT user_id FROM staff_members WHERE role='admin') LIMIT 1")->fetch();
        if ($admin && $admin['fcm_token']) send_push($admin['fcm_token'], '🚨 تذكرة مُصعَّدة', "تذكرة #$ticketId تحتاج تدخلاً عاجلاً");
    } catch (Throwable $ignored) {}

    json_response(['success'=>true,'message'=>'تم التصعيد للإدارة']);
}

Kernel::fail('unknown_action', '', 400);
