<?php
// admin/exams.php - Complete Exam Management
require_once '../config/config.php';
require_login();

$action = $_GET['action'] ?? 'list';
$exam_id = $_GET['id'] ?? null;

// Handle Create Exam
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'];
    $duration = $_POST['duration'];
    $instructions = $_POST['instructions'];
    $passing_marks = $_POST['passing_marks'];
    $exam_date = $_POST['exam_date'];
    $exam_time = $_POST['exam_time'];
    $status = $_POST['status'];
    $show_result = isset($_POST['show_result']) ? 1 : 0;
    
    // Generate unique token
    $exam_token = bin2hex(random_bytes(5));
    
    $stmt = $pdo->prepare("
        INSERT INTO exams (title, duration, instructions, passing_marks, exam_date, exam_time, exam_token, status, show_result)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([$title, $duration, $instructions, $passing_marks, $exam_date, $exam_time, $exam_token, $status, $show_result]);
    
    set_flash('success', 'Exam created successfully!');
    redirect('admin/exams.php');
}

// Handle Update Exam
if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("
        UPDATE exams 
        SET title = ?, duration = ?, instructions = ?, passing_marks = ?, 
            exam_date = ?, exam_time = ?, status = ?, show_result = ?
        WHERE id = ?
    ");
    $stmt->execute([
        $_POST['title'], $_POST['duration'], $_POST['instructions'], 
        $_POST['passing_marks'], $_POST['exam_date'], $_POST['exam_time'],
        $_POST['status'], isset($_POST['show_result']) ? 1 : 0, $exam_id
    ]);
    
    set_flash('success', 'Exam updated successfully!');
    redirect('admin/exams.php');
}

// Handle Delete Exam
if ($action === 'delete' && $exam_id) {
    $stmt = $pdo->prepare("DELETE FROM exams WHERE id = ?");
    $stmt->execute([$exam_id]);
    set_flash('success', 'Exam deleted successfully!');
    redirect('admin/exams.php');
}

// Get single exam for editing
$exam = null;
if ($action === 'edit' && $exam_id) {
    $stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ?");
    $stmt->execute([$exam_id]);
    $exam = $stmt->fetch();
}

// Get all exams
$exams = $pdo->query("SELECT * FROM exams ORDER BY created_at DESC")->fetchAll();
$flash = get_flash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Exams - <?php echo APP_NAME; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dom-to-image-more@2.11.23/dist/dom-to-image-more.min.js"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s ease;
        }
        
        .modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .modal-content {
            background-color: #fefefe;
            padding: 0;
            border-radius: 16px;
            max-width: 600px;
            width: 90%;
            max-height: none;
            overflow: visible;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        #printable-card {
            background-color: #ffffff;
            font-family: 'Inter', sans-serif;
        }
        
        .qr-wrapper {
            position: relative;
            display: inline-block;
            padding: 1rem;
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        @media print {
            body > *:not(#qr-modal) {
                visibility: hidden;
            }
            #printable-card-wrapper, #printable-card-wrapper * {
                visibility: visible;
            }
            #printable-card-wrapper {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                margin: 0;
                padding: 1cm;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            #printable-card {
                border: none;
                box-shadow: none;
            }
        }
    </style>
