<?php
// ─── Support Tickets API ────────────────────────────────────────────────

function ticketList() {
    $uid = require_login();
    global $conn;
    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";
    
    $rss = mysqli_query($conn, "SELECT DISTINCT h_support.rid,h_support.subject,h_support.date,h_support.status
        FROM h_support JOIN (SELECT rid,MAX(id) mid FROM h_support WHERE 1=1 $uidok GROUP BY rid) l 
        ON h_support.rid=l.rid AND h_support.id=l.mid ORDER BY h_support.date DESC LIMIT 50");
    
    $items = [];
    while ($row = mysqli_fetch_assoc($rss)) {
        $items[] = [
            'rid' => (int)$row['rid'],
            'subject' => $row['subject'],
            'status' => (int)($row['status'] ?? 0),
            'date' => $row['date']
        ];
    }
    success_response(['items' => $items]);
}

function detail() {
    $uid = require_login();
    global $conn;
    $rid = (int)($_GET['rid'] ?? 0);
    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";
    
    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_support WHERE rid='$rid' $uidok ORDER BY id DESC LIMIT 1"));
    if (!$row) error_response('Ticket not found', 404);
    
    $messages = [];
    $rt = mysqli_query($conn, "SELECT * FROM h_support WHERE rid='$rid' $uidok ORDER BY id ASC");
    while ($m = mysqli_fetch_assoc($rt)) {
        $uinfo = mysqli_fetch_assoc(mysqli_query($conn, "SELECT name FROM h_user WHERE id='{$m['uid']}'"));
        $messages[] = [
            'id' => $m['id'],
            'uid' => $m['uid'],
            'message' => decode($m['message'], KEY_ONE),
            'date' => $m['date'],
            'is_staff' => in_array($m['status'], [1, 2]),
            'user_name' => $uinfo['name'] ?? 'Unknown'
        ];
    }
    
    success_response([
        'rid' => $rid,
        'subject' => $row['subject'],
        'status' => (int)$row['status'],
        'messages' => $messages
    ]);
}

function create() {
    $uid = require_login();
    global $conn, $now;
    
    $subject = mysqli_real_escape_string($conn, trim($_POST['subject'] ?? ''));
    $message = encode(nl2br(trim($_POST['message'] ?? '')), KEY_ONE);
    
    if (empty($subject) || empty($message)) error_response('Please fill in all fields.');
    
    $rwss = mysqli_fetch_assoc(mysqli_query($conn, "SELECT MAX(id) as maxid FROM h_support"));
    $rid = ((int)$rwss['maxid']) + 1;
    
    mysqli_query($conn, "INSERT INTO h_support (subject,message,uid,rid,udate,date,status,stall) 
        VALUES ('$subject','$message','$uid','$rid','$now','$now','0','0')");
    
    success_response(['rid' => $rid], 'Ticket created.');
}

function reply() {
    $uid = require_login();
    global $conn, $now;
    
    $rid = (int)($_POST['rid'] ?? 0);
    $subject = mysqli_real_escape_string($conn, trim($_POST['subject'] ?? ''));
    $rawMessage = trim($_POST['message'] ?? '');
    $message = encode(nl2br($rawMessage), KEY_ONE);
    
    if (empty($rawMessage)) error_response('Message is required.');
    
    $status = is_admin($uid) ? 1 : 0;
    mysqli_query($conn, "UPDATE h_support SET stall='$status', status='$status' WHERE rid='$rid' ORDER BY id DESC LIMIT 1");
    mysqli_query($conn, "INSERT INTO h_support (subject,message,uid,rid,udate,date,status,stall) 
        VALUES ('$subject','$message','$uid','$rid','$now','$now','$status','$status')");
    
    success_response([], 'Reply sent.');
}

function close() {
    $uid = require_login();
    global $conn;
    $rid = (int)($_GET['rid'] ?? 0);
    mysqli_query($conn, "UPDATE h_support SET stall='2', status='2' WHERE rid='$rid' AND status!='2'");
    success_response([], 'Ticket closed.');
}