<?php
/**
 * Notification Statistics API Endpoint
 * 
 * Retrieves notification statistics for the current user
 */

// Initialize the session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Include database connection
require_once __DIR__ . '/../../config/db_connect.php';

// Check authentication
if (!isset($_SESSION['admin_id'])) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Authentication required'
    ]);
    exit;
}

$admin_id = $_SESSION['admin_id'];

try {
    // Get total notifications
    $stmt = $conn->prepare("
        SELECT COUNT(*) as total
        FROM notifications n
        INNER JOIN notification_recipients nr ON nr.notification_id = n.id
        WHERE nr.recipient_id = ? AND nr.recipient_type = 'admin'
    ");
    $stmt->bind_param('i', $admin_id);
    $stmt->execute();
    $total_result = $stmt->get_result();
    $total = $total_result->fetch_assoc()['total'];
    
    // Get read notifications
    $stmt = $conn->prepare("
        SELECT COUNT(*) as total
        FROM notifications n
        INNER JOIN notification_recipients nr ON nr.notification_id = n.id
        WHERE nr.recipient_id = ? AND nr.recipient_type = 'admin' AND nr.is_read = 1
    ");
    $stmt->bind_param('i', $admin_id);
    $stmt->execute();
    $read_result = $stmt->get_result();
    $read = $read_result->fetch_assoc()['total'];
    
    // Get unread notifications
    $stmt = $conn->prepare("
        SELECT COUNT(*) as total
        FROM notifications n
        INNER JOIN notification_recipients nr ON nr.notification_id = n.id
        WHERE nr.recipient_id = ? AND nr.recipient_type = 'admin' AND nr.is_read = 0
    ");
    $stmt->bind_param('i', $admin_id);
    $stmt->execute();
    $unread_result = $stmt->get_result();
    $unread = $unread_result->fetch_assoc()['total'];
    
    // Get active assignments
    $stmt = $conn->prepare("
        SELECT COUNT(*) as total
        FROM admin_assignments
        WHERE assigned_to = ? AND status = 'active'
    ");
    $stmt->bind_param('i', $admin_id);
    $stmt->execute();
    $assignments_result = $stmt->get_result();
    $active_assignments = $assignments_result->fetch_assoc()['total'];
    
    // Return statistics
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'data' => [
            'total' => (int)$total,
            'read' => (int)$read,
            'unread' => (int)$unread,
            'active_assignments' => (int)$active_assignments
        ]
    ]);
} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Error retrieving notification statistics: ' . $e->getMessage()
    ]);
}
