<?php
// csr/ajax/get_notifications.php
require_once '../../config/database.php';
session_start();

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

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

$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$get_unread_only = isset($_GET['unread_only']) ? (bool)$_GET['unread_only'] : false;

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $where = "WHERE n.csr_id = :csr_id AND COALESCE(n.reference_type, '') <> 'announcement'";
    $params = [':csr_id' => $_SESSION['csr_id']];
    
    if ($get_unread_only) {
        $where .= " AND n.is_read = 0";
    }
    
    // Get notifications
    $query = "SELECT n.*, 
              CONCAT(cu.first_name, ' ', cu.last_name) as created_by_name
              FROM csr_notifications n
              LEFT JOIN csr_users cu ON n.created_by = cu.id
              $where
              ORDER BY n.created_at DESC
              LIMIT :limit";
    
    $stmt = $db->prepare($query);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get unread count
    $query = "SELECT COUNT(*) as count FROM csr_notifications 
              WHERE csr_id = :csr_id AND is_read = 0 AND COALESCE(reference_type, '') <> 'announcement'";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':csr_id', $_SESSION['csr_id']);
    $stmt->execute();
    $unread_count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    echo json_encode([
        'success' => true,
        'notifications' => $notifications,
        'unread_count' => $unread_count
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>