<?php
require_once 'auth_check.php';
require_once 'db.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Non autorisé']);
    exit;
}

try {
    $db1 = getDB1Connection();
    
    $query = "SELECT 
                st.id,
                st.subject,
                st.status,
                st.priority,
                st.created_at,
                u.username as user_name,
                u.email as user_email
              FROM support_tickets st
              INNER JOIN utilisateurs u ON st.user_id = u.id
              ORDER BY st.created_at DESC";
              
    $stmt = $db1->query($query);
    $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach($tickets as &$ticket) {
        $ticket['created_at'] = date('d/m/Y H:i', strtotime($ticket['created_at']));
    }
    
    echo json_encode($tickets);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Erreur lors du chargement des tickets: ' . $e->getMessage()]);
}