<?php
session_start();
header('Content-Type: application/json');
if (!isset($_SESSION['csr_id'])) { echo json_encode(['success'=>false,'message'=>'Unauthorized']); exit; }
require_once '../../config/database.php';
require_once '../../includes/chat_helper.php';
require_once '../../includes/app_helpers.php';
$database=new Database();$db=$database->getConnection();ensureChatTables($db);ensureCsrTeamTables($db);releaseOverdueChatAssignments($db,5);
try{
    $csr=(int)$_SESSION['csr_id'];
    $stmt=$db->prepare("SELECT COUNT(*) FROM csr_notifications WHERE csr_id=:id AND is_read=0 AND COALESCE(reference_type,'')<>'announcement'");$stmt->execute([':id'=>$csr]);$unread=(int)$stmt->fetchColumn();

    $scope = getCsrRequestScope($db, $csr);
    if (!empty($scope['is_manager'])) {
        $params = [];
        $teamIn = addInClauseParams($params, $scope['team_ids'], 'live_team');
        $csrIn = addInClauseParams($params, $scope['visible_csr_ids'], 'live_csr');
        $params[':manager_id'] = $csr;
        $stmt=$db->prepare("SELECT COUNT(*) FROM chat_conversations cc WHERE cc.status='open' AND (cc.assigned_team_id IN ($teamIn) OR cc.assigned_manager_id=:manager_id OR cc.assigned_csr_id IN ($csrIn))");
        foreach($params as $k=>$v){$stmt->bindValue($k,$v,is_int($v)?PDO::PARAM_INT:PDO::PARAM_STR);} $stmt->execute();
    } else {
        $stmt=$db->prepare("SELECT COUNT(*) FROM chat_conversations cc WHERE cc.status='open' AND cc.assigned_csr_id=:csr");$stmt->execute([':csr'=>$csr]);
    }
    $chats=(int)$stmt->fetchColumn();

    $requestParams = [];
    $visibilitySql = buildCsrRequestVisibilitySql($db, $csr, 'sr', $requestParams, 'live_req_scope');
    $stmt=$db->prepare("SELECT COUNT(*) FROM service_requests sr WHERE sr.job_status_id NOT IN (4,5) AND $visibilitySql");
    foreach($requestParams as $k=>$v){$stmt->bindValue($k,$v,is_int($v)?PDO::PARAM_INT:PDO::PARAM_STR);} $stmt->execute();
    $requests=(int)$stmt->fetchColumn();
    echo json_encode(['success'=>true,'counts'=>['notifications'=>$unread,'visible_chats'=>$chats,'visible_requests'=>$requests,'server_time'=>date('Y-m-d H:i:s')]]);
}catch(Exception $e){echo json_encode(['success'=>false,'message'=>$e->getMessage()]);}
