<?php
session_start();
require_once 'db.php';

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

$db = new Database();
$conn = $db->connect();

try {
    // Récupération des notifications non lues
    $stmt = $conn->prepare("
        SELECT n.*, t.subject, t.status
        FROM ticket_notifications n
        JOIN support_tickets t ON n.ticket_id = t.id
        WHERE n.user_id = ? AND n.is_read = FALSE
        ORDER BY n.created_at DESC
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Formatage des notifications pour l'affichage
    $formatted_notifications = array_map(function($notification) {
        return [
            'id' => $notification['id'],
            'ticket_id' => $notification['ticket_id'],
            'message' => $notification['message'],
            'subject' => $notification['subject'],
            'status' => $notification['status'],
            'created_at' => date('Y-m-d H:i:s', strtotime($notification['created_at'])),
            'url' => "view_ticket.php?id=" . $notification['ticket_id']
        ];
    }, $notifications);

    // Compter les notifications non lues
    $stmt = $conn->prepare("
        SELECT COUNT(*) as count 
        FROM ticket_notifications 
        WHERE user_id = ? AND is_read = FALSE
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $unread_count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];

    // Retourner la réponse
    echo json_encode([
        'notifications' => $formatted_notifications,
        'unread_count' => $unread_count
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    error_log("Notification error: " . $e->getMessage());
    echo json_encode(['error' => 'Internal server error']);
}