<?php
require_once '../src/Database.php';
$conn = Database::getInstance();

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

// Fetch tickets with user details from external_ticket table
$sql = "
    SELECT 
        external_ticket.*, 
        users.name AS user_name, 
        users.email AS user_email, 
        users.phone AS user_phone
    FROM external_ticket
    JOIN users ON external_ticket.ticket_user_id = users.id
    WHERE external_ticket.ticket_user_id = ?
    ORDER BY external_ticket.created_at DESC
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$tickets = [];

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Ensure task_id is a string even if empty
        $row['task_id'] = !empty($row['task_id']) ? $row['task_id'] : '';

        // Here, no API calls, only DB data returned as-is
        $tickets[] = $row;
    }
}

$conn->close();

header('Content-Type: application/json');
echo json_encode($tickets);
