<?php
session_start();
require_once '../../config/database.php';
require_once '../../includes/app_helpers.php';
header('Content-Type: application/json');

if (empty($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    ensureOperationalTables($db);

    $active = $db->query("SELECT crl.request_id, crl.csr_id, crl.csr_name, crl.locked_at, sr.request_number, sr.full_name,
                          js.status_name
                          FROM csr_request_locks crl
                          JOIN service_requests sr ON sr.id = crl.request_id
                          LEFT JOIN job_statuses js ON js.id = sr.job_status_id
                          WHERE sr.job_status_id NOT IN (4,5)
                          ORDER BY crl.updated_at DESC
                          LIMIT 25")->fetchAll(PDO::FETCH_ASSOC);

    $latest = $db->query("SELECT rl.*, sr.request_number, COALESCE(cu.first_name, '') AS csr_first_name, COALESCE(cu.last_name, '') AS csr_last_name
                          FROM request_logs rl
                          LEFT JOIN service_requests sr ON sr.id = rl.request_id
                          LEFT JOIN csr_users cu ON cu.id = rl.user_id AND rl.user_role = 'csr'
                          ORDER BY rl.created_at DESC
                          LIMIT 30")->fetchAll(PDO::FETCH_ASSOC);

    $csrPerformance = $db->query("SELECT cu.id, CONCAT(cu.first_name, ' ', cu.last_name) AS csr_name,
                                  COUNT(ca.id) AS actions_today,
                                  SUM(ca.action = 'request_claimed') AS claimed_today,
                                  SUM(ca.action = 'status_change') AS status_changes_today,
                                  SUM(ca.action = 'chat_reply') AS chat_replies_today
                                  FROM csr_users cu
                                  LEFT JOIN csr_activity ca ON ca.csr_id = cu.id AND DATE(ca.created_at) = CURDATE()
                                  WHERE cu.is_active = 1
                                  GROUP BY cu.id
                                  ORDER BY actions_today DESC, csr_name ASC")->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['success' => true, 'active_handling' => $active, 'latest_logs' => $latest, 'csr_performance' => $csrPerformance]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
