<?php
/**
 * Badge API
 * Handles badge generation, preview, and download
 */

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

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

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

try {
    $pdo = getDBConnection();
    
    // Get badge settings
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM badge_settings");
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    switch ($action) {
        case 'preview':
            $delegate_id = $_GET['delegate_id'] ?? 0;
            echo generateBadgeHTML($delegate_id, $settings, $pdo);
            break;
            
        case 'print':
            $delegate_id = $_GET['delegate_id'] ?? 0;
            printBadge($delegate_id, $settings, $pdo);
            break;
            
        case 'download':
            $delegate_id = $_GET['delegate_id'] ?? 0;
            downloadBadge($delegate_id, $settings, $pdo);
            break;
            
        case 'batch_generate':
            $type = $_GET['type'] ?? 'all';
            batchGenerateBadges($type, $settings, $pdo);
            break;
            
        default:
            http_response_code(400);
            echo json_encode(['error' => 'Invalid action']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}

/**
 * Generate Badge HTML
 */
function generateBadgeHTML($delegate_id, $settings, $pdo) {
    // Get delegate data
    $stmt = $pdo->prepare("
        SELECT 
            d.*,
            r.registration_number,
            r.university_name,
            r.contact_full_name,
            r.contact_department,
            r.country
        FROM delegates d 
        JOIN registrations r ON d.registration_id = r.id 
        WHERE d.id = ?
    ");
    $stmt->execute([$delegate_id]);
    $delegate = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$delegate) {
        return '<div class="alert alert-error">Delegate not found</div>';
    }
    
    // Use badge_name as-is for large display
    $badge_name_display = strtoupper(trim($delegate['badge_name']));
    
    $event_name = $settings['event_name'] ?? 'Applied HE>X CHANGE';
    $event_dates = $settings['event_dates'] ?? '27-28 FEB 2025';
    $event_location = $settings['event_location'] ?? 'MANILA, PHILIPPINES';
    $badge_width = $settings['badge_width'] ?? 340;
    $badge_height = $settings['badge_height'] ?? 500;
    $bg_color = $settings['badge_background_color'] ?? '#ffffff';
    $text_color = $settings['badge_text_color'] ?? '#000000';
    $accent_color = $settings['badge_accent_color'] ?? '#6B9F3E';
    $enable_qr = ($settings['enable_qr_code'] ?? 'true') === 'true';
    $show_hosting_logo = ($settings['show_hosting_logo'] ?? 'true') === 'true';
    $show_partner_logo = ($settings['show_partner_logo'] ?? 'true') === 'true';
    $footer_decoration = ($settings['footer_decoration'] ?? 'true') === 'true';
    
    // Generate QR code data
    $qr_data = $delegate['registration_number'];
    if (!empty($settings['qr_code_base_url'])) {
        $qr_data = $settings['qr_code_base_url'] . $delegate['registration_number'];
    }
    
    // QR Code API URL (using a free service)
    $qr_code_url = 'https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=' . urlencode($qr_data);
    
    // Logo paths
    $event_logo = !empty($settings['event_logo_path']) ? '../' . $settings['event_logo_path'] : '';
    $university_logo = !empty($settings['university_logo_path']) ? '../' . $settings['university_logo_path'] : '';
    $partner_logo = !empty($settings['partner_logo_path']) ? '../' . $settings['partner_logo_path'] : '';
    
    ob_start();
    ?>
     <div class="event-badge" style="
        width: <?php echo $badge_width; ?>px;
        height: <?php echo $badge_height; ?>px;
        background: <?php echo $bg_color; ?>;
        color: <?php echo $text_color; ?>;
        font-family: 'Poppins', Arial, sans-serif;
        position: relative;
        overflow: hidden;
        box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        border-radius: 12px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    ">
        <!-- Header Section - Sticks to top -->
        <div style="
            padding: 15px 20px;
            text-align: center;
            border-bottom: 3px solid <?php echo $accent_color; ?>;
            flex-shrink: 0;
        ">
            <?php if (!empty($event_logo)): ?>
            <img src="<?php echo htmlspecialchars($event_logo); ?>" alt="Event Logo" style="
                max-width: 200px;
                max-height: 40px;
                object-fit: contain;
                margin-bottom: 8px;
            ">
            <?php else: ?>
            <div style="
                font-size: 28px;
                font-weight: 800;
                color: <?php echo $accent_color; ?>;
                margin-bottom: 4px;
                letter-spacing: 1px;
            "><?php echo htmlspecialchars($event_name); ?></div>
            <?php endif; ?>
            
            <div style="
                font-size: 10px;
                font-weight: 600;
                color: <?php echo $text_color; ?>;
                letter-spacing: 0.5px;
            "><?php echo htmlspecialchars($event_dates); ?> - <?php echo htmlspecialchars($event_location); ?></div>
        </div>
        
        <!-- Body Section - Centers in middle -->
        <div style="
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 20px;
            text-align: center;
        ">
            <!-- Badge Name (Large) -->
            <div style="
                font-size: 56px;
                font-weight: 900;
                color: <?php echo $text_color; ?>;
                line-height: 1;
                margin-bottom: 20px;
                letter-spacing: 2px;
            "><?php echo htmlspecialchars($badge_name_display); ?></div>
            
            <!-- Full Name -->
            <div style="
                font-size: 16px;
                font-weight: 700;
                color: <?php echo $text_color; ?>;
                margin-bottom: 8px;
                line-height: 1.2;
            "><?php echo htmlspecialchars($delegate['full_name']); ?></div>
            
            <!-- Designation -->
            <div style="
                font-size: 13px;
                font-weight: 600;
                color: <?php echo $text_color; ?>;
                margin-bottom: 4px;
                font-style: italic;
            "><?php echo htmlspecialchars($delegate['designation']); ?></div>
            
            <!-- Department (if available) -->
            <?php if (!empty($delegate['department'])): ?>
            <div style="
                font-size: 11px;
                font-weight: 500;
                color: <?php echo $text_color; ?>;
                margin-bottom: 4px;
            "><?php echo htmlspecialchars($delegate['department']); ?></div>
            <?php endif; ?>
            
            <!-- University Name -->
            <div style="
                font-size: 13px;
                font-weight: 800;
                color: <?php echo $text_color; ?>;
                margin-top: 10px;
                line-height: 1.3;
                text-transform: uppercase;
                letter-spacing: 0.5px;
            "><?php echo htmlspecialchars($delegate['university_name']); ?></div>
            
            <!-- Country (if available) -->
            <?php if (!empty($delegate['country'])): ?>
            <div style="
                font-size: 10px;
                font-weight: 600;
                color: <?php echo $text_color; ?>;
                margin-top: 4px;
                text-transform: uppercase;
                letter-spacing: 0.5px;
                opacity: 0.8;
            "><?php echo htmlspecialchars($delegate['country']); ?></div>
            <?php endif; ?>
        </div>
        
        <!-- Footer Section - Sticks to bottom -->
        <div style="
            padding: 5px 20px 8px 20px;
            border-top: 2px solid #e5e7eb;
            flex-shrink: 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 10px;
            min-height: 0;
        ">
            <!-- Logos Section -->
            <div style="
                display: flex;
                gap: 10px;
                align-items: center;
                flex: 1;
            ">
                <?php 
                // Check if partner logo exists
                $has_partner_logo = $show_partner_logo && !empty($partner_logo);
                // University logo size: double size if no partner logo
                $university_logo_size = $has_partner_logo ? '50px' : '100px'; // 50px × 2 = 100px
                $university_logo_height = $has_partner_logo ? '40px' : '80px'; // 40px × 2 = 80px
                ?>
                
                 <?php if ($show_hosting_logo && !empty($university_logo)): ?>
                <img src="<?php echo htmlspecialchars($university_logo); ?>" alt="University Logo" style="
                    max-width: <?php echo $university_logo_size; ?>;
                    max-height: <?php echo $university_logo_height; ?>;
                    object-fit: contain;
                    display: block;
                ">
                <?php endif; ?>
                
                <?php if ($has_partner_logo): ?>
                <img src="<?php echo htmlspecialchars($partner_logo); ?>" alt="Partner Logo" style="
                    max-width: 50px;
                    max-height: 40px;
                    object-fit: contain;
                    display: block;
                ">
                <?php endif; ?>
            </div>
            
            <!-- QR Code -->
            <?php if ($enable_qr): ?>
            <div style="text-align: center; display: flex; flex-direction: column; justify-content: flex-end; line-height: 1;">
                <img src="<?php echo htmlspecialchars($qr_code_url); ?>" alt="QR Code" style="
                    width: 65px;
                    height: 65px;
                    border: 1px solid #e5e7eb;
                    border-radius: 4px;
                    padding: 2px;
                    background: white;
                    display: block;
                ">
                <div style="
                    font-size: 6px;
                    color: <?php echo $text_color; ?>;
                    margin-top: 2px;
                    font-weight: 600;
                    line-height: 1;
                ">Scan for schedule</div>
            </div>
            <?php endif; ?>
        </div>
        
        <?php if ($footer_decoration): ?>
        <!-- Decorative Footer -->
        <div style="
            height: 40px;
            background: linear-gradient(90deg, 
                <?php echo $accent_color; ?> 0%, 
                <?php echo adjustColorBrightness($accent_color, -20); ?> 50%, 
                <?php echo $accent_color; ?> 100%);
            position: relative;
            overflow: hidden;
        ">
            <div style="
                position: absolute;
                bottom: 0;
                left: 0;
                right: 0;
                height: 30px;
                background: url('data:image/svg+xml;utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 1200 120%22 preserveAspectRatio=%22none%22><path d=%22M0,0V46.29c47.79,22.2,103.59,32.17,158,28,70.36-5.37,136.33-33.31,206.8-37.5C438.64,32.43,512.34,53.67,583,72.05c69.27,18,138.3,24.88,209.4,13.08,36.15-6,69.85-17.84,104.45-29.34C989.49,25,1113-14.29,1200,52.47V0Z%22 opacity=%22.25%22 fill=%22%23ffffff%22/><path d=%22M0,0V15.81C13,36.92,27.64,56.86,47.69,72.05,99.41,111.27,165,111,224.58,91.58c31.15-10.15,60.09-26.07,89.67-39.8,40.92-19,84.73-46,130.83-49.67,36.26-2.85,70.9,9.42,98.6,31.56,31.77,25.39,62.32,62,103.63,73,40.44,10.79,81.35-6.69,119.13-24.28s75.16-39,116.92-43.05c59.73-5.85,113.28,22.88,168.9,38.84,30.2,8.66,59,6.17,87.09-7.5,22.43-10.89,48-26.93,60.65-49.24V0Z%22 opacity=%22.5%22 fill=%22%23ffffff%22/><path d=%22M0,0V5.63C149.93,59,314.09,71.32,475.83,42.57c43-7.64,84.23-20.12,127.61-26.46,59-8.63,112.48,12.24,165.56,35.4C827.93,77.22,886,95.24,951.2,90c86.53-7,172.46-45.71,248.8-84.81V0Z%22 fill=%22%23ffffff%22/></svg>') no-repeat bottom center;
                background-size: cover;
                opacity: 0.3;
            "></div>
        </div>
        <?php endif; ?>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * Print Badge - Opens in new window ready to print
 */
function printBadge($delegate_id, $settings, $pdo) {
    $html = generateBadgeHTML($delegate_id, $settings, $pdo);
    
    // Get delegate info for page title
    $stmt = $pdo->prepare("SELECT d.badge_name, r.registration_number FROM delegates d JOIN registrations r ON d.registration_id = r.id WHERE d.id = ?");
    $stmt->execute([$delegate_id]);
    $delegate = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$delegate) {
        echo '<div class="alert alert-error">Delegate not found</div>';
        exit;
    }
    
    // Log badge generation
    $stmt = $pdo->prepare("INSERT INTO badge_generation_log (delegate_id, generation_type, file_path) VALUES (?, 'single', 'print')");
    $stmt->execute([$delegate_id]);
    
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Print Badge - <?php echo htmlspecialchars($delegate['badge_name']); ?></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;500;600;700;800;900&display=swap" rel="stylesheet">
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: 'Poppins', Arial, sans-serif;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                min-height: 100vh;
                background: #f3f4f6;
                padding: 20px;
            }
            .print-controls {
                margin-bottom: 20px;
                text-align: center;
            }
            .print-controls button {
                background: #3b82f6;
                color: white;
                border: none;
                padding: 12px 24px;
                border-radius: 8px;
                font-size: 16px;
                font-weight: 600;
                cursor: pointer;
                display: inline-flex;
                align-items: center;
                gap: 8px;
                box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
                transition: all 0.2s;
            }
            .print-controls button:hover {
                background: #2563eb;
                transform: translateY(-2px);
                box-shadow: 0 6px 16px rgba(59, 130, 246, 0.4);
            }
            .print-info {
                background: white;
                padding: 15px 20px;
                border-radius: 8px;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                margin-bottom: 20px;
                max-width: 600px;
            }
            .print-info h4 {
                margin: 0 0 10px 0;
                color: #1f2937;
                font-size: 16px;
            }
            .print-info p {
                margin: 5px 0;
                color: #6b7280;
                font-size: 13px;
            }
            @media print {
                @page {
                    size: A4;
                    margin: 3mm;
                }
                
                html, body {
                    width: 100%;
                    height: 100%;
                    margin: 0;
                    padding: 0;
                    background: white;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
                
                .print-controls,
                .print-info {
                    display: none !important;
                }
                
                .event-badge {
                    page-break-inside: avoid;
                    break-inside: avoid;
                    /* Scale badge to fill page */
                    width: 340px !important;
                    height: 500px !important;
                    transform: scale(2.18);
                    transform-origin: center;
                    margin: auto;
                    box-shadow: none !important;
                    border-radius: 0 !important;
                }
            }
        </style>
    </head>
    <body>
        <div class="print-info">
            <h4>🖨️ Badge Ready to Print</h4>
            <p><strong>Delegate:</strong> <?php echo htmlspecialchars($delegate['badge_name']); ?></p>
            <p><strong>Registration:</strong> <?php echo htmlspecialchars($delegate['registration_number']); ?></p>
            <p>Click the button below or press <strong>Ctrl+P</strong> (Cmd+P on Mac) to print</p>
        </div>
        
        <div class="print-controls">
            <button onclick="window.print()">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="6 9 6 2 18 2 18 9"></polyline>
                    <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path>
                    <rect x="6" y="14" width="12" height="8"></rect>
                </svg>
                Print Badge
            </button>
        </div>
        
        <?php echo $html; ?>
        
        <script>
            // Auto-open print dialog after page loads
            window.addEventListener('load', function() {
                setTimeout(function() {
                    window.print();
                }, 500); // Small delay to ensure everything is loaded
            });
        </script>
    </body>
    </html>
    <?php
    exit;
}

/**
 * Download Badge as PNG
 */
function downloadBadge($delegate_id, $settings, $pdo) {
    // For now, we'll redirect to a page that can be printed/saved
    // In production, you'd use a library like html2canvas (JS) or wkhtmltoimage (PHP)
    
    $html = generateBadgeHTML($delegate_id, $settings, $pdo);
    
    // Get delegate info for filename
    $stmt = $pdo->prepare("SELECT d.badge_name, r.registration_number FROM delegates d JOIN registrations r ON d.registration_id = r.id WHERE d.id = ?");
    $stmt->execute([$delegate_id]);
    $delegate = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $filename = 'badge_' . $delegate['registration_number'] . '.html';
    
    header('Content-Type: text/html; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Event Badge - <?php echo htmlspecialchars($delegate['badge_name']); ?></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;500;600;700;800;900&display=swap" rel="stylesheet">
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: 'Poppins', Arial, sans-serif;
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 100vh;
                background: #f3f4f6;
                padding: 20px;
            }
            .print-instructions {
                position: fixed;
                top: 20px;
                right: 20px;
                background: white;
                padding: 15px 20px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.1);
                max-width: 300px;
            }
            .print-instructions h4 {
                margin: 0 0 10px 0;
                color: #1f2937;
            }
            .print-instructions ol {
                margin: 0;
                padding-left: 20px;
                font-size: 13px;
                color: #6b7280;
            }
            .print-instructions li {
                margin-bottom: 5px;
            }
            @media print {
                body {
                    background: white;
                }
                .print-instructions {
                    display: none;
                }
            }
        </style>
    </head>
    <body>
        <div class="print-instructions">
            <h4>📄 How to Save as Image</h4>
            <ol>
                <li>Right-click on the badge</li>
                <li>Select "Take screenshot" or use your OS screenshot tool</li>
                <li>Or press Ctrl+P (Cmd+P on Mac) to print/save as PDF</li>
            </ol>
        </div>
        <?php echo $html; ?>
    </body>
    </html>
    <?php
    
    // Log badge generation
    $stmt = $pdo->prepare("INSERT INTO badge_generation_log (delegate_id, generation_type, file_path) VALUES (?, 'single', ?)");
    $stmt->execute([$delegate_id, $filename]);
    
    exit;
}

/**
 * Batch Generate Badges
 */
function batchGenerateBadges($type, $settings, $pdo) {
    // Get delegates based on type
    $where_clause = "";
    $params = [];
    
    if ($type === 'paid') {
        $where_clause = "WHERE r.payment_status = 'paid'";
    } elseif ($type === 'filtered') {
        $delegate_ids = explode(',', $_GET['delegate_ids'] ?? '');
        $placeholders = implode(',', array_fill(0, count($delegate_ids), '?'));
        $where_clause = "WHERE d.id IN ($placeholders)";
        $params = $delegate_ids;
    }
    
    $query = "
        SELECT d.id, d.badge_name, r.registration_number 
        FROM delegates d 
        JOIN registrations r ON d.registration_id = r.id 
        $where_clause
        ORDER BY d.id ASC
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $delegates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Generate HTML page with all badges
    header('Content-Type: text/html; charset=utf-8');
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Batch Badge Generation - <?php echo count($delegates); ?> Badges</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;500;600;700;800;900&display=swap" rel="stylesheet">
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: 'Poppins', Arial, sans-serif;
                background: #f3f4f6;
                padding: 20px;
            }
            .badge-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
                gap: 30px;
                max-width: 1400px;
                margin: 0 auto;
            }
            .badge-container {
                page-break-inside: avoid;
                break-inside: avoid;
            }
            .header {
                text-align: center;
                padding: 20px;
                background: white;
                border-radius: 12px;
                margin-bottom: 30px;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            }
            @media print {
                @page {
                    size: A4;
                    margin: 3mm;
                }
                
                body {
                    background: white;
                    padding: 0;
                }
                
                .header {
                    display: none;
                }
                
                .badge-grid {
                    display: block;
                }
                
                .badge-container {
                    page-break-after: always;
                    page-break-inside: avoid;
                    break-inside: avoid;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    min-height: 100vh;
                    padding: 0;
                }
                
                .badge-container:last-child {
                    page-break-after: auto;
                }
                
                .event-badge {
                    width: 340px !important;
                    height: 500px !important;
                    transform: scale(2.1);
                    transform-origin: center;
                    box-shadow: none !important;
                    border-radius: 0 !important;
                }
            }
        </style>
    </head>
    <body>
        <div class="header">
            <h1>Event Badges</h1>
            <p>Generated <?php echo count($delegates); ?> badges | Press Ctrl+P (Cmd+P) to print</p>
        </div>
        <div class="badge-grid">
            <?php foreach ($delegates as $delegate): ?>
            <div class="badge-container">
                <?php echo generateBadgeHTML($delegate['id'], $settings, $pdo); ?>
            </div>
            <?php endforeach; ?>
        </div>
    </body>
    </html>
    <?php
    
    // Log batch generation
    $stmt = $pdo->prepare("INSERT INTO badge_generation_log (generation_type, file_path) VALUES ('batch', ?)");
    $stmt->execute(["batch_{$type}_" . count($delegates) . "_badges.html"]);
    
    exit;
}

/**
 * Helper function to adjust color brightness
 */
function adjustColorBrightness($hex, $steps) {
    // Remove # if present
    $hex = str_replace('#', '', $hex);
    
    // Convert to RGB
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
    
    // Adjust
    $r = max(0, min(255, $r + $steps));
    $g = max(0, min(255, $g + $steps));
    $b = max(0, min(255, $b + $steps));
    
    // Convert back to hex
    return '#' . str_pad(dechex($r), 2, '0', STR_PAD_LEFT) . 
                 str_pad(dechex($g), 2, '0', STR_PAD_LEFT) . 
                 str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
}
?>

