<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_admin.php');

date_default_timezone_set('Africa/Lagos');

// Auto-delete expired used codes 
if (!isset($_SESSION['codes_cleaned'])) {
    try {
        $DBH->exec("DELETE FROM exam_access_codes WHERE is_used = TRUE AND expiry_date < NOW() - INTERVAL 1 DAY");
        $_SESSION['codes_cleaned'] = true;
    } catch (Exception $e) {
        error_log("Error cleaning codes: " . $e->getMessage());
    }
}

// Check for required columns
$createdByColumnExists = false;
$batchIdColumnExists = false;
try {
    $stmt = $DBH->query("SHOW COLUMNS FROM exam_access_codes LIKE 'created_by'");
    $createdByColumnExists = $stmt->rowCount() > 0;
    
    $stmt = $DBH->query("SHOW COLUMNS FROM exam_access_codes LIKE 'batch_id'");
    $batchIdColumnExists = $stmt->rowCount() > 0;
} catch (Exception $e) {
    error_log("Error checking columns: " . $e->getMessage());
}

// Handle form submissions
$message = '';
$error = '';
$generatedCodes = [];
$selectedCodes = [];
$searchResults = [];
$viewBatch = null;

// Generate Access Codes
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate'])) {
    $quantity = (int)$_POST['quantity'];
    $prefix = !empty($_POST['prefix']) ? trim($_POST['prefix']) : 'EXA'; // Default prefix
    
    // NEW: Get activation and expiry dates
    $activationDate = !empty($_POST['activation_date']) ? $_POST['activation_date'] : date('Y-m-d H:i:s');
    $expiryDate = !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : date('Y-m-d H:i:s', strtotime("+10 hours"));
    
    // Convert to proper datetime format
    $activationDate = date('Y-m-d H:i:s', strtotime($activationDate));
    $expiryDate = date('Y-m-d H:i:s', strtotime($expiryDate));
    
    // Validate dates
    if (strtotime($activationDate) > strtotime($expiryDate)) {
        $error = "Activation date cannot be after expiry date!";
    } else {
        // Validate and clean prefix
        $prefix = preg_replace('/[^A-Za-z]/', '', $prefix); // Remove non-letters
        $prefix = strtoupper($prefix); // Convert to uppercase
        
        // Ensure prefix is exactly 3 characters
        if (strlen($prefix) > 3) {
            $prefix = substr($prefix, 0, 3); // Truncate to 3 chars
        } elseif (strlen($prefix) < 3) {
            // Pad with X if less than 3 chars
            $prefix = str_pad($prefix, 3, 'X', STR_PAD_RIGHT);
        }
        
        $adminUsername = isset($_SESSION['admin']['username']) ? $_SESSION['admin']['username'] : 'System';
        $batchId = uniqid();

        try {
            $DBH->beginTransaction();
            
            $codes = [];
            $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
            $alphabetLength = strlen($alphabet);
            
            // Keep track of generated codes to avoid duplicates in this batch
            $generatedInBatch = [];
            
            for ($i = 0; $i < $quantity; $i++) {
                // Generate unique 6-character code for this batch
                $attempts = 0;
                do {
                    // Generate 6 random uppercase alphabets
                    $randomPart = '';
                    for ($j = 0; $j < 6; $j++) {
                        $randomPart .= $alphabet[random_int(0, $alphabetLength - 1)];
                    }
                    
                    $code = $prefix . $randomPart; // Total 9 characters
                    $attempts++;
                    
                    // Check if this code was already generated in current batch
                    $alreadyGenerated = in_array($code, $generatedInBatch);
                    
                    // Also check if code exists in database (optional safety check)
                    $stmt = $DBH->prepare("SELECT COUNT(*) as count FROM exam_access_codes WHERE access_code = ?");
                    $stmt->execute([$code]);
                    $existsInDB = $stmt->fetch(PDO::FETCH_ASSOC)['count'] > 0;
                    
                } while (($alreadyGenerated || $existsInDB) && $attempts < 10);
                
                // Add to batch tracking
                $generatedInBatch[] = $code;
                
                $startTime = date('Y-m-d H:i:s');
                
                if ($batchIdColumnExists) {
                    // Check if activation_date and expiry_date columns exist
                    $stmt = $DBH->query("SHOW COLUMNS FROM exam_access_codes LIKE 'activation_date'");
                    $hasActivationDate = $stmt->rowCount() > 0;
                    
                    $stmt = $DBH->query("SHOW COLUMNS FROM exam_access_codes LIKE 'expiry_date'");
                    $hasExpiryDate = $stmt->rowCount() > 0;
                    
                    if ($hasActivationDate && $hasExpiryDate) {
                        $stmt = $DBH->prepare("
                            INSERT INTO exam_access_codes 
                            (access_code, start_time, end_time, activation_date, expiry_date, created_by, batch_id) 
                            VALUES (?, ?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([$code, $startTime, $expiryDate, $activationDate, $expiryDate, $adminUsername, $batchId]);
                    } else {
                        $stmt = $DBH->prepare("
                            INSERT INTO exam_access_codes 
                            (access_code, start_time, end_time, created_by, batch_id) 
                            VALUES (?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([$code, $startTime, $expiryDate, $adminUsername, $batchId]);
                    }
                } else {
                    $stmt = $DBH->prepare("
                        INSERT INTO exam_access_codes 
                        (access_code, start_time, end_time, created_by) 
                        VALUES (?, ?, ?, ?)
                    ");
                    $adminUsername = $createdByColumnExists ? $adminUsername : null;
                    $stmt->execute([$code, $startTime, $expiryDate, $adminUsername]);
                }
                
                $codes[] = [
                    'code' => $code,
                    'start_time' => $startTime,
                    'end_time' => $expiryDate,
                    'activation_date' => $activationDate,
                    'expiry_date' => $expiryDate,
                    'created_by' => $adminUsername,
                    'batch_id' => $batchId,
                    'prefix' => $prefix
                ];
            }
            
            $DBH->commit();
            $message = "Successfully generated {$quantity} access codes (Batch: " . substr($batchId, 0, 8) . ")!";
            $generatedCodes = $codes;
        } catch (Exception $e) {
            $DBH->rollBack();
            $error = "Error generating codes: " . $e->getMessage();
            error_log("Code generation error: " . $e->getMessage());
        }
    }
}

// Handle search
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search'])) {
    $searchTerm = trim($_POST['search_term']);
    $searchBy = $_POST['search_by'];
    
    try {
        $query = "SELECT * FROM exam_access_codes WHERE ";
        $params = [];
        
        switch ($searchBy) {
            case 'code':
                $query .= "access_code LIKE ?";
                $params[] = "%{$searchTerm}%";
                break;
            case 'batch':
                if ($batchIdColumnExists) {
                    $query .= "batch_id LIKE ?";
                    $params[] = "%{$searchTerm}%";
                } else {
                    $query .= "1=0"; // No results if batch_id doesn't exist
                }
                break;
            case 'date':
                $query .= "DATE(start_time) LIKE ?";
                $params[] = "%{$searchTerm}%";
                break;
            case 'status':
                if (strtolower($searchTerm) === 'used') {
                    $query .= "is_used = TRUE";
                } else {
                    $query .= "is_used = FALSE AND expiry_date >= NOW()";
                }
                break;
            default:
                $query .= "(access_code LIKE ? OR " . ($batchIdColumnExists ? "batch_id LIKE ?" : "1=0") . " OR DATE(start_time) LIKE ?)";
                $params = ["%{$searchTerm}%", "%{$searchTerm}%", "%{$searchTerm}%"];
        }
        
        $query .= " ORDER BY start_time DESC";
        $stmt = $DBH->prepare($query);
        $stmt->execute($params);
        $searchResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($searchResults)) {
            $message = "No codes found matching your criteria.";
        }
    } catch (Exception $e) {
        $error = "Error searching codes: " . $e->getMessage();
        error_log("Search error: " . $e->getMessage());
    }
}

// Handle view batch request
if (isset($_GET['batch'])) {
    $batchId = $_GET['batch'];
    try {
        $stmt = $DBH->prepare("SELECT * FROM exam_access_codes WHERE batch_id = ? ORDER BY start_time DESC");
        $stmt->execute([$batchId]);
        $viewBatch = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $error = "Error loading batch: " . $e->getMessage();
        error_log("Batch view error: " . $e->getMessage());
    }
}

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    $action = $_POST['bulk_action'];
    $selected = isset($_POST['selected_codes']) ? (array)$_POST['selected_codes'] : [];
    
    try {
        if ($action === 'delete' && !empty($selected)) {
            $placeholders = implode(',', array_fill(0, count($selected), '?'));
            $stmt = $DBH->prepare("DELETE FROM exam_access_codes WHERE id IN ($placeholders)");
            $stmt->execute($selected);
            $message = "Deleted " . count($selected) . " codes successfully!";
        } elseif ($action === 'print' && !empty($selected)) {
            $placeholders = implode(',', array_fill(0, count($selected), '?'));
            $stmt = $DBH->prepare("SELECT * FROM exam_access_codes WHERE id IN ($placeholders)");
            $stmt->execute($selected);
            $selectedCodes = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (Exception $e) {
        $error = "Error processing bulk action: " . $e->getMessage();
        error_log("Bulk action error: " . $e->getMessage());
    }
}

// Handle individual code deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_code'])) {
    $codeId = $_POST['code_id'] ?? null;
    if ($codeId) {
        try {
            $stmt = $DBH->prepare("DELETE FROM exam_access_codes WHERE id = ?");
            $stmt->execute([$codeId]);
            $message = "Code deleted successfully!";
        } catch (Exception $e) {
            $error = "Error deleting code: " . $e->getMessage();
            error_log("Delete code error: " . $e->getMessage());
        }
    }
}

// Get daily batches
$dailyBatches = [];
try {
    $query = "SELECT 
        DATE(start_time) as gen_date, 
        " . ($batchIdColumnExists ? "batch_id," : "'N/A' as batch_id,") . "
        COUNT(*) as code_count,
        " . ($createdByColumnExists ? "created_by" : "'System' as created_by") . "
    FROM exam_access_codes
    GROUP BY DATE(start_time)" . ($batchIdColumnExists ? ", batch_id, created_by" : "") . "
    ORDER BY DATE(start_time) DESC" . ($batchIdColumnExists ? ", batch_id DESC" : "") . "
    LIMIT 30";
    
    $dailyBatches = $DBH->query($query)->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log("Error fetching batches: " . $e->getMessage());
}

// Handle PDF download
if (isset($_GET['download_pdf']) && isset($_GET['batch'])) {
    $batchId = $_GET['batch'];
    try {
        // Validate batch ID
        if (empty($batchId)) {
            throw new Exception("Invalid batch ID.");
        }

        // Fetch codes for the batch
        $stmt = $DBH->prepare("SELECT * FROM exam_access_codes WHERE batch_id = ? ORDER BY start_time ASC");
        $stmt->execute([$batchId]);
        $codes = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($codes)) {
            throw new Exception("No codes found for batch: " . htmlspecialchars($batchId));
        }

        // Check if TCPDF is available
        if (!file_exists('source/tcpdf/tcpdf.php')) {
            throw new Exception("TCPDF library not found at source/tcpdf/tcpdf.php");
        }

        // Include TCPDF
        require_once('source/tcpdf/tcpdf.php');

        // Create new PDF document
        $pdf = new TCPDF('L', 'mm', 'A4', true, 'UTF-8', false); // Landscape A4

        // Set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('BKMS-BLC');
        $pdf->SetTitle('Access Codes - Batch ' . htmlspecialchars($batchId));
        $pdf->SetSubject('Access Codes');
        $pdf->SetKeywords('Access Codes, BKMS-BLC, Batch ' . htmlspecialchars($batchId));

        // Remove header and footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

        // Set margins for better space utilization
        $pdf->SetMargins(5, 5, 5); // Small margins for A4 landscape
        $pdf->SetAutoPageBreak(TRUE, 5);

        // Add a page
        $pdf->AddPage();

        // NEW: Calculate layout for 84 codes per page
        // A4 Landscape: 297mm x 210mm
        // After margins: 287mm x 200mm usable space
        // We'll create a 7x12 grid (84 codes)
        $cols = 7;  // 7 columns
        $rows = 12; // 12 rows
        $cellWidth = 40; // mm
        $cellHeight = 24; // mm
        
        $html = '<style>
            .code-container {
                width: ' . $cellWidth . 'mm;
                height: ' . $cellHeight . 'mm;
                border: 0.5px solid #ccc;
                text-align: center;
                padding: 2mm;
                box-sizing: border-box;
                page-break-inside: avoid;
                margin: 0;
                float: left;
            }
            .access-code {
                font-size: 14pt;
                font-weight: bold;
                margin: 1mm 0;
                line-height: 1.2;
            }
            .date-info {
                font-size: 6pt;
                line-height: 1.1;
                margin: 0.5mm 0;
            }
            .clearfix {
                clear: both;
            }
        </style>';
        
        $html .= '<div style="width: 100%;">';
        
        $count = 0;
        foreach ($codes as $code) {
            if ($count % $cols == 0 && $count > 0) {
                // Start new row
                $html .= '<div class="clearfix"></div>';
            }
            
            // Use activation_date and expiry_date if available, otherwise use start_time and end_time
            $activationDate = isset($code['activation_date']) && !empty($code['activation_date']) 
                ? date('d/m/y', strtotime($code['activation_date']))
                : date('d/m/y', strtotime($code['start_time']));
            
            $expiryDate = isset($code['expiry_date']) && !empty($code['expiry_date'])
                ? date('d/m/y', strtotime($code['expiry_date']))
                : date('d/m/y', strtotime($code['end_time']));
            
            $html .= '
            <div class="code-container">
                <div class="access-code">' . htmlspecialchars($code['access_code']) . '</div>
                <div class="date-info">Date of Activation: ' . $activationDate . '</div>
                <div class="date-info">Valid till: ' . $expiryDate . '</div>
            </div>';
            
            $count++;
            
            // If we've reached 84 codes, create a new page
            if ($count % ($cols * $rows) == 0 && $count < count($codes)) {
                $html .= '</div>';
                $pdf->writeHTML($html, true, false, true, false, '');
                $pdf->AddPage();
                $html = '<style>
                    .code-container {
                        width: ' . $cellWidth . 'mm;
                        height: ' . $cellHeight . 'mm;
                        border: 0.5px solid #ccc;
                        text-align: center;
                        padding: 2mm;
                        box-sizing: border-box;
                        page-break-inside: avoid;
                        margin: 0;
                        float: left;
                    }
                    .access-code {
                        font-size: 14pt;
                        font-weight: bold;
                        margin: 1mm 0;
                        line-height: 1.2;
                    }
                    .date-info {
                        font-size: 6pt;
                        line-height: 1.1;
                        margin: 0.5mm 0;
                    }
                    .clearfix {
                        clear: both;
                    }
                </style>';
                $html .= '<div style="width: 100%;">';
            }
        }
        
        $html .= '<div class="clearfix"></div></div>';
        
        // Write HTML to PDF
        $pdf->writeHTML($html, true, false, true, false, '');

        // Output PDF
        $pdf->Output('access_codes_' . htmlspecialchars($batchId) . '.pdf', 'D');
        exit;
    } catch (Exception $e) {
        $error = "Error generating PDF: " . htmlspecialchars($e->getMessage());
        error_log("PDF generation error: " . $e->getMessage());
    }
}
?>

<?php
// ... [Previous code remains the same until the print section] ...
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>BKMS-BLC - Access Code Generator</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .code-card {
            width: 45%; 
            float: left; 
            margin: 10px; 
            padding: 15px;
            border: 2px dashed #ccc;
            border-radius: 5px;
            page-break-inside: avoid;
        }
        
        /* OPTIMIZED: Print styles for maximum codes on A4 landscape */
        @media print {
            @page {
                size: A4 landscape;
                margin: 3mm;
            }
            
            body * { 
                visibility: hidden; 
                margin: 0 !important;
                padding: 0 !important;
            }
            
            .print-section, .print-section * { 
                visibility: visible; 
            }
            
            .print-section { 
                position: absolute; 
                left: 0; 
                top: 0; 
                width: 100%; 
                height: 100%;
                margin: 0 !important;
                padding: 0 !important;
            }
            
            .no-print { 
                display: none !important; 
            }
            
            /* Ultra-compact code block for maximum density */
            .code-block {
                width: 33mm;
                height: 15mm;
                border: 0.3mm solid #000;
                text-align: center;
                padding: 0.5mm;
                box-sizing: border-box;
                page-break-inside: avoid;
                margin: 0.2mm;
                float: left;
                font-family: Arial, sans-serif;
                overflow: hidden;
            }
            
            /* Grid container - much denser */
            .print-grid {
                display: block;
                width: 100%;
                height: 100%;
                margin: 0;
                padding: 0;
            }
            
            /* VERY bold access code */
            .access-code-bold {
                font-size: 10pt !important;
                font-weight: 900 !important;
                margin: 0.2mm 0;
                line-height: 1;
                letter-spacing: 0.5pt;
            }
            
            /* EXTREMELY tiny text */
            .tiny-text {
                font-size: 4pt !important;
                line-height: 1;
                margin: 0.1mm 0;
                font-family: Arial, sans-serif;
            }
            
            /* Page container */
            .page-container {
                width: 290mm;
                height: 200mm;
                margin: 0 auto;
                padding: 0;
            }
        }
        
        /* Screen preview */
        @media screen {
            .code-block {
                width: 33mm;
                height: 15mm;
                border: 1px solid #000;
                text-align: center;
                padding: 1mm;
                box-sizing: border-box;
                margin: 0.5mm;
                float: left;
                font-family: Arial, sans-serif;
                background: white;
            }
            
            .access-code-bold {
                font-size: 10pt;
                font-weight: 900;
                margin: 0.5mm 0;
                line-height: 1;
            }
            
            .tiny-text {
                font-size: 4pt;
                line-height: 1;
                margin: 0.2mm 0;
                font-family: Arial, sans-serif;
            }
            
            .print-grid {
                width: 210mm; /* A4 width in landscape */
                margin: 0 auto;
                background: #f5f5f5;
                padding: 2mm;
                border: 1px solid #ccc;
            }
            
            .page-container {
                width: 210mm;
                min-height: 148mm; /* A4 height in landscape */
                margin: 0 auto;
                background: white;
                box-shadow: 0 0 10px rgba(0,0,0,0.1);
            }
        }
        
        .batch-card {
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .batch-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .action-buttons .btn {
            margin-right: 5px;
            margin-bottom: 5px;
        }
        
        .prefix-example {
            font-size: 0.875rem;
            color: #6c757d;
        }
        
        .validity-note {
            background-color: #e7f3ff;
            border-left: 4px solid #0d6efd;
            padding: 10px;
            margin: 15px 0;
            border-radius: 4px;
        }
        
        /* Clearfix for floated elements */
        .clearfix {
            clear: both;
        }
    </style>
</head>
<body>
<?php include('admin_nav.php'); ?>

<div class="container py-4">
    <!-- Back Links -->
    <div class="row mb-4">
        <div class="col-12 text-center">
            <a href="../main.php" class="btn btn-outline-secondary me-2">
                <i class="bi bi-arrow-left"></i> Back to Admin Dashboard
            </a>
            <a href="cbt_admin_home.php" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i> Back to CBT Dashboard
            </a>
        </div>
    </div>

    <!-- Generation Form -->
    <div class="row mb-4">
        <div class="col-md-10 mx-auto">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h4 class="mb-0"><i class="bi bi-key"></i> Generate Access Codes</h4>
                </div>
                <div class="card-body">
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
                    <?php endif; ?>
                    <?php if ($message): ?>
                        <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
                    <?php endif; ?>
                    
                    <form method="POST">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label for="quantity" class="form-label">Number of Codes</label>
                                <input type="number" class="form-control" id="quantity" name="quantity" min="1" max="1000" value="200" required>
                                <div class="form-text">Recommended: 200-300 codes for high-density printing</div>
                            </div>
                            
                            <div class="col-md-4">
                                <label for="prefix" class="form-label">Code Prefix (3 letters)</label>
                                <input type="text" class="form-control" id="prefix" name="prefix" maxlength="3" 
                                       pattern="[A-Za-z]{3}" title="Exactly 3 letters" 
                                       placeholder="EXA" value="EXA" required>
                                <div class="prefix-example mt-1">
                                    <small>Example: EXA + 6 random letters = EXAABCDEF (9 characters total)</small>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <label for="activation_date" class="form-label">Activation Date & Time</label>
                                <input type="datetime-local" class="form-control" id="activation_date" 
                                       name="activation_date" 
                                       value="<?php echo date('Y-m-d\TH:i'); ?>"
                                       min="<?php echo date('Y-m-d\TH:i'); ?>"
                                       required>
                                <div class="form-text">When the code becomes active</div>
                            </div>
                            
                            <div class="col-md-4">
                                <label for="expiry_date" class="form-label">Expiry Date & Time</label>
                                <input type="datetime-local" class="form-control" id="expiry_date" 
                                       name="expiry_date" 
                                       value="<?php echo date('Y-m-d\TH:i', strtotime('+10 hours')); ?>"
                                       min="<?php echo date('Y-m-d\TH:i'); ?>"
                                       required>
                                <div class="form-text">When the code expires</div>
                            </div>
                            
                            <div class="col-md-8">
                                <div class="alert alert-info">
                                    <i class="bi bi-printer"></i> 
                                    <strong>Print Optimization:</strong> 
                                    <ul class="mb-0">
                                        <li>Ultra-compact layout for maximum codes per page</li>
                                        <li>Each code block: 33mm × 15mm</li>
                                        <li>Approximately 200+ codes per A4 landscape page</li>
                                        <li>Bold access codes with tiny date text</li>
                                    </ul>
                                </div>
                            </div>
                            
                            <div class="col-12">
                                <button type="submit" name="generate" class="btn btn-success">
                                    <i class="bi bi-plus-circle"></i> Generate Codes
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Daily Batches -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h4 class="mb-0"><i class="bi bi-collection"></i> Recent Code Batches</h4>
                </div>
                <div class="card-body">
                    <div class="row">
                        <?php foreach ($dailyBatches as $batch): ?>
                            <div class="col-md-4 mb-3">
                                <div class="card batch-card h-100">
                                    <div class="card-body">
                                        <h5 class="card-title">
                                            <?php echo date('M j, Y', strtotime($batch['gen_date'])); ?>
                                        </h5>
                                        <p class="card-text">
                                            <strong>Batch ID:</strong> <?php echo htmlspecialchars(substr($batch['batch_id'], 0, 8)); ?><br>
                                            <strong>Codes:</strong> <?php echo htmlspecialchars($batch['code_count']); ?><br>
                                            <strong>Generated by:</strong> <?php echo htmlspecialchars($batch['created_by']); ?>
                                        </p>
                                        <div class="action-buttons">
                                            <a href="?batch=<?php echo urlencode($batch['batch_id']); ?>" class="btn btn-sm btn-outline-success">
                                                <i class="bi bi-eye"></i> View
                                            </a>
                                            <a href="?batch=<?php echo urlencode($batch['batch_id']); ?>&print=1" class="btn btn-sm btn-outline-primary">
                                                <i class="bi bi-printer"></i> Print
                                            </a>
                                            <a href="?batch=<?php echo urlencode($batch['batch_id']); ?>&download_pdf=1" class="btn btn-sm btn-outline-info">
                                                <i class="bi bi-download"></i> PDF
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- View Batch Section -->
    <?php if (!empty($viewBatch)): ?>
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h4 class="mb-0">
                            <i class="bi bi-collection"></i> Viewing Batch: <?php echo htmlspecialchars(substr($viewBatch[0]['batch_id'], 0, 8)); ?>
                            <a href="generate_access_key.php" class="btn btn-sm btn-light float-end">
                                <i class="bi bi-x"></i> Close
                            </a>
                        </h4>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info mb-3">
                            <i class="bi bi-clock"></i> 
                            <strong>Validity Information:</strong> Check activation and expiry dates for each code
                        </div>
                        
                        <form method="POST" id="bulkForm">
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <thead class="table-success">
                                        <tr>
                                            <th width="40">
                                                <input type="checkbox" id="selectAllBatch">
                                            </th>
                                            <th>Access Code</th>
                                            <th>Activation Date</th>
                                            <th>Expiry Date</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($viewBatch as $code): ?>
                                            <?php
                                            // Determine status based on activation and expiry dates
                                            $now = time();
                                            $activationTime = isset($code['activation_date']) && !empty($code['activation_date']) 
                                                ? strtotime($code['activation_date']) 
                                                : strtotime($code['start_time']);
                                            
                                            $expiryTime = isset($code['expiry_date']) && !empty($code['expiry_date'])
                                                ? strtotime($code['expiry_date'])
                                                : strtotime($code['end_time']);
                                            
                                            if ($code['is_used']) {
                                                $status = '<span class="badge bg-secondary">Used</span>';
                                            } elseif ($now < $activationTime) {
                                                $status = '<span class="badge bg-warning">Inactive</span>';
                                            } elseif ($now > $expiryTime) {
                                                $status = '<span class="badge bg-danger">Expired</span>';
                                            } else {
                                                $status = '<span class="badge bg-success">Active</span>';
                                            }
                                            
                                            // Format dates for display
                                            $activationDate = isset($code['activation_date']) && !empty($code['activation_date'])
                                                ? date('M j, Y h:i A', strtotime($code['activation_date']))
                                                : date('M j, Y h:i A', strtotime($code['start_time']));
                                            
                                            $expiryDate = isset($code['expiry_date']) && !empty($code['expiry_date'])
                                                ? date('M j, Y h:i A', strtotime($code['expiry_date']))
                                                : date('M j, Y h:i A', strtotime($code['end_time']));
                                            ?>
                                            <tr>
                                                <td>
                                                    <input type="checkbox" name="selected_codes[]" value="<?php echo htmlspecialchars($code['id']); ?>">
                                                </td>
                                                <td><code><?php echo htmlspecialchars($code['access_code']); ?></code></td>
                                                <td><?php echo $activationDate; ?></td>
                                                <td><?php echo $expiryDate; ?></td>
                                                <td><?php echo $status; ?></td>
                                                <td>
                                                    <div class="btn-group">
                                                        <form method="POST" class="d-inline">
                                                            <input type="hidden" name="selected_codes[]" value="<?php echo htmlspecialchars($code['id']); ?>">
                                                            <button type="submit" name="bulk_action" value="print" class="btn btn-sm btn-outline-primary">
                                                                <i class="bi bi-printer"></i>
                                                            </button>
                                                        </form>
                                                        <form method="POST" class="d-inline">
                                                            <input type="hidden" name="code_id" value="<?php echo htmlspecialchars($code['id']); ?>">
                                                            <button type="submit" name="delete_code" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this code?')">
                                                                <i class="bi bi-trash"></i>
                                                            </button>
                                                        </form>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class="mt-3">
                                <select class="form-select d-inline-block" name="bulk_action" style="width: auto;">
                                    <option value="">Bulk Actions</option>
                                    <option value="print">Print Selected</option>
                                    <option value="delete">Delete Selected</option>
                                </select>
                                <button type="submit" class="btn btn-success ms-2">
                                    <i class="bi bi-check-circle"></i> Apply
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
    
    <!-- Printable Section -->
    <?php if (!empty($generatedCodes) || !empty($selectedCodes) || isset($_GET['print'])): ?>
        <?php 
        $codesToPrint = [];
        if (!empty($generatedCodes)) {
            $codesToPrint = $generatedCodes;
        } elseif (!empty($selectedCodes)) {
            $codesToPrint = $selectedCodes;
        } elseif (!empty($viewBatch)) {
            $codesToPrint = $viewBatch;
        }
        ?>
        
        <?php if (!empty($codesToPrint)): ?>
            <div class="print-section">
                <div class="no-print mb-4">
                    <div class="alert alert-info">
                        <h5><i class="bi bi-printer"></i> High-Density Print Preview</h5>
                        <p class="mb-2">
                            <strong>Layout optimized for maximum codes per page:</strong>
                        </p>
                        <ul class="mb-2">
                            <li>Paper Size: <strong>A4 Landscape</strong></li>
                            <li>Codes per page: <strong>Approximately 200-250+</strong></li>
                            <li>Each code block: <strong>33mm × 15mm</strong></li>
                            <li>Margins: <strong>Minimal (3mm)</strong></li>
                        </ul>
                        <p class="mb-0 text-success">
                            <i class="bi bi-lightbulb"></i> 
                            <strong>Tip:</strong> Adjust your printer settings to "Borderless" or "Minimal Margins" for best results
                        </p>
                    </div>
                </div>
                
                <!-- ULTRA-COMPACT: High-density grid for maximum codes -->
                <div class="print-grid">
                    <?php 
                    // Calculate optimal layout
                    $codesPerRow = 7; // Increased from 6
                    $rowsPerPage = 30; // Increased from 12
                    $codesPerPage = $codesPerRow * $rowsPerPage; // ~210 codes per page
                    
                    $totalPages = ceil(count($codesToPrint) / $codesPerPage);
                    
                    for ($page = 1; $page <= $totalPages; $page++): 
                    ?>
                        <div class="page-container">
                            <div style="width: 100%; height: 100%; padding: 0;">
                                <?php 
                                $pageStart = ($page - 1) * $codesPerPage;
                                $pageEnd = min($pageStart + $codesPerPage, count($codesToPrint));
                                ?>
                                
                                <?php for ($i = $pageStart; $i < $pageEnd; $i++): 
                                    $code = $codesToPrint[$i];
                                    
                                    // Use activation_date and expiry_date if available, otherwise use start_time and end_time
                                    $activationDate = isset($code['activation_date']) && !empty($code['activation_date']) 
                                        ? date('d/m/y', strtotime($code['activation_date']))
                                        : date('d/m/y', strtotime($code['start_time']));
                                    
                                    $expiryDate = isset($code['expiry_date']) && !empty($code['expiry_date'])
                                        ? date('d/m/y', strtotime($code['expiry_date']))
                                        : date('d/m/y', strtotime($code['end_time']));
                                ?>
                                    <div class="code-block">
                                        <div class="access-code-bold"><?php echo htmlspecialchars($code['access_code']); ?></div>
                                        <div class="tiny-text">Date of Activation: <?php echo $activationDate; ?></div>
                                        <div class="tiny-text">Valid till: <?php echo $expiryDate; ?></div>
                                    </div>
                                    
                                    <!-- Add clearfix after each row -->
                                    <?php if (($i + 1 - $pageStart) % $codesPerRow == 0): ?>
                                        <div class="clearfix"></div>
                                    <?php endif; ?>
                                <?php endfor; ?>
                                
                                <!-- Fill remaining slots with empty blocks if needed -->
                                <?php 
                                $remainingSlots = $codesPerPage - ($pageEnd - $pageStart);
                                if ($remainingSlots > 0 && $page == $totalPages) {
                                    for ($j = 0; $j < $remainingSlots; $j++) {
                                        echo '<div class="code-block" style="border: none; background: transparent;"></div>';
                                        if (($j + 1) % $codesPerRow == 0) {
                                            echo '<div class="clearfix"></div>';
                                        }
                                    }
                                }
                                ?>
                            </div>
                            
                            <!-- Page break for printing -->
                            <?php if ($page < $totalPages): ?>
                                <div style="page-break-after: always;"></div>
                            <?php endif; ?>
                        </div>
                    <?php endfor; ?>
                </div>
                
                <div class="clearfix"></div>
                <div class="text-center mt-4 no-print">
                    <button class="btn btn-success btn-lg" onclick="window.print()">
                        <i class="bi bi-printer"></i> Print All Codes
                    </button>
                    <a href="generate_access_key.php" class="btn btn-outline-secondary">
                        <i class="bi bi-x-circle"></i> Close Print View
                    </a>
                    
                    <div class="mt-3">
                        <p class="text-muted">
                            <small>
                                <i class="bi bi-info-circle"></i>
                                Printing <?php echo count($codesToPrint); ?> codes on <?php echo $totalPages; ?> page(s)
                                (Approx. <?php echo $codesPerPage; ?> codes per page)
                            </small>
                        </p>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    <?php endif; ?>
    
    <!-- Search Results Section -->
    <?php if (!empty($searchResults)): ?>
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h4 class="mb-0"><i class="bi bi-search"></i> Search Results</h4>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info mb-3">
                            <i class="bi bi-clock"></i> 
                            <strong>Validity Information:</strong> Check activation and expiry dates for each code
                        </div>
                        
                        <form method="POST" id="searchBulkForm">
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <thead class="table-success">
                                        <tr>
                                            <th width="40">
                                                <input type="checkbox" id="selectAllSearch">
                                            </th>
                                            <th>Access Code</th>
                                            <th>Batch ID</th>
                                            <th>Activation Date</th>
                                            <th>Expiry Date</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($searchResults as $code): ?>
                                            <?php
                                            // Determine status based on activation and expiry dates
                                            $now = time();
                                            $activationTime = isset($code['activation_date']) && !empty($code['activation_date']) 
                                                ? strtotime($code['activation_date']) 
                                                : strtotime($code['start_time']);
                                            
                                            $expiryTime = isset($code['expiry_date']) && !empty($code['expiry_date'])
                                                ? strtotime($code['expiry_date'])
                                                : strtotime($code['end_time']);
                                            
                                            if ($code['is_used']) {
                                                $status = '<span class="badge bg-secondary">Used</span>';
                                            } elseif ($now < $activationTime) {
                                                $status = '<span class="badge bg-warning">Inactive</span>';
                                            } elseif ($now > $expiryTime) {
                                                $status = '<span class="badge bg-danger">Expired</span>';
                                            } else {
                                                $status = '<span class="badge bg-success">Active</span>';
                                            }
                                            
                                            // Format dates for display
                                            $activationDate = isset($code['activation_date']) && !empty($code['activation_date'])
                                                ? date('M j, Y h:i A', strtotime($code['activation_date']))
                                                : date('M j, Y h:i A', strtotime($code['start_time']));
                                            
                                            $expiryDate = isset($code['expiry_date']) && !empty($code['expiry_date'])
                                                ? date('M j, Y h:i A', strtotime($code['expiry_date']))
                                                : date('M j, Y h:i A', strtotime($code['end_time']));
                                            ?>
                                            <tr>
                                                <td>
                                                    <input type="checkbox" name="selected_codes[]" value="<?php echo htmlspecialchars($code['id']); ?>">
                                                </td>
                                                <td><code><?php echo htmlspecialchars($code['access_code']); ?></code></td>
                                                <td><?php echo isset($code['batch_id']) ? htmlspecialchars(substr($code['batch_id'], 0, 8)) : 'N/A'; ?></td>
                                                <td><?php echo $activationDate; ?></td>
                                                <td><?php echo $expiryDate; ?></td>
                                                <td><?php echo $status; ?></td>
                                                <td>
                                                    <div class="btn-group">
                                                        <a href="?batch=<?php echo urlencode($code['batch_id']); ?>" class="btn btn-sm btn-outline-success">
                                                            <i class="bi bi-eye"></i> View
                                                        </a>
                                                        <a href="?batch=<?php echo urlencode($code['batch_id']); ?>&print=1" class="btn btn-sm btn-outline-primary">
                                                            <i class="bi bi-printer"></i> Print
                                                        </a>
                                                        <a href="?batch=<?php echo urlencode($code['batch_id']); ?>&download_pdf=1" class="btn btn-sm btn-outline-info">
                                                            <i class="bi bi-download"></i> PDF
                                                        </a>
                                                        <form method="POST" class="d-inline">
                                                            <input type="hidden" name="code_id" value="<?php echo htmlspecialchars($code['id']); ?>">
                                                            <button type="submit" name="delete_code" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this code?')">
                                                                <i class="bi bi-trash"></i>
                                                            </button>
                                                        </form>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class="mt-3">
                                <select class="form-select d-inline-block" name="bulk_action" style="width: auto;">
                                    <option value="">Bulk Actions</option>
                                    <option value="print">Print Selected</option>
                                    <option value="delete">Delete Selected</option>
                                </select>
                                <button type="submit" class="btn btn-success ms-2">
                                    <i class="bi bi-check-circle"></i> Apply
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Select all checkboxes
    document.getElementById('selectAllBatch')?.addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('#bulkForm input[name="selected_codes[]"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });
    
    document.getElementById('selectAllSearch')?.addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('#searchBulkForm input[name="selected_codes[]"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });
    
    // Validate prefix input
    document.getElementById('prefix')?.addEventListener('input', function(e) {
        this.value = this.value.replace(/[^A-Za-z]/g, '').toUpperCase();
        if (this.value.length > 3) {
            this.value = this.value.substring(0, 3);
        }
    });
    
    // Set minimum expiry date based on activation date
    document.getElementById('activation_date')?.addEventListener('change', function() {
        const activationDate = new Date(this.value);
        const expiryInput = document.getElementById('expiry_date');
        expiryInput.min = this.value;
        
        // If expiry date is before activation date, update it
        const expiryDate = new Date(expiryInput.value);
        if (expiryDate < activationDate) {
            // Set expiry to 10 hours after activation by default
            activationDate.setHours(activationDate.getHours() + 10);
            expiryInput.value = activationDate.toISOString().slice(0, 16);
        }
    });
    
    // Set default expiry date (10 hours from now)
    window.addEventListener('load', function() {
        const activationInput = document.getElementById('activation_date');
        const expiryInput = document.getElementById('expiry_date');
        
        if (activationInput && expiryInput) {
            const now = new Date();
            const defaultExpiry = new Date(now.getTime() + (10 * 60 * 60 * 1000));
            
            // Set default values if not already set
            if (!activationInput.value) {
                activationInput.value = now.toISOString().slice(0, 16);
            }
            
            if (!expiryInput.value) {
                expiryInput.value = defaultExpiry.toISOString().slice(0, 16);
            }
        }
    });
    
    // Auto-print when print parameter is set
    <?php if (isset($_GET['print'])): ?>
        window.addEventListener('load', function() {
            // Small delay to ensure everything is loaded
            setTimeout(function() {
                window.print();
            }, 500);
        });
    <?php endif; ?>
    
    // Optimize print layout
    document.addEventListener('DOMContentLoaded', function() {
        // Add print optimization tips
        const printTips = `
            <div class="alert alert-warning mt-3 no-print">
                <h6><i class="bi bi-printer"></i> For Best Printing Results:</h6>
                <ul class="mb-0">
                    <li>Use "Borderless" or "Minimal Margins" in printer settings</li>
                    <li>Paper: A4 Landscape</li>
                    <li>Scale: 100% (do not fit to page)</li>
                    <li>Print in "Fast" or "Draft" mode to save ink</li>
                </ul>
            </div>
        `;
        
        const printSection = document.querySelector('.print-section');
        if (printSection) {
            const existingTips = printSection.querySelector('.alert-warning');
            if (!existingTips) {
                const printButton = printSection.querySelector('.no-print .btn-success');
                if (printButton) {
                    printButton.insertAdjacentHTML('afterend', printTips);
                }
            }
        }
    });
</script>
</body>
</html>