<?php
/**
 * Badge Management Page
 * View and generate event badges for delegates
 */

require_once 'auth_rbac.php';
require_once '../db_config.php';

// Require admin login and delegates view permission
requirePermission('delegates', 'view');

$currentPage = 'badges';

// Pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 25;
$offset = ($page - 1) * $per_page;

// Search and filter
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$product_code_filter = $_GET['product_code'] ?? '';
$print_status_filter = $_GET['print_status'] ?? '';

try {
    $pdo = getDBConnection();
    
    // Build WHERE clause
    $where_conditions = [];
    $params = [];
    
    if (!empty($search)) {
        $where_conditions[] = "(d.full_name LIKE ? OR d.badge_name LIKE ? OR d.designation LIKE ? OR r.registration_number LIKE ?)";
        $search_param = "%{$search}%";
        $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    }
    
    if (!empty($status_filter)) {
        $where_conditions[] = "r.payment_status = ?";
        $params[] = $status_filter;
    }
    
    if (!empty($product_code_filter)) {
        $where_conditions[] = "(EXISTS (
            SELECT 1 FROM registration_products rp2 
            JOIN products p2 ON rp2.product_id = p2.id 
            JOIN product_categories pc2 ON p2.category_id = pc2.id 
            WHERE rp2.registration_id = r.id 
            AND pc2.name = 'Delegate Pass' 
            AND p2.product_code = ?
        ) OR (NOT EXISTS (
            SELECT 1 FROM registration_products rp3 
            JOIN products p3 ON rp3.product_id = p3.id 
            JOIN product_categories pc3 ON p3.category_id = pc3.id 
            WHERE rp3.registration_id = r.id 
            AND pc3.name = 'Delegate Pass'
        ) AND r.delegate_type = ?))";
        $params[] = $product_code_filter;
        $legacy_type = $product_code_filter === 'DELEGATE_EARLY_BIRD' ? 'earlyBird' : 'standard';
        $params[] = $legacy_type;
    }
    
    if (!empty($print_status_filter)) {
        if ($print_status_filter === 'printed') {
            $where_conditions[] = "EXISTS (
                SELECT 1 FROM badge_generation_log bgl 
                WHERE bgl.delegate_id = d.id 
                AND bgl.is_printed = TRUE
            )";
        } elseif ($print_status_filter === 'unprinted') {
            $where_conditions[] = "(NOT EXISTS (
                SELECT 1 FROM badge_generation_log bgl 
                WHERE bgl.delegate_id = d.id 
                AND bgl.is_printed = TRUE
            ) OR NOT EXISTS (
                SELECT 1 FROM badge_generation_log bgl2 
                WHERE bgl2.delegate_id = d.id
            ))";
        }
    }
    
    $where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";
    
    // Get total count for pagination
    $count_query = "
        SELECT COUNT(DISTINCT d.id) 
        FROM delegates d 
        JOIN registrations r ON d.registration_id = r.id 
        LEFT JOIN registration_products rp ON r.id = rp.registration_id
        LEFT JOIN products p ON rp.product_id = p.id
        LEFT JOIN product_categories pc ON p.category_id = pc.id
        {$where_clause}
    ";
    $stmt = $pdo->prepare($count_query);
    $stmt->execute($params);
    $total_records = $stmt->fetchColumn();
    $total_pages = ceil($total_records / $per_page);
    
    // Get delegates with registration info
    $query = "
        SELECT 
            d.*,
            r.registration_number,
            r.contact_full_name as contact_name,
            r.university_name,
            r.delegate_type,
            r.payment_status,
            r.created_at as registration_date,
            MAX(CASE WHEN pc.name = 'Delegate Pass' THEN rp.pricing_tier END) as pricing_tier,
            MAX(CASE WHEN pc.name = 'Delegate Pass' THEN p.product_code END) as product_code,
            (SELECT COUNT(*) FROM badge_generation_log bgl WHERE bgl.delegate_id = d.id) as badge_generated_count,
            (SELECT is_printed FROM badge_generation_log bgl WHERE bgl.delegate_id = d.id ORDER BY bgl.created_at DESC LIMIT 1) as is_printed,
            (SELECT printed_at FROM badge_generation_log bgl WHERE bgl.delegate_id = d.id ORDER BY bgl.created_at DESC LIMIT 1) as printed_at
        FROM delegates d 
        JOIN registrations r ON d.registration_id = r.id 
        LEFT JOIN registration_products rp ON r.id = rp.registration_id
        LEFT JOIN products p ON rp.product_id = p.id
        LEFT JOIN product_categories pc ON p.category_id = pc.id
        {$where_clause}
        GROUP BY d.id, r.registration_number, r.contact_full_name, r.university_name, r.delegate_type, r.payment_status, r.created_at
        ORDER BY r.created_at DESC, d.id ASC
        LIMIT {$per_page} OFFSET {$offset}
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $delegates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get delegate statistics
    $stats_query = "
        SELECT 
            COUNT(*) as total_delegates,
            COUNT(CASE WHEN r.payment_status = 'paid' THEN 1 END) as paid_delegates,
            (SELECT COUNT(*) FROM badge_generation_log) as total_badges_generated,
            (SELECT COUNT(DISTINCT delegate_id) FROM badge_generation_log WHERE is_printed = TRUE) as total_badges_printed
        FROM delegates d
        LEFT JOIN registrations r ON d.registration_id = r.id
    ";
    $stats = $pdo->query($stats_query)->fetch(PDO::FETCH_ASSOC);
    
    // Get available product codes for delegate products
    $product_codes_query = "
        SELECT p.product_code, p.name, p.display_order
        FROM products p
        JOIN product_categories pc ON p.category_id = pc.id
        WHERE pc.name = 'Delegate Pass' AND p.is_active = 1
        GROUP BY p.product_code, p.name, p.display_order
        ORDER BY p.display_order, p.name
    ";
    $product_codes_result = $pdo->query($product_codes_query)->fetchAll(PDO::FETCH_ASSOC);
    
    // Add legacy options
    $product_codes = [
        ['product_code' => 'DELEGATE_EARLY_BIRD', 'name' => 'Early Bird Delegate'],
        ['product_code' => 'DELEGATE_STANDARD', 'name' => 'Standard Delegate']
    ];
    
    foreach ($product_codes_result as $pc) {
        $exists = false;
        foreach ($product_codes as $existing) {
            if ($existing['product_code'] === $pc['product_code']) {
                $exists = true;
                break;
            }
        }
        if (!$exists) {
            $product_codes[] = $pc;
        }
    }
    
    // Get badge settings
    $badge_settings_query = "SELECT setting_key, setting_value FROM badge_settings";
    $badge_settings_result = $pdo->query($badge_settings_query)->fetchAll(PDO::FETCH_KEY_PAIR);
    
} catch (Exception $e) {
    $error = "Database error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Badges - XChange Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <style>
        .action-buttons {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 2rem;
            flex-wrap: wrap;
        }
        
        .action-buttons .btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .badge-icon {
            font-size: 1.2em;
        }
        
        .badge-status-indicator {
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            font-size: 0.85em;
        }
        
        .badge-status-indicator.generated {
            color: #10b981;
        }
        
        .badge-status-indicator.not-generated {
            color: #6b7280;
        }
    </style>
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <div class="page-header" style="display: flex; justify-content: space-between; align-items: center;">
            <div>
                <h1>🎫 Event Badges</h1>
                <p>Generate and manage event badges for delegates</p>
            </div>
            <div>
                <a href="badge-settings.php" class="btn btn-secondary">
                    ⚙️ Badge Settings
                </a>
            </div>
        </div>

        <?php if (isset($error)): ?>
            <div class="alert alert-error mb-4"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <?php if (!isset($error)): ?>
        
        <!-- Badge Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <h3>Total Delegates</h3>
                <p class="stat-value"><?php echo number_format($stats['total_delegates']); ?></p>
                <p class="stat-change">Registered delegates</p>
            </div>
            
            <div class="stat-card">
                <h3>Confirmed Delegates</h3>
                <p class="stat-value"><?php echo number_format($stats['paid_delegates']); ?></p>
                <p class="stat-change"><?php echo $stats['total_delegates'] > 0 ? round(($stats['paid_delegates'] / $stats['total_delegates']) * 100, 1) : 0; ?>% of total</p>
            </div>
            
            <div class="stat-card">
                <h3>Badges Generated</h3>
                <p class="stat-value"><?php echo number_format($stats['total_badges_generated']); ?></p>
                <p class="stat-change">Total badge generations</p>
            </div>
            
            <div class="stat-card">
                <h3>🖨️ Badges Printed</h3>
                <p class="stat-value"><?php echo number_format($stats['total_badges_printed']); ?></p>
                <p class="stat-change"><?php echo $stats['total_delegates'] > 0 ? round(($stats['total_badges_printed'] / $stats['total_delegates']) * 100, 1) : 0; ?>% printed</p>
            </div>
        </div>
        
        <!-- Bulk Actions -->
        <div class="action-buttons">
            <button onclick="generateBatchBadges('all')" class="btn btn-primary">
                <span class="badge-icon">📦</span>
                Generate All Badges
            </button>
            <button onclick="generateBatchBadges('paid')" class="btn btn-success">
                <span class="badge-icon">✅</span>
                Generate Paid Delegates
            </button>
            <button onclick="generateBatchBadges('filtered')" class="btn btn-secondary">
                <span class="badge-icon">🔍</span>
                Generate Filtered
            </button>
            <button onclick="markSelectedAsPrinted()" class="btn" style="background-color: #10b981; color: white;">
                <span class="badge-icon">🖨️</span>
                Mark Selected as Printed
            </button>
            <button onclick="markSelectedAsUnprinted()" class="btn btn-outline-secondary">
                <span class="badge-icon">↩️</span>
                Mark Selected as Unprinted
            </button>
            <a href="badge-generator.php" class="btn btn-outline-primary">
                <span class="badge-icon">🎨</span>
                Badge Designer
            </a>
        </div>
        
        <!-- Filters -->
        <div class="filters">
            <form method="GET" class="filter-form">
                <div class="filter-row">
                    <div class="filter-field">
                        <label for="search" class="filter-label">Search</label>
                        <input type="text" id="search" name="search" class="filter-input" 
                               placeholder="Name, designation, registration #..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="filter-field">
                        <label for="status" class="filter-label">Payment Status</label>
                        <select id="status" name="status" class="filter-input">
                            <option value="">All</option>
                            <option value="paid" <?php echo $status_filter === 'paid' ? 'selected' : ''; ?>>Paid</option>
                            <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="failed" <?php echo $status_filter === 'failed' ? 'selected' : ''; ?>>Failed</option>
                        </select>
                    </div>
                    
                    <div class="filter-field">
                        <label for="product_code" class="filter-label">Delegate Type</label>
                        <select id="product_code" name="product_code" class="filter-input">
                            <option value="">All</option>
                            <?php foreach ($product_codes as $pc): ?>
                                <option value="<?php echo htmlspecialchars($pc['product_code']); ?>" 
                                        <?php echo $product_code_filter === $pc['product_code'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($pc['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="filter-field">
                        <label for="print_status" class="filter-label">Print Status</label>
                        <select id="print_status" name="print_status" class="filter-input">
                            <option value="">All</option>
                            <option value="printed" <?php echo $print_status_filter === 'printed' ? 'selected' : ''; ?>>🖨️ Printed</option>
                            <option value="unprinted" <?php echo $print_status_filter === 'unprinted' ? 'selected' : ''; ?>>⚪ Not Printed</option>
                        </select>
                    </div>
                    
                    <div class="filter-actions">
                        <button type="submit" class="btn btn-primary">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z"/>
                            </svg>
                            Filter
                        </button>
                        <a href="badges.php" class="btn btn-secondary">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M3 6h18l-2 13H5L3 6z"/>
                                <path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                            </svg>
                            Reset
                        </a>
                    </div>
                </div>
            </form>
        </div>

        <!-- Delegates Table -->
        <div class="data-table">
            <h2>Delegates (<?php echo number_format($total_records); ?> total)</h2>
            <div class="table-container">
                <table class="table">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="select-all" onchange="toggleSelectAll(this)"></th>
                            <th>Registration #</th>
                            <th>Badge Name</th>
                            <th>Full Name</th>
                            <th>Designation</th>
                            <th>Department</th>
                            <th>University</th>
                            <th>Payment</th>
                            <th>Badge Status</th>
                            <th>Print Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($delegates)): ?>
                        <tr>
                            <td colspan="11" class="empty-state muted">
                                No delegates found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($delegates as $delegate): ?>
                        <tr>
                            <td>
                                <input type="checkbox" class="delegate-checkbox" 
                                       value="<?php echo $delegate['id']; ?>"
                                       data-registration="<?php echo htmlspecialchars($delegate['registration_number']); ?>">
                            </td>
                            <td>
                                <a href="registration-details.php?id=<?php echo urlencode($delegate['registration_number']); ?>" 
                                   class="link link-strong">
                                    <?php echo htmlspecialchars($delegate['registration_number']); ?>
                                </a>
                            </td>
                            <td><strong><?php echo htmlspecialchars($delegate['badge_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($delegate['full_name']); ?></td>
                            <td><?php echo htmlspecialchars($delegate['designation']); ?></td>
                            <td><?php echo htmlspecialchars($delegate['department'] ?: '—'); ?></td>
                            <td><?php echo htmlspecialchars($delegate['university_name']); ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $delegate['payment_status']; ?>">
                                    <?php echo ucfirst($delegate['payment_status']); ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($delegate['badge_generated_count'] > 0): ?>
                                    <span class="badge-status-indicator generated">
                                        ✅ Generated (<?php echo $delegate['badge_generated_count']; ?>)
                                    </span>
                                <?php else: ?>
                                    <span class="badge-status-indicator not-generated">
                                        ⚪ Not Generated
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($delegate['is_printed']): ?>
                                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                                        <span class="badge-status-indicator" style="color: #10b981; font-weight: 600;">
                                            ✅ Printed
                                        </span>
                                        <?php if ($delegate['printed_at']): ?>
                                            <small class="muted" style="font-size: 0.75em;">
                                                <?php echo date('M d, H:i', strtotime($delegate['printed_at'])); ?>
                                            </small>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <span class="badge-status-indicator" style="color: #6b7280;">
                                        ⚪ Not Printed
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div style="display: flex; gap: 5px; align-items: center; flex-wrap: wrap;">
                                    <button type="button" class="btn btn-sm btn-primary" 
                                            onclick="previewBadge(<?php echo $delegate['id']; ?>)" 
                                            title="Preview badge">
                                        👁️
                                    </button>
                                    <button type="button" class="btn btn-sm btn-success" 
                                            onclick="printBadge(<?php echo $delegate['id']; ?>)" 
                                            title="Print badge">
                                        🖨️
                                    </button>
                                    <button type="button" 
                                            class="btn btn-sm <?php echo $delegate['is_printed'] ? 'btn-outline-secondary' : 'btn-outline-success'; ?>" 
                                            onclick="togglePrintStatus(<?php echo $delegate['id']; ?>, this)" 
                                            title="<?php echo $delegate['is_printed'] ? 'Mark as unprinted' : 'Mark as printed'; ?>"
                                            data-printed="<?php echo $delegate['is_printed'] ? '1' : '0'; ?>">
                                        <?php echo $delegate['is_printed'] ? '↩️' : '✓'; ?>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>&product_code=<?php echo urlencode($product_code_filter); ?>&print_status=<?php echo urlencode($print_status_filter); ?>">
                    Previous
                </a>
            <?php endif; ?>
            
            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                <?php if ($i === $page): ?>
                    <span class="current"><?php echo $i; ?></span>
                <?php else: ?>
                    <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>&product_code=<?php echo urlencode($product_code_filter); ?>&print_status=<?php echo urlencode($print_status_filter); ?>">
                        <?php echo $i; ?>
                    </a>
                <?php endif; ?>
            <?php endfor; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>&product_code=<?php echo urlencode($product_code_filter); ?>&print_status=<?php echo urlencode($print_status_filter); ?>">
                    Next
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <?php endif; ?>
    </div>

<!-- Badge Preview Modal -->
<div id="badgePreviewModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 420px;">
        <div class="modal-header">
            <h4>Badge Preview</h4>
            <span class="close" onclick="closeBadgePreviewModal()">&times;</span>
        </div>
        <div id="badgePreviewContent" style="padding: 20px; text-align: center;">
            <div class="loading">Loading preview...</div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeBadgePreviewModal()">Close</button>
            <button type="button" class="btn btn-primary" onclick="printCurrentBadge()">🖨️ Print Badge</button>
        </div>
    </div>
</div>

<script>
let currentDelegateId = null;

function toggleSelectAll(checkbox) {
    const checkboxes = document.querySelectorAll('.delegate-checkbox');
    checkboxes.forEach(cb => cb.checked = checkbox.checked);
}

function getSelectedDelegateIds() {
    const checkboxes = document.querySelectorAll('.delegate-checkbox:checked');
    return Array.from(checkboxes).map(cb => cb.value);
}

function previewBadge(delegateId) {
    currentDelegateId = delegateId;
    document.getElementById('badgePreviewModal').style.display = 'block';
    document.body.style.overflow = 'hidden';
    document.getElementById('badgePreviewContent').innerHTML = '<div class="loading">Loading preview...</div>';
    
    // Fetch badge preview
    fetch(`badge_api.php?action=preview&delegate_id=${delegateId}`)
        .then(response => response.text())
        .then(html => {
            document.getElementById('badgePreviewContent').innerHTML = html;
        })
        .catch(error => {
            document.getElementById('badgePreviewContent').innerHTML = 
                '<div class="alert alert-error">Error loading preview: ' + error.message + '</div>';
        });
}

function closeBadgePreviewModal() {
    document.getElementById('badgePreviewModal').style.display = 'none';
    document.body.style.overflow = 'auto';
    currentDelegateId = null;
}

function printCurrentBadge() {
    if (currentDelegateId) {
        printBadge(currentDelegateId);
    }
}

function printBadge(delegateId) {
    // Open badge in new window/tab ready for printing
    window.open(`badge_api.php?action=print&delegate_id=${delegateId}`, '_blank');
}

function generateBatchBadges(type) {
    let delegateIds = [];
    let message = '';
    
    if (type === 'all') {
        message = 'Generate badges for ALL delegates? This may take a while.';
    } else if (type === 'paid') {
        message = 'Generate badges for all paid delegates?';
    } else if (type === 'filtered') {
        delegateIds = getSelectedDelegateIds();
        if (delegateIds.length === 0) {
            alert('Please select at least one delegate by checking the checkboxes.');
            return;
        }
        message = `Generate badges for ${delegateIds.length} selected delegate(s)?`;
    }
    
    if (confirm(message)) {
        const params = new URLSearchParams({
            action: 'batch_generate',
            type: type
        });
        
        if (type === 'filtered' && delegateIds.length > 0) {
            params.append('delegate_ids', delegateIds.join(','));
        }
        
        window.location.href = `badge_api.php?${params.toString()}`;
    }
}

// Print tracking functions
function togglePrintStatus(delegateId, button) {
    const formData = new FormData();
    formData.append('action', 'toggle_print_status');
    formData.append('delegate_id', delegateId);
    
    // Disable button during request
    button.disabled = true;
    const originalText = button.innerHTML;
    button.innerHTML = '⏳';
    
    fetch('badge_print_api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Reload page to update all statuses
            window.location.reload();
        } else {
            alert('Error: ' + (data.error || 'Failed to update print status'));
            button.disabled = false;
            button.innerHTML = originalText;
        }
    })
    .catch(error => {
        alert('Error: ' + error.message);
        button.disabled = false;
        button.innerHTML = originalText;
    });
}

function markSelectedAsPrinted() {
    const delegateIds = getSelectedDelegateIds();
    
    if (delegateIds.length === 0) {
        alert('Please select at least one delegate by checking the checkboxes.');
        return;
    }
    
    if (!confirm(`Mark ${delegateIds.length} badge(s) as printed?`)) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'mark_printed');
    formData.append('delegate_ids', delegateIds.join(','));
    
    fetch('badge_print_api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            window.location.reload();
        } else {
            alert('Error: ' + (data.error || 'Failed to mark badges as printed'));
        }
    })
    .catch(error => {
        alert('Error: ' + error.message);
    });
}

function markSelectedAsUnprinted() {
    const delegateIds = getSelectedDelegateIds();
    
    if (delegateIds.length === 0) {
        alert('Please select at least one delegate by checking the checkboxes.');
        return;
    }
    
    if (!confirm(`Mark ${delegateIds.length} badge(s) as unprinted?`)) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'mark_unprinted');
    formData.append('delegate_ids', delegateIds.join(','));
    
    fetch('badge_print_api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            window.location.reload();
        } else {
            alert('Error: ' + (data.error || 'Failed to mark badges as unprinted'));
        }
    })
    .catch(error => {
        alert('Error: ' + error.message);
    });
}
</script>

<?php include 'includes/footer.php'; ?>
</body>
</html>

