<?php
require_once '../auth.php';
ensureAdminAjaxAuth();
require_once '../../config/database.php';
header('Content-Type: application/json');
try {
    $database = new Database();
    $db = $database->getConnection();
    $counts = [
        'total' => (int)$db->query("SELECT COUNT(*) FROM service_requests")->fetchColumn(),
        'new_request' => (int)$db->query("SELECT COUNT(*) FROM service_requests WHERE job_status_id = 1")->fetchColumn(),
        'assigned' => (int)$db->query("SELECT COUNT(*) FROM service_requests WHERE job_status_id = 2")->fetchColumn(),
        'in_progress' => (int)$db->query("SELECT COUNT(*) FROM service_requests WHERE job_status_id = 3")->fetchColumn(),
        'completed' => (int)$db->query("SELECT COUNT(*) FROM service_requests WHERE job_status_id = 4")->fetchColumn(),
        'cancelled' => (int)$db->query("SELECT COUNT(*) FROM service_requests WHERE job_status_id = 5")->fetchColumn(),
        'unread_chats' => (int)$db->query("SELECT COUNT(*) FROM chat_conversations WHERE status='open' AND (assignment_status IN ('unassigned','returned_queue') OR assigned_csr_id IS NULL)")->fetchColumn(),
        'last_request_id' => (int)$db->query("SELECT COALESCE(MAX(id),0) FROM service_requests")->fetchColumn(),
        'server_time' => date('Y-m-d H:i:s')
    ];
    echo json_encode(['success' => true, 'counts' => $counts]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
