<?php
// csr/ajax/get_all_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();
}

$page = isset($_POST['page']) ? (int)$_POST['page'] : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

$where = "WHERE n.csr_id = :csr_id AND COALESCE(n.reference_type, '') <> 'announcement'";
$params = [':csr_id' => $_SESSION['csr_id']];

// Apply filters
if (!empty($_POST['type'])) {
    $where .= " AND n.type = :type";
    $params[':type'] = $_POST['type'];
}

if (!empty($_POST['status'])) {
    if ($_POST['status'] == 'unread') {
        $where .= " AND n.is_read = 0";
    } elseif ($_POST['status'] == 'read') {
        $where .= " AND n.is_read = 1";
    }
}

if (!empty($_POST['date_range'])) {
    switch($_POST['date_range']) {
        case 'today':
            $where .= " AND DATE(n.created_at) = CURDATE()";
            break;
        case 'week':
            $where .= " AND YEARWEEK(n.created_at) = YEARWEEK(CURDATE())";
            break;
        case 'month':
            $where .= " AND MONTH(n.created_at) = MONTH(CURDATE()) AND YEAR(n.created_at) = YEAR(CURDATE())";
            break;
    }
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get total count
    $countQuery = "SELECT COUNT(*) as total FROM csr_notifications n $where";
    $stmt = $db->prepare($countQuery);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->execute();
    $total = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Get paginated data
    $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 OFFSET :offset";
    
    $stmt = $db->prepare($query);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Calculate pagination
    $total_pages = ceil($total / $limit);
    $start_page = max(1, $page - 2);
    $end_page = min($total_pages, $page + 2);
    
    echo json_encode([
        'success' => true,
        'notifications' => $notifications,
        'total' => $total,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => $total_pages,
            'start_page' => $start_page,
            'end_page' => $end_page,
            'start' => $offset + 1,
            'end' => min($offset + $limit, $total),
            'total' => $total
        ]
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>