<?php
// 1. REVEAL CRITICAL ERRORS SEAMLESSLY IF SOMETHING CRASHES
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once 'db.php';

$message = "";

// 2. OPTION A: MANUAL FORM ENGINE INPUT LOGIC
if (isset($_POST['add_manual_question'])) {
    try {
        $stmt = $pdo->prepare("INSERT INTO questions (course_id, question_text, option_a, option_b, option_c, option_d, correct_option) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            intval($_POST['course_id']), 
            trim($_POST['q_text']), 
            trim($_POST['opt_a']), 
            trim($_POST['opt_b']), 
            trim($_POST['opt_c']), 
            trim($_POST['opt_d']), 
            strtoupper(trim($_POST['correct']))
        ]);
        $message = "<div class='alert alert-success'>✅ Success: Individual Question Saved to Bank!</div>";
    } catch (\PDOException $e) { 
        $message = "<div class='alert alert-danger'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</div>"; 
    }
}

// 3. OPTION B: FIXED HIGH-ACCURACY BULK CSV IMPORT PIPELINE
if (isset($_POST['import_questions_csv'])) {
    if (isset($_FILES['question_csv']) && $_FILES['question_csv']['error'] == 0) {
        $file = fopen($_FILES['question_csv']['tmp_name'], "r");
        $headers = fgetcsv($file, 1000, ",");
        
        if ($headers !== FALSE) {
            $headers = array_map(function($h) { return strtolower(trim($h)); }, $headers);
            
            $idx_course  = array_search('course_id', $headers);
            $idx_text    = array_search('question_text', $headers);
            $idx_opt_a   = array_search('option_a', $headers);
            $idx_opt_b   = array_search('option_b', $headers);
            $idx_opt_c   = array_search('option_c', $headers);
            $idx_opt_d   = array_search('option_d', $headers);
            $idx_correct = array_search('correct_option', $headers);

            if ($idx_course !== false && $idx_text !== false && $idx_opt_a !== false && $idx_opt_b !== false && $idx_opt_c !== false && $idx_opt_d !== false && $idx_correct !== false) {
                $count = 0;
                $errors = 0;
                try {
                    $stmt = $pdo->prepare("INSERT INTO questions (course_id, question_text, option_a, option_b, option_c, option_d, correct_option) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    while (($row = fgetcsv($file, 1000, ",")) !== FALSE) {
                        if (empty($row) || count($row) < 7) continue;
                        try {
                            $stmt->execute([
                                intval($row[$idx_course]),
                                trim($row[$idx_text]),
                                trim($row[$idx_opt_a]),
                                trim($row[$idx_opt_b]),
                                trim($row[$idx_opt_c]),
                                trim($row[$idx_opt_d]),
                                strtoupper(trim($row[$idx_correct]))
                            ]);
                            $count++;
                        } catch (\PDOException $ex) { $errors++; }
                    }
                    $message = ($errors > 0) ? "<div class='alert alert-warning'>⚠️ Imported $count questions, skipped $errors duplicates.</div>" : "<div class='alert alert-success'>✅ Success: Bulk Imported $count Questions from CSV!</div>";
                } catch (\PDOException $e) { $message = "<div class='alert alert-danger'>❌ Query Fault: " . htmlspecialchars($e->getMessage()) . "</div>"; }
            } else { $message = "<div class='alert alert-danger'>❌ CSV Error: Missing required structural column headers!</div>"; }
        } else { $message = "<div class='alert alert-danger'>❌ Error: Uploaded file is blank.</div>"; }
        fclose($file);
    } else { $message = "<div class='alert alert-danger'>❌ System Exception: No file selected or server error.</div>"; }
}

