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

$notification_id = isset($_POST['notification_id']) ? (int)$_POST['notification_id'] : 0;
$mark_all = isset($_POST['mark_all']) ? (bool)$_POST['mark_all'] : false;

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if ($mark_all) {
        // Mark all as read
        $query = "UPDATE csr_notifications 
                  SET is_read = 1, read_at = NOW() 
                  WHERE csr_id = :csr_id AND COALESCE(reference_type, '') <> 'announcement' AND is_read = 0";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':csr_id', $_SESSION['csr_id']);
        $stmt->execute();
        
        echo json_encode(['success' => true, 'message' => 'All notifications marked as read']);
    } elseif ($notification_id > 0) {
        // Mark single notification as read
        $query = "UPDATE csr_notifications 
                  SET is_read = 1, read_at = NOW() 
                  WHERE id = :id AND csr_id = :csr_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':id', $notification_id);
        $stmt->bindParam(':csr_id', $_SESSION['csr_id']);
        $stmt->execute();
        
        echo json_encode(['success' => true, 'message' => 'Notification marked as read']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid request']);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>