<?php
require_once '../config.php';
require_once '../auth/check_auth.php';

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

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

try {
    // Get ID cards statistics
    $stats = [];
    
    // Total ID cards
    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM id_cards");
    $stmt->execute();
    $stats['total'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Active ID cards
    $stmt = $pdo->prepare("SELECT COUNT(*) as active FROM id_cards WHERE status = 'active'");
    $stmt->execute();
    $stats['active'] = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    
    // Expired ID cards
    $stmt = $pdo->prepare("SELECT COUNT(*) as expired FROM id_cards WHERE status = 'expired' OR expiry_date < CURDATE()");
    $stmt->execute();
    $stats['expired'] = $stmt->fetch(PDO::FETCH_ASSOC)['expired'];
    
    // Expiring soon (within 30 days)
    $stmt = $pdo->prepare("SELECT COUNT(*) as expiring FROM id_cards WHERE status = 'active' AND expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)");
    $stmt->execute();
    $stats['expiring'] = $stmt->fetch(PDO::FETCH_ASSOC)['expiring'];
    
    // Cancelled ID cards
    $stmt = $pdo->prepare("SELECT COUNT(*) as cancelled FROM id_cards WHERE status = 'cancelled'");
    $stmt->execute();
    $stats['cancelled'] = $stmt->fetch(PDO::FETCH_ASSOC)['cancelled'];
    
    // Recent generations (last 30 days)
    $stmt = $pdo->prepare("SELECT COUNT(*) as recent FROM id_cards WHERE generated_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
    $stmt->execute();
    $stats['recent'] = $stmt->fetch(PDO::FETCH_ASSOC)['recent'];
    
    // Cards by type
    $stmt = $pdo->prepare("SELECT card_type, COUNT(*) as count FROM id_cards GROUP BY card_type");
    $stmt->execute();
    $cardTypes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stats['by_type'] = [];
    foreach ($cardTypes as $type) {
        $stats['by_type'][$type['card_type']] = $type['count'];
    }
    
    // Monthly generation stats (last 12 months)
    $stmt = $pdo->prepare("
        SELECT 
            DATE_FORMAT(generated_date, '%Y-%m') as month,
            COUNT(*) as count
        FROM id_cards 
        WHERE generated_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
        GROUP BY DATE_FORMAT(generated_date, '%Y-%m')
        ORDER BY month ASC
    ");
    $stmt->execute();
    $monthlyStats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stats['monthly'] = $monthlyStats;
    
    // Members without ID cards
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as without_cards
        FROM members m
        LEFT JOIN id_cards ic ON m.id = ic.member_id AND ic.status = 'active'
        WHERE ic.id IS NULL
    ");
    $stmt->execute();
    $stats['without_cards'] = $stmt->fetch(PDO::FETCH_ASSOC)['without_cards'];
    
    echo json_encode([
        'success' => true,
        'stats' => $stats
    ]);
    
} catch (Exception $e) {
    error_log("ID Cards Stats Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching statistics: ' . $e->getMessage()
    ]);
}
?>
