<?php
require_once '../includes/admin_auth.php';

if (!$adminAuth->isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$db = Database::getInstance()->connect();

// Get notification count (open support tickets)
$count_stmt = $db->prepare("SELECT COUNT(*) as count FROM support_tickets WHERE status = 'open'");
$count_stmt->execute();
$count = $count_stmt->fetchColumn();

// Get recent notifications (open support tickets)
$list_stmt = $db->prepare("SELECT * FROM support_tickets WHERE status = 'open' ORDER BY created_at DESC LIMIT 5");
$list_stmt->execute();
$tickets = $list_stmt->fetchAll();

// Helper function for time ago
function time_ago($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) return 'just now';
    if ($diff < 3600) return floor($diff/60) . ' minutes ago';
    if ($diff < 86400) return floor($diff/3600) . ' hours ago';
    if ($diff < 604800) return floor($diff/86400) . ' days ago';
    return date('M d, Y', $time);
}

$html = '';
if (empty($tickets)) {
    $html = '<p class="text-gray-500 text-sm text-center p-4">No new notifications</p>';
} else {
    foreach ($tickets as $ticket) {
        $html .= '<a href="ticket-view.php?id=' . $ticket['id'] . '" class="block p-3 rounded-lg hover:bg-gray-100">';
        $html .= '<div class="flex items-start space-x-3"><i class="fas fa-ticket-alt text-blue-500 mt-1"></i><div>';
        $html .= '<p class="text-sm font-semibold">New Ticket: #' . htmlspecialchars($ticket['ticket_id']) . '</p>';
        $html .= '<p class="text-sm text-gray-600 truncate">' . htmlspecialchars($ticket['subject']) . '</p>';
        $html .= '<p class="text-xs text-gray-400 mt-1">' . time_ago($ticket['created_at']) . '</p>';
        $html .= '</div></div></a>';
    }
}

header('Content-Type: application/json');
echo json_encode([
    'success' => true,
    'count' => $count,
    'html' => $html
]);
?>