<?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 filters
    $status = $_GET['status'] ?? '';
    $type = $_GET['type'] ?? '';
    $search = $_GET['search'] ?? '';
    $page = (int)($_GET['page'] ?? 1);
    $limit = (int)($_GET['limit'] ?? 50);
    $offset = ($page - 1) * $limit;
    
    // Build query
    $query = "SELECT 
                ic.id,
                ic.card_number,
                ic.card_type,
                ic.status,
                ic.issue_date,
                ic.expiry_date,
                ic.generated_date,
                ic.template_used,
                ic.qr_code_included,
                m.first_name,
                m.last_name,
                m.kso_id,
                m.photo_url,
                CONCAT(m.first_name, ' ', m.last_name) as member_name,
                m.kso_id as member_id
              FROM id_cards ic
              LEFT JOIN members m ON ic.member_id = m.id
              WHERE 1=1";
    
    $params = [];
    
    // Apply filters
    if (!empty($status)) {
        $query .= " AND ic.status = ?";
        $params[] = $status;
    }
    
    if (!empty($type)) {
        $query .= " AND ic.card_type = ?";
        $params[] = $type;
    }
    
    if (!empty($search)) {
        $query .= " AND (CONCAT(m.first_name, ' ', m.last_name) LIKE ? OR m.kso_id LIKE ? OR ic.card_number LIKE ?)";
        $searchTerm = "%$search%";
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    }
    
    // Get total count
    $countQuery = "SELECT COUNT(*) as total FROM ($query) as countQuery";
    $countStmt = $pdo->prepare($countQuery);
    $countStmt->execute($params);
    $totalRecords = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Add pagination
    $query .= " ORDER BY ic.generated_date DESC LIMIT ? OFFSET ?";
    $params[] = $limit;
    $params[] = $offset;
    
    // Execute main query
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $cards = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Process cards data
    $processedCards = [];
    foreach ($cards as $card) {
        $processedCards[] = [
            'id' => $card['id'],
            'card_number' => $card['card_number'],
            'card_type' => ucfirst(str_replace('_', ' ', $card['card_type'])),
            'status' => $card['status'],
            'issue_date' => $card['issue_date'],
            'expiry_date' => $card['expiry_date'],
            'generated_date' => $card['generated_date'],
            'template_used' => $card['template_used'],
            'qr_code_included' => $card['qr_code_included'],
            'member_name' => $card['member_name'],
            'member_id' => $card['member_id'],
            'photo_url' => $card['photo_url'],
            'is_expired' => (strtotime($card['expiry_date']) < time()),
            'days_until_expiry' => (strtotime($card['expiry_date']) - time()) / (24 * 60 * 60)
        ];
    }
    
    echo json_encode([
        'success' => true,
        'cards' => $processedCards,
        'pagination' => [
            'current_page' => $page,
            'per_page' => $limit,
            'total' => $totalRecords,
            'pages' => ceil($totalRecords / $limit)
        ]
    ]);
    
} catch (Exception $e) {
    error_log("ID Cards Fetch Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching ID cards: ' . $e->getMessage()
    ]);
}
?>
