<?php
require_once '../element/connection.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Not logged in']);
    exit();
}

$conn = getConnection();
$user_id = intval($_SESSION['user_id']);

// Get unread count with timestamp to prevent caching
$query = "SELECT COUNT(DISTINCT m.id) as unread_count,
                 MAX(m.created_at) as last_message_time
          FROM support_messages m 
          JOIN support_tickets t ON m.ticket_id = t.id 
          WHERE t.user_id = '$user_id' 
          AND m.sender_type = 'admin' 
          AND m.is_read = 0";
$result = mysqli_query($conn, $query);
$data = mysqli_fetch_assoc($result);

// Get last 3 unread messages for preview
$messages_query = "SELECT m.id, m.message, m.created_at, t.ticket_id, t.subject
                   FROM support_messages m 
                   JOIN support_tickets t ON m.ticket_id = t.id 
                   WHERE t.user_id = '$user_id' 
                   AND m.sender_type = 'admin' 
                   AND m.is_read = 0 
                   ORDER BY m.created_at DESC 
                   LIMIT 3";
$messages_result = mysqli_query($conn, $messages_query);
$messages = [];

while ($row = mysqli_fetch_assoc($messages_result)) {
    $messages[] = [
        'id' => $row['id'],
        'ticket_id' => $row['ticket_id'],
        'message' => substr($row['message'], 0, 50) . (strlen($row['message']) > 50 ? '...' : ''),
        'time' => date('h:i A', strtotime($row['created_at'])),
        'full_message' => $row['message']
    ];
}

echo json_encode([
    'success' => true,
    'unread_count' => (int)$data['unread_count'],
    'last_message_time' => $data['last_message_time'],
    'messages' => $messages,
    'timestamp' => time()
]);
exit();
?>