<?php
// =====================================================
// GET /get-user-tickets.php?user_id=X
// Response: JSON Array of tickets for specific user
// =====================================================
require_once 'config.php';

$conn = getConnection();

$user_id = $_GET['user_id'] ?? '';

if (empty($user_id)) {
    echo json_encode([]);
    exit;
}

$stmt = $conn->prepare("SELECT id, problem, assign, location, created_at, status, end_time,
                                recharge_id, user_id, name, phone, priroty, create_by,
                                check_time, remark, check_count
                         FROM ticket WHERE user_id = ? ORDER BY id DESC");
$stmt->bind_param("s", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$tickets = [];
while ($row = $result->fetch_assoc()) {
    // Count tickets for same recharge_id in last 30 days
    $recharge_count = 0;
    if (!empty($row['recharge_id'])) {
        $stmt2 = $conn->prepare("SELECT COUNT(*) as cnt FROM ticket WHERE recharge_id = ?");
        $stmt2->bind_param("s", $row['recharge_id']);
        $stmt2->execute();
        $recharge_count = $stmt2->get_result()->fetch_assoc()['cnt'];
        $stmt2->close();
    }

    $tickets[] = [
        "id"          => (string)$row['id'],
        "problem"     => $row['problem'] ?? '',
        "assign"      => $row['assign'] ?? '',
        "location"    => $row['location'] ?? '',
        "created_at"  => $row['created_at'] ?? '',
        "status"      => $row['status'] ?? '',
        "end_time"    => $row['end_time'] ?? '',
        "recharge_id" => $row['recharge_id'] ?? '',
        "user_id"     => $row['user_id'] ?? '',
        "name"        => $row['name'] ?? '',
        "phone"       => $row['phone'] ?? '',
        "priority"    => $row['priroty'] ?? '',
        "create_by"   => $row['create_by'] ?? '',
        "check_time"  => $row['check_time'] ?? '',
        "remark"      => $row['remark'] ?? '',
        "check_count" => (string)($row['check_count'] ?? '0'),
        "creator"     => '',
        "recharge_ticket_count_last_30_days" => (string)$recharge_count
    ];
}

echo json_encode($tickets);

$stmt->close();
$conn->close();
