<?php
// admin/trainings.php - Complete Training Session Management
require_once '../config/config.php';
require_login();

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

// --- Helper function for URL Encryption ---
// This function mimics the encryption used in corporate-feedback (1).php
function encrypt_training_id($id, $key) {
    // Generate a secure initialization vector
    $iv = openssl_random_pseudo_bytes(16);
    
    // Encrypt the ID
    $ciphertext = openssl_encrypt($id, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv);
    
    // Concatenate IV and ciphertext
    $encrypted = $iv . $ciphertext;
    
    // Base64 encode and make URL safe
    return str_replace(['+', '/'], ['-', '_'], base64_encode($encrypted));
}

// Key used for encryption/decryption in the feedback form (should match the key in corporate-feedback (1).php)
$encryption_key = "hG72kLmP94QwXc8tZbR1nT6pVfE3yU0A";


// Handle Create Training (Using tm_training fields)
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $course_name = $_POST['course_name'];
    $instructor_name = $_POST['instructor_name'];
    $client_name = $_POST['client_name']; // **NEW FIELD**
    $course_date = $_POST['course_date'];
    $course_time = $_POST['course_time'];
    $course_venue = $_POST['course_venue'];
    $status = $_POST['status'];
    
    // Note: 'created_at' is handled by the DB default (or NOW())
    $stmt = $pdo->prepare("
        INSERT INTO tm_training (course_name, instructor_name, client_name, course_date, course_time, course_venue, status, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([$course_name, $instructor_name, $client_name, $course_date, $course_time, $course_venue, $status]); // **ADDED client_name**
    
    set_flash('success', 'Training session created successfully!');
    redirect('admin/trainings.php');
}

// Handle Update Training (Using tm_training fields)
if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("
        UPDATE tm_training 
        SET course_name = ?, instructor_name = ?, client_name = ?, course_date = ?, course_time = ?, course_venue = ?, status = ?
        WHERE id = ?
    ");
    $stmt->execute([
        $_POST['course_name'], 
        $_POST['instructor_name'], 
        $_POST['client_name'], // **ADDED client_name**
        $_POST['course_date'], 
        $_POST['course_time'], 
        $_POST['course_venue'], 
        $_POST['status'], 
        $training_id
    ]);
    
    set_flash('success', 'Training session updated successfully!');
    redirect('admin/trainings.php');
}

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

// Get single training for editing
$training = null;
if ($action === 'edit' && $training_id) {
    // Ensure you select all columns including the new one
    $stmt = $pdo->prepare("SELECT * FROM tm_training WHERE id = ?");
    $stmt->execute([$training_id]);
    $training = $stmt->fetch();
}

// Get all trainings
$trainings = $pdo->query("SELECT * FROM tm_training 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 Training Sessions - <?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 Styles remain consistent */
        .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(#feedback-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'; // Assuming a navigation file exists ?>
    
    <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'): ?>
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-3xl font-bold text-gray-800">
                    <i class="fas fa-chalkboard-teacher text-blue-600 mr-2"></i> Manage Training Sessions
                </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> Schedule New Training
                </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">Course / Instructor</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Company</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date / Time / Venue</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 ($trainings as $t): 
                            // Encrypt the ID for the student link (using the same logic as the form file)
                            $encrypted_id = encrypt_training_id($t->id, $encryption_key);
                            // NOTE: Assumes the feedback form URL is located at 'student/corporate-feedback.php'
                            $feedback_url = base_url('student/corporate-feedback.php?training_id=' . $encrypted_id);
                        ?>
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="font-medium text-gray-900"><?php echo escape($t->course_name); ?></div>
                                <div class="text-sm text-gray-500">Instructor: <?php echo escape($t->instructor_name); ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <?php echo escape($t->client_name); ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <div class="font-medium"><?php echo escape($t->course_venue); ?></div>
                                <div class="text-sm text-gray-500">
                                    <?php echo date('M d, Y', strtotime($t->course_date)); ?> at <?php echo date('h:i A', strtotime($t->course_time)); ?>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                                    <?php 
                                        if ($t->status === 'completed') echo 'bg-blue-100 text-blue-800';
                                        elseif ($t->status === 'cancelled') echo 'bg-red-100 text-red-800';
                                        else echo 'bg-green-100 text-green-800';
                                    ?>">
                                    <?php echo ucfirst($t->status); ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-3">
                                <button onclick="openQRModal('<?php echo escape($t->course_name); ?>', '<?php echo $feedback_url; ?>', '<?php echo escape($t->instructor_name); ?>', '<?php echo escape($t->client_name); ?>')" 
                                    class="text-indigo-600 hover:text-indigo-900" title="Generate Feedback QR Code">
                                    <i class="fas fa-qrcode"></i> Feedback QR
                                </button>
                                <a href="?action=edit&id=<?php echo $t->id; ?>" 
                                    class="text-blue-600 hover:text-blue-900">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <a href="?action=delete&id=<?php echo $t->id; ?>" 
                                    onclick="return confirm('Delete this training session?')"
                                    class="text-red-600 hover:text-red-900">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($trainings)): ?>
                        <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 training sessions scheduled yet. Schedule your first training!</p>
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
        <?php elseif ($action === 'create' || $action === 'edit'): ?>
            <div class="max-w-3xl mx-auto">
                <h1 class="text-3xl font-bold text-gray-800 mb-6">
                    <?php echo $action === 'create' ? 'Schedule New Training' : 'Edit Training Session'; ?>
                </h1>
                
                <form method="POST" action="?action=<?php echo $action === 'create' ? 'create' : 'update'; ?>&id=<?php echo $training_id; ?>" 
                      class="bg-white rounded-xl shadow-lg p-8">
                    
                    <div class="mb-6">
                        <label class="block text-gray-700 font-semibold mb-2">Course Name *</label>
                        <input type="text" name="course_name" required 
                               value="<?php echo $training ? escape($training->course_name) : ''; ?>"
                               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">Instructor Name</label>
                            <input type="text" name="instructor_name" 
                                   value="<?php echo $training ? escape($training->instructor_name) : ''; ?>"
                                   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">Company Name</label>
                            <input type="text" name="client_name" 
                                   value="<?php echo $training ? escape($training->client_name) : ''; ?>"
                                   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">Course Venue (e.g., Virtual, Hotel)</label>
                         <input type="text" name="course_venue" 
                                value="<?php echo $training ? escape($training->course_venue) : ''; ?>"
                                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-3 gap-6 mb-6">
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">Course Date *</label>
                            <input type="date" name="course_date" required 
                                   value="<?php echo $training ? $training->course_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">Course Time</label>
                            <input type="time" name="course_time" 
                                   value="<?php echo $training ? $training->course_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>
                            <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="scheduled" <?php echo ($training && $training->status === 'scheduled') ? 'selected' : ''; ?>>Scheduled</option>
                                <option value="completed" <?php echo ($training && $training->status === 'completed') ? 'selected' : ''; ?>>Completed</option>
                                <option value="cancelled" <?php echo ($training && $training->status === 'cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                            </select>
                        </div>
                    </div>
                    
                    <?php if ($training): 
                        $encrypted_id = encrypt_training_id($training->id, $encryption_key);
                        $feedback_url = base_url('student/corporate-feedback.php?training_id=' . $encrypted_id);
                    ?>
                    <div class="mb-6 bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <p class="text-sm text-gray-700"><strong>Feedback Link (Training ID: <?php echo $training->id; ?>):</strong></p>
                        <p class="text-blue-600 font-mono text-sm break-all">
                            <?php echo $feedback_url; ?>
                        </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' ? 'Schedule Training' : 'Update Training'; ?>
                        </button>
                    </div>
                </form>
            </div>
        <?php endif; ?>
    </div>

    <div id="feedback-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> Training Feedback 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">
                    <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 Card
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let qrCodeInstance = null;
        let currentTrainingTitle = '';
        let currentFeedbackUrl = '';
        let currentInstructor = ''; 
        let currentClient = ''; // **NEW VARIABLE**
        const modalId = 'feedback-qr-modal';

        function openQRModal(trainingTitle, feedbackUrl, instructor, client) { // **ADDED client ARGUMENT**
            currentTrainingTitle = trainingTitle;
            currentFeedbackUrl = feedbackUrl;
            currentInstructor = instructor;
            currentClient = client; // **STORED NEW VARIABLE**
            
            document.getElementById(modalId).classList.add('active');
            document.body.style.overflow = 'hidden';
            
            // Auto-generate on open
            setTimeout(() => generateQR(), 100);
        }

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

        function generateQR() {
            const size = 280; 
            const color = '#004B75'; // TTC Dark Blue
            const logoUrl = 'https://www.edoxi.com/assets/images/edoxi-logo.svg'; 
            
            const printableWrapper = document.getElementById('printable-card-wrapper');
            printableWrapper.innerHTML = '';
            qrCodeInstance = null;
            
            // Build printable card
            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`;
            
            // Time Training Center Logo
            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 = () => {
                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);
            
            // Training Title
            const titleSpan = document.createElement('h2');
            titleSpan.className = 'text-lg font-bold text-gray-800 mb-2 leading-tight uppercase';
            titleSpan.textContent = currentTrainingTitle;
            printableCard.appendChild(titleSpan);
            
            // **NEW: Client Detail**
            if (currentClient) {
                const clientSpan = document.createElement('p');
                clientSpan.className = 'text-sm font-semibold text-blue-600 mb-2';
                clientSpan.textContent = 'Company: ' + currentClient;
                printableCard.appendChild(clientSpan);
            }
            // End New: Client Detail
            
            // Instructor Detail
            if (currentInstructor) {
                const instructorSpan = document.createElement('p');
                instructorSpan.className = 'text-sm text-gray-500 mb-4';
                instructorSpan.textContent = 'Instructor: ' + currentInstructor;
                printableCard.appendChild(instructorSpan);
            }
            
            // 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 Feedback Text
            const cta = document.createElement('p');
            cta.className = 'text-xl font-bold mt-4 text-blue-800 uppercase tracking-wide';
            cta.textContent = 'Scan to Provide Feedback';
            printableCard.appendChild(cta);
            
            // Instruction
            const instruction = document.createElement('p');
            instruction.className = 'text-xs mt-2 text-gray-600 mb-2';
            instruction.textContent = 'Use your phone camera to scan the code';
            printableCard.appendChild(instruction);
            
            printableWrapper.appendChild(printableCard);
            
            // Generate QR
            try {
                qrCodeInstance = new QRCode(qrBox, {
                    text: currentFeedbackUrl,
                    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 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(modalId).addEventListener('click', function(e) {
            if (e.target === this) {
                closeQRModal();
            }
        });
    </script>
</body>
</html>