<?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 end_time < 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) {}

// 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']) : 'EXAM';
    $adminUsername = isset($_SESSION['admin']['username']) ? $_SESSION['admin']['username'] : 'System';
    $batchId = uniqid();

    try {
        $DBH->beginTransaction();
        
        $codes = [];
        for ($i = 0; $i < $quantity; $i++) {
            $code = $prefix . strtoupper(substr(md5(uniqid(rand(), true)), 0, 8));
            $startTime = date('Y-m-d H:i:s');
            $endTime = date('Y-m-d H:i:s', strtotime("+8 hours"));
            
            if ($batchIdColumnExists) {
                $stmt = $DBH->prepare("
                    INSERT INTO exam_access_codes 
                    (access_code, start_time, end_time, created_by, batch_id) 
                    VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->execute([$code, $startTime, $endTime, $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, $endTime, $adminUsername]);
            }
            
            $codes[] = [
                'code' => $code,
                'start_time' => $startTime,
                'end_time' => $endTime,
                'created_by' => $adminUsername,
                'batch_id' => $batchId
            ];
        }
        
        $DBH->commit();
        $message = "Successfully generated {$quantity} access codes (Batch: {$batchId})!";
        $generatedCodes = $codes;
    } catch (Exception $e) {
        $DBH->rollBack();
        $error = "Error generating codes: " . $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 end_time >= 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();
    }
}

// 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();
    }
}

// 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();
    }
}

// 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(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

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

        // Set default header data
        $pdf->SetHeaderData('', 0, 'VDA-COLL Access Codes', 'Batch: ' . htmlspecialchars($batchId));

        // Set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        // Set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        // Set font
        $pdf->SetFont('helvetica', '', 10);

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

        // Generate HTML content for PDF
        $html = '<!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: helvetica, sans-serif; }
                .code-card {
                    width: 45%;
                    float: left;
                    margin: 10px;
                    padding: 15px;
                    border: 2px dashed #ccc;
                    border-radius: 5px;
                    page-break-inside: avoid;
                }
                .print-grid { display: flex; flex-wrap: wrap; }
                .clear { clear: both; }
                h1 { text-align: center; margin-bottom: 20px; }
                .batch-info { text-align: center; margin-bottom: 30px; }
            </style>
        </head>
        <body>
            <h1>VDA-COLL Access Codes</h1>
            <div class="batch-info">
                <p><strong>Batch ID:</strong> ' . htmlspecialchars($batchId) . '</p>
                <p><strong>Generated On:</strong> ' . (isset($codes[0]['start_time']) ? date('M j, Y h:i A', strtotime($codes[0]['start_time'])) : 'N/A') . '</p>
                <p><strong>Total Codes:</strong> ' . count($codes) . '</p>
            </div>
            <div class="print-grid">';

        foreach ($codes as $code) {
            $html .= '
            <div class="code-card">
                <h3 style="text-align:center">' . htmlspecialchars($code['access_code']) . '</h3>
                <hr>
                <p><strong>Valid From:</strong> ' . date('M j, Y h:i A', strtotime($code['start_time'])) . '</p>
                <p><strong>Valid Until:</strong> ' . date('M j, Y h:i A', strtotime($code['end_time'])) . '</p>
            </div>';
        }

        $html .= '</div><div class="clear"></div></body></html>';

        // 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());
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>VERBUM DEI INT'L COLLEGE - 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;
        }
        .print-grid {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
        }
        @media print {
            body * { visibility: hidden; }
            .print-section, .print-section * { visibility: visible; }
            .print-section { position: absolute; left: 0; top: 0; width: 100%; }
            .no-print { display: none !important; }
        }
        .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;
        }
    </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-8 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-6">
                                <label for="quantity" class="form-label">Number of Codes</label>
                                <input type="number" class="form-control" id="quantity" name="quantity" min="1" max="100" value="10" required>
                            </div>
                            <div class="col-md-6">
                                <label for="prefix" class="form-label">Code Prefix (optional)</label>
                                <input type="text" class="form-control" id="prefix" name="prefix" maxlength="10" placeholder="EXAM">
                            </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">
                        <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>Valid From</th>
                                            <th>Valid Until</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($viewBatch as $code): ?>
                                            <?php
                                            $status = '';
                                            if ($code['is_used']) {
                                                $status = '<span class="badge bg-secondary">Used</span>';
                                            } elseif (strtotime($code['end_time']) < time()) {
                                                $status = '<span class="badge bg-danger">Expired</span>';
                                            } else {
                                                $status = '<span class="badge bg-success">Active</span>';
                                            }
                                            ?>
                                            <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 date('M j, Y h:i A', strtotime($code['start_time'])); ?></td>
                                                <td><?php echo date('M j, Y h:i A', strtotime($code['end_time'])); ?></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">
                <h3 class="text-center mb-4">VERBUM DEI INT'L COLLEGE Access Codes</h3>
                <p class="text-center mb-4">
                    <strong>Batch:</strong> <?php echo isset($codesToPrint[0]['batch_id']) ? htmlspecialchars(substr($codesToPrint[0]['batch_id'], 0, 8)) : 'N/A'; ?> |
                    <strong>Generated:</strong> <?php echo date('M j, Y h:i A'); ?>
                </p>
                
                <div class="print-grid">
                    <?php foreach ($codesToPrint as $code): ?>
                        <div class="code-card">
                            <h4 class="text-center"><?php echo htmlspecialchars($code['access_code']); ?></h4>
                            <hr>
                            <p class="mb-1"><strong>Valid From:</strong> <?php echo date('M j, Y h:i A', strtotime($code['start_time'])); ?></p>
                            <p class="mb-1"><strong>Valid Until:</strong> <?php echo date('M j, Y h:i A', strtotime($code['end_time'])); ?></p>
                            <p class="mb-0"><strong>Batch:</strong> <?php echo isset($code['batch_id']) ? htmlspecialchars(substr($code['batch_id'], 0, 8)) : 'N/A'; ?></p>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="clearfix"></div>
                <div class="text-center mt-4 no-print">
                    <button class="btn btn-success" onclick="window.print()">
                        <i class="bi bi-printer"></i> Print Codes
                    </button>
                    <a href="generate_access_key.php" class="btn btn-outline-secondary">
                        <i class="bi bi-x-circle"></i> Close
                    </a>
                </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">
                        <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>Valid From</th>
                                            <th>Valid Until</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($searchResults as $code): ?>
                                            <?php
                                            $status = '';
                                            if ($code['is_used']) {
                                                $status = '<span class="badge bg-secondary">Used</span>';
                                            } elseif (strtotime($code['end_time']) < time()) {
                                                $status = '<span class="badge bg-danger">Expired</span>';
                                            } else {
                                                $status = '<span class="badge bg-success">Active</span>';
                                            }
                                            ?>
                                            <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 date('M j, Y h:i A', strtotime($code['start_time'])); ?></td>
                                                <td><?php echo date('M j, Y h:i A', strtotime($code['end_time'])); ?></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;
        });
    });
    
    // Auto-print when print parameter is set
    <?php if (isset($_GET['print'])): ?>
        window.addEventListener('load', function() {
            window.print();
        });
    <?php endif; ?>
</script>
</body>
</html>