<?php
header('Content-Type: application/json; charset=utf-8');
include('../connection.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request method'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$rechargeId = trim($_POST['recharge_id'] ?? '');

if ($rechargeId === '') {
    echo json_encode([
        'status' => 'error',
        'message' => 'Recharge ID is required'
    ], JSON_UNESCAPED_UNICODE);
    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 recharge_id = ? ORDER BY id DESC');
$stmt->bind_param('s', $rechargeId);
$stmt->execute();
$result = $stmt->get_result();

$data = [];

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $data[] = [
            'id' => (int) $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'],
            'priroty' => $row['priroty'],
            'create_by' => $row['create_by'],
            'check_time' => $row['check_time'],
            'remark' => $row['remark'],
            'check_count' => $row['check_count'],
            'admin' => 0,
            'user' => 0
        ];
    }
}

echo json_encode([
    'status' => 'success',
    'data' => $data
], JSON_UNESCAPED_UNICODE);