</head>
<body class="bg-gray-100">
    <?php include 'includes/nav.php'; ?>
    
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <?php if ($flash): ?>
            <div class="mb-6 bg-<?php echo $flash['type'] === 'success' ? 'green' : 'red'; ?>-50 border-l-4 border-<?php echo $flash['type'] === 'success' ? 'green' : 'red'; ?>-500 p-4 rounded-lg">
                <p class="text-<?php echo $flash['type'] === 'success' ? 'green' : 'red'; ?>-700">
                    <?php echo escape($flash['message']); ?>
                </p>
            </div>
        <?php endif; ?>
        
        <?php if ($action === 'list'): ?>
            <!-- List Exams -->
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-3xl font-bold text-gray-800">
                    <i class="fas fa-file-alt text-blue-600 mr-2"></i> Manage Exams
                </h1>
                <a href="?action=create" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition flex items-center">
                    <i class="fas fa-plus mr-2"></i> Create New Exam
                </a>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Title</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Duration</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($exams as $e): ?>
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="font-medium text-gray-900"><?php echo escape($e->title); ?></div>
                                <div class="text-sm text-gray-500">Marks: <?php echo $e->total_marks; ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <?php echo $e->duration; ?> min
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <?php echo date('M d, Y', strtotime($e->exam_date)); ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                                    <?php echo $e->status === 'published' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'; ?>">
                                    <?php echo ucfirst($e->status); ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-3">
                                <button onclick="openQRModal('<?php echo escape($e->title); ?>', '<?php echo base_url('student/register.php?token=' . $e->exam_token); ?>', '<?php echo escape($e->exam_date); ?>')" 
                                   class="text-indigo-600 hover:text-indigo-900" title="Generate QR Code">
                                    <i class="fas fa-qrcode"></i> QR
                                </button>
                                <a href="<?php echo base_url('admin/questions.php?action=assign&exam_id=' . $e->id); ?>" 
                                   class="text-purple-600 hover:text-purple-900">
                                    <i class="fas fa-tasks"></i> Assign
                                </a>
                                <a href="?action=edit&id=<?php echo $e->id; ?>" 
                                   class="text-blue-600 hover:text-blue-900">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <a href="?action=delete&id=<?php echo $e->id; ?>" 
                                   onclick="return confirm('Delete this exam?')"
                                   class="text-red-600 hover:text-red-900">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($exams)): ?>
                        <tr>
                            <td colspan="5" class="px-6 py-12 text-center text-gray-500">
                                <i class="fas fa-inbox text-4xl mb-2"></i>
                                <p>No exams created yet. Create your first exam!</p>
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
        <?php elseif ($action === 'create' || $action === 'edit'): ?>
            <!-- Create/Edit Exam Form -->
            <div class="max-w-3xl mx-auto">
                <h1 class="text-3xl font-bold text-gray-800 mb-6">
                    <?php echo $action === 'create' ? 'Create New Exam' : 'Edit Exam'; ?>
                </h1>
                
                <form method="POST" action="?action=<?php echo $action === 'create' ? 'create' : 'update'; ?>&id=<?php echo $exam_id; ?>" 
                      class="bg-white rounded-xl shadow-lg p-8">
                    
                    <div class="mb-6">
                        <label class="block text-gray-700 font-semibold mb-2">Exam Title *</label>
                        <input type="text" name="title" required 
                               value="<?php echo $exam ? escape($exam->title) : ''; ?>"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    </div>
                    
                    <div class="grid grid-cols-2 gap-6 mb-6">
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">Duration (minutes) *</label>
                            <input type="number" name="duration" required 
                                   value="<?php echo $exam ? $exam->duration : ''; ?>"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        </div>
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">Passing Marks *</label>
                            <input type="number" name="passing_marks" required step="0.01"
                                   value="<?php echo $exam ? $exam->passing_marks : ''; ?>"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-6 mb-6">
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">Exam Date *</label>
                            <input type="date" name="exam_date" required 
                                   value="<?php echo $exam ? $exam->exam_date : ''; ?>"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        </div>
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">Exam Time *</label>
                            <input type="time" name="exam_time" required 
                                   value="<?php echo $exam ? $exam->exam_time : ''; ?>"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        </div>
                    </div>
                    
                    <div class="mb-6">
                        <label class="block text-gray-700 font-semibold mb-2">Instructions</label>
                        <textarea name="instructions" rows="5"
                                  class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"><?php echo $exam ? escape($exam->instructions) : ''; ?></textarea>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-6 mb-6">
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">Status *</label>
                            <select name="status" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                <option value="unpublished" <?php echo ($exam && $exam->status === 'unpublished') ? 'selected' : ''; ?>>Unpublished</option>
                                <option value="published" <?php echo ($exam && $exam->status === 'published') ? 'selected' : ''; ?>>Published</option>
                            </select>
                        </div>
                        <div class="flex items-center pt-8">
                            <input type="checkbox" name="show_result" id="show_result" 
                                   <?php echo (!$exam || $exam->show_result) ? 'checked' : ''; ?>
                                   class="w-5 h-5 text-blue-600 border-gray-300 rounded focus:ring-2 focus:ring-blue-500">
                            <label for="show_result" class="ml-2 text-gray-700 font-semibold">Show Result to Students</label>
                        </div>
                    </div>
                    
                    <?php if ($exam): ?>
                    <div class="mb-6 bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <p class="text-sm text-gray-700"><strong>Student Registration Link:</strong></p>
                        <p class="text-blue-600 font-mono text-sm break-all">
                            <?php echo base_url('student/register.php?token=' . $exam->exam_token); ?>
                        </p>
                    </div>
                    <?php endif; ?>
                    
                    <div class="flex justify-end space-x-4">
                        <a href="?action=list" class="px-6 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">
                            Cancel
                        </a>
                        <button type="submit" class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                            <i class="fas fa-save mr-2"></i> <?php echo $action === 'create' ? 'Create Exam' : 'Update Exam'; ?>
                        </button>
                    </div>
                </form>
            </div>
        <?php endif; ?>
    </div>

    <!-- QR Code Modal -->
    <div id="qr-modal" class="modal">
        <div class="modal-content">
            <div class="bg-gradient-to-r from-blue-600 to-purple-600 text-white p-4 rounded-t-2xl">
                <div class="flex justify-between items-center">
                    <h2 class="text-lg font-bold">
                        <i class="fas fa-qrcode mr-2"></i> Assessment QR Code
                    </h2>
                    <button onclick="closeQRModal()" class="text-white hover:text-gray-200 text-xl">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            
            <div class="p-6">
                <div class="flex flex-col items-center">
                    <!-- Preview Panel -->
                    <div id="qr-code-output" class="w-full flex justify-center mb-4">
                        <div id="printable-card-wrapper" class="bg-white rounded-xl shadow-lg">
                            <p class="text-gray-500 text-center p-8">Generating QR Code...</p>
                        </div>
                    </div>
                    
                    <div class="flex gap-3">
                        
                        <button onclick="printCard()" 
                                class="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition text-sm">
                            <i class="fas fa-print mr-2"></i> Print
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let qrCodeInstance = null;
        let currentExamTitle = '';
        let currentExamUrl = '';
        let currentExamDate = '';

        function openQRModal(examTitle, examUrl, examDate) {
            currentExamTitle = examTitle;
            currentExamUrl = examUrl;
            currentExamDate = examDate;
            
            document.getElementById('qr-modal').classList.add('active');
            document.body.style.overflow = 'hidden';
            
            // Auto-generate on open
            setTimeout(() => generateQR(), 100);
        }

        function closeQRModal() {
            document.getElementById('qr-modal').classList.remove('active');
            document.body.style.overflow = '';
        }

        function generateQR() {
            const size = 280; // Smaller size for compact popup
            const color = '#1E3A8A'; // Blue color
            const logoUrl = 'https://assessment.edoxi.cyradrive.com/assets/01.png'; // Edoxi Training Center logo
            
            const printableWrapper = document.getElementById('printable-card-wrapper');
            printableWrapper.innerHTML = '';
            qrCodeInstance = null;
            
            // Build printable card - more compact
            const printableCard = document.createElement('div');
            printableCard.id = 'printable-card';
            printableCard.className = 'bg-white text-center p-6 flex flex-col items-center';
            printableCard.style.width = `${size + 80}px`;
            
            // Edoxi Training Center Logo - smaller
            const topLogo = document.createElement('img');
            topLogo.src = logoUrl;
            topLogo.alt = 'Edoxi Training Center';
            topLogo.className = 'mb-4';
            topLogo.style.maxHeight = '60px';
            topLogo.style.width = 'auto';
            topLogo.onerror = () => {
                // Fallback: Create text logo if image not found
                const textLogo = document.createElement('div');
                textLogo.className = 'text-xl font-bold text-blue-800 mb-4';
                textLogo.textContent = 'EDOXI TRAINING CENTER';
                printableCard.replaceChild(textLogo, topLogo);
            };
            topLogo.crossOrigin = 'anonymous';
            printableCard.appendChild(topLogo);
            
            // Exam Title - compact
            const titleSpan = document.createElement('h2');
            titleSpan.className = 'text-lg font-bold text-gray-800 mb-4 leading-tight uppercase';
            titleSpan.textContent = currentExamTitle;
            printableCard.appendChild(titleSpan);
            
            // QR Container
            const qrContainer = document.createElement('div');
            qrContainer.className = 'qr-wrapper mx-auto my-3';
            
            const qrBox = document.createElement('div');
            qrBox.id = 'qr-box';
            qrBox.style.width = `${size}px`;
            qrBox.style.height = `${size}px`;
            qrContainer.appendChild(qrBox);
            printableCard.appendChild(qrContainer);
            
            // Scan for Assessment Text - compact
            const cta = document.createElement('p');
            cta.className = 'text-xl font-bold mt-4 text-blue-800 uppercase tracking-wide';
            cta.textContent = 'Scan for Assessment';
            printableCard.appendChild(cta);
            
            // Instruction - smaller
            const instruction = document.createElement('p');
            instruction.className = 'text-xs mt-2 text-gray-600 mb-2';
            instruction.textContent = 'Use your phone camera to scan';
            printableCard.appendChild(instruction);
            
            printableWrapper.appendChild(printableCard);
            
            // Generate QR
            try {
                qrCodeInstance = new QRCode(qrBox, {
                    text: currentExamUrl,
                    width: size,
                    height: size,
                    colorDark: color,
                    colorLight: "#ffffff",
                    correctLevel: QRCode.CorrectLevel.H
                });
            } catch (error) {
                console.error("QR Code generation failed:", error);
                printableWrapper.innerHTML = '<p class="text-red-500 text-center p-8">Error generating QR Code</p>';
            }
        }

        function downloadFullCardPNG() {
            const printableCard = document.getElementById('printable-card');
            
            if (!printableCard) {
                alert('Please wait for QR code to generate');
                return;
            }
            
            const originalBoxShadow = printableCard.style.boxShadow;
            const originalBorder = printableCard.style.border;
            printableCard.style.boxShadow = 'none';
            printableCard.style.border = 'none';
            
            const options = { 
                bgcolor: '#ffffff',
                cacheBust: true,
                quality: 0.95,
                width: printableCard.offsetWidth,
                height: printableCard.offsetHeight
            };

            domtoimage.toPng(printableCard, options)
                .then(function (dataUrl) {
                    const link = document.createElement('a');
                    link.download = `${currentExamTitle.replace(/[^a-z0-9]/gi, '_')}_Assessment_QR.png`;
                    link.href = dataUrl;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);

                    printableCard.style.boxShadow = originalBoxShadow;
                    printableCard.style.border = originalBorder;
                })
                .catch(function (error) {
                    console.error('Error capturing card:', error);
                    alert('Download failed. Please try the Print option for PDF export.');
                    
                    printableCard.style.boxShadow = originalBoxShadow;
                    printableCard.style.border = originalBorder;
                });
        }

        function printCard() {
            window.print();
        }

        // Close modal on escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeQRModal();
            }
        });

        // Close modal on outside click
        document.getElementById('qr-modal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeQRModal();
            }
        });
    </script>
</body>
</html>