try { $courses = $pdo->query("SELECT * FROM courses ORDER BY course_code ASC")->fetchAll(); } catch(\Exception $e) { $courses = []; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Questions Portal</title>
    <style>
        body { font-family: Arial, sans-serif; background: #fff; padding: 15px; color: #333; margin: 0; }
        .sub-nav { display: flex; gap: 10px; background: #f1f3f5; padding: 10px; margin-bottom: 20px; border-radius: 4px; }
        .sub-btn { padding: 8px 16px; background: #fff; border: 1px solid #ccc; cursor: pointer; font-weight: bold; border-radius: 4px; font-size: 13px; }
        .sub-btn.active { background: #6f42c1; color: white; border-color: #6f42c1; }
        .sub-btn.active-green { background: #28a745; color: white; border-color: #28a745; }
        .pane-view { display: none; } .pane-view.active { display: block; }
        .card { background: #fdfdfd; padding: 22px; border: 1px solid #dee2e6; border-radius: 6px; box-shadow: 0 1px 4px rgba(0,0,0,0.04); }
        input, select { width: 100%; padding: 11px; margin: 8px 0; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; }
        .btn { padding: 11px 20px; background: #28a745; color: white; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; font-size: 14px; width: 100%; }
        .btn-csv { background: #6f42c1; }
        .csv-note { background: #f8f9fa; border-left: 4px solid #6f42c1; padding: 12px; font-size: 12px; margin: 10px 0; color: #444; line-height: 1.5; }
        .alert { padding: 12px; border-radius: 4px; margin-bottom: 18px; font-weight: bold; font-size: 14px; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-danger { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .alert-warning { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
    </style>
</head>
<body>

    <h2 style="color: #333; margin-top: 5px; border-bottom: 1px solid #eee; padding-bottom: 8px; font-size: 20px;">CBT Examination Questions Manager</h2>
    
    <?php echo $message; ?>

    <!-- 🛠️ CACHE-BREAKING SELECTION NAVIGATION TOGGLES -->
    <div class="sub-nav">
        <button id="btn1" class="sub-btn active-green" onclick="togglePane('manual', 'btn1')">📝 Add Single Question</button>
        <button id="btn2" class="sub-btn" onclick="togglePane('bulk', 'btn2')">📤 Bulk Import via CSV File</button>
    </div>

    <!-- ENTRY PANE 1: MANUAL SINGLE INPUTS -->
    <div id="manual_pane" class="pane-view active">
        <div class="card" style="border-top: 4px solid #28a745;">
            <h4 style="margin-top:0; color:#28a745; font-size: 15px;">Method A: Add Single Question One by One</h4>
            <form method="POST" action="upload_question.php">
                <select name="course_id" required>
                    <?php if(empty($courses)): ?>
                        <option value="1">[COM111] Introduction to Computing</option>
                    <?php else: ?>
                        <?php foreach ($courses as $c): ?>
                            <option value="<?php echo $c['id']; ?>">[<?php echo htmlspecialchars($c['course_code']); ?>] - <?php echo htmlspecialchars($c['course_title']); ?></option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
                <input type="text" name="q_text" placeholder="Type examination question main prompt text body here" required autocomplete="off">
                <input type="text" name="opt_a" placeholder="Enter display string for Option A" required autocomplete="off">
                <input type="text" name="opt_b" placeholder="Enter display string for Option B" required autocomplete="off">
                <input type="text" name="opt_c" placeholder="Enter display string for Option C" required autocomplete="off">
                <input type="text" name="opt_d" placeholder="Enter display string for Option D" required autocomplete="off">
                <select name="correct" required>
                    <option value="A">Correct answer selection matches: A</option>
                    <option value="B">Correct answer selection matches: B</option>
                    <option value="C">Correct answer selection matches: C</option>
                    <option value="D">Correct answer selection matches: D</option>
                </select>
                <button type="submit" name="add_manual_question" class="btn">Save Question to Bank</button>
            </form>
        </div>
    </div>

    <!-- ENTRY PANE 2: BULK SPREADSHEET UPLOADER METHOD -->
    <div id="bulk_pane" class="pane-view">
        <div class="card" style="border-top: 4px solid #6f42c1;">
            <h4 style="margin-top:0; color:#6f42c1; font-size: 15px;">Method B: Bulk Upload Questions via CSV File Spreadsheet</h4>
            <div class="csv-note">
                <strong>📋 Formatting Requirement Rules Checklist:</strong><br>
                Your data table row array parameters **MUST** contain these exact headers in row 1:<br>
                <code style="background: #fff; padding: 4px; border: 1px solid #ddd; display: block; margin-top: 6px; font-family: monospace; font-weight: bold; color: #c7254e;">course_id, question_text, option_a, option_b, option_c, option_d, correct_option</code>
            </div>
            <form method="POST" enctype="multipart/form-data" action="upload_question.php">
                <input type="file" name="question_csv" accept=".csv" required style="background: #f8f9fa; border: 1px dashed #ccc; padding: 15px; margin-bottom: 10px;">
                <button type="submit" name="import_questions_csv" class="btn btn-csv">Execute Bulk Question Import</button>
            </form>
        </div>
    </div>

<script>
    function togglePane(pane, btnId) {
        document.getElementById("manual_pane").classList.remove("active");
