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

if (!isset($_SESSION['admin_id'])) {
    header('Location: ../login.php');
    exit();
}

$ids = $_GET['ids'] ?? '';

if (empty($ids)) {
    die('No cards selected');
}

try {
    $card_ids = explode(',', $ids);
    $placeholders = str_repeat('?,', count($card_ids) - 1) . '?';
    
    // Get card details
    $stmt = $pdo->prepare("
        SELECT 
            ic.*,
            m.first_name,
            m.last_name,
            m.kso_id,
            CONCAT(m.first_name, ' ', m.last_name) as member_name
        FROM id_cards ic
        LEFT JOIN members m ON ic.member_id = m.id
        WHERE ic.id IN ($placeholders)
    ");
    
    $stmt->execute($card_ids);
    $cards = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($cards)) {
        die('No cards found');
    }
    
    // Create a ZIP file
    $zip = new ZipArchive();
    $zip_filename = 'id_cards_' . date('Y-m-d_H-i-s') . '.zip';
    $zip_path = '../../../uploads/temp/' . $zip_filename;
    
    // Create temp directory if it doesn't exist
    if (!is_dir('../../../uploads/temp/')) {
        mkdir('../../../uploads/temp/', 0755, true);
    }
    
    if ($zip->open($zip_path, ZipArchive::CREATE) !== TRUE) {
        die('Cannot create ZIP file');
    }
    
    foreach ($cards as $card) {
        $card_html = generateCardHTML($card);
        $filename = "id_card_{$card['card_number']}.html";
        $zip->addFromString($filename, $card_html);
    }
    
    $zip->close();
    
    // Set headers for download
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . $zip_filename . '"');
    header('Content-Length: ' . filesize($zip_path));
    
    // Output the file
    readfile($zip_path);
    
    // Clean up
    unlink($zip_path);
    
} catch (Exception $e) {
    error_log("Bulk Download Error: " . $e->getMessage());
    die('Error creating download: ' . $e->getMessage());
}

function generateCardHTML($card) {
    $member_name = $card['member_name'];
    $photo_url = $card['photo_url'] ?? 'dist/img/default-user.png';
    
    $qr_code_html = $card['qr_code_included'] ? "<div class='qr-code'><i class='fas fa-qrcode'></i></div>" : '';
    
    return "
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset='utf-8'>
        <title>ID Card - {$member_name}</title>
        <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css'>
        <style>
            body { 
                margin: 0; 
                padding: 20px; 
                font-family: Arial, sans-serif; 
                background: #f5f5f5;
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 100vh;
            }
            .id-card {
                width: 320px;
                height: 200px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                border-radius: 15px;
                padding: 20px;
                color: white;
                position: relative;
                box-shadow: 0 8px 25px rgba(0,0,0,0.15);
            }
            .card-header {
                text-align: center;
                font-size: 12px;
                font-weight: bold;
                margin-bottom: 10px;
            }
            .member-info {
                display: flex;
                align-items: center;
                gap: 15px;
            }
            .member-photo {
                width: 60px;
                height: 60px;
                border-radius: 50%;
                background: #fff;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24px;
                color: #667eea;
            }
            .member-details {
                flex: 1;
            }
            .member-name {
                font-size: 16px;
                font-weight: bold;
                margin-bottom: 5px;
            }
            .member-id {
                font-size: 12px;
                opacity: 0.9;
            }
            .card-footer {
                position: absolute;
                bottom: 10px;
                right: 15px;
                font-size: 10px;
                opacity: 0.8;
            }
            .qr-code {
                position: absolute;
                bottom: 10px;
                left: 15px;
                width: 30px;
                height: 30px;
                background: white;
                border-radius: 4px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 12px;
                color: #333;
            }
        </style>
    </head>
    <body>
        <div class='id-card'>
            <div class='card-header'>
                KUKI STUDENTS' ORGANISATION<br>
                CHANDIGARH
            </div>
            <div class='member-info'>
                <div class='member-photo'>
                    <i class='fas fa-user'></i>
                </div>
                <div class='member-details'>
                    <div class='member-name'>{$member_name}</div>
                    <div class='member-id'>ID: {$card['kso_id']}</div>
                    <div class='member-id'>Card: {$card['card_number']}</div>
                    <div class='member-id'>Type: " . ucfirst(str_replace('_', ' ', $card['card_type'])) . "</div>
                </div>
            </div>
            {$qr_code_html}
            <div class='card-footer'>
                Valid Until: " . date('M Y', strtotime($card['expiry_date'])) . "
            </div>
        </div>
    </body>
    </html>";
}
?>
