<?php
// =====================================================
// GET /all_ticket.php
// Response: JSON Array of all tickets with recharge_ticket_count_last_30_days
// =====================================================
require_once 'config.php';

$conn = getConnection();

$result = $conn->query("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 ORDER BY id DESC");

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

$conn->close();
