<?php 
// 1. Database Connection and Logic (Before any HTML output)
require_once '../db_connect.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check Exam ID from URL
if (!isset($_GET['exam_id'])) {
    header("Location: manage_exams.php");
    exit;
}

$exam_id = (int)$_GET['exam_id'];

// Fetch Exam Info
$exam_stmt = $pdo->prepare("SELECT exam_title, total_questions FROM exams WHERE id = ?");
$exam_stmt->execute([$exam_id]);
$exam_data = $exam_stmt->fetch();

if (!$exam_data) {
    die("<div class='p-5 text-center fw-bold text-danger'>Invalid Exam ID!</div>");
}

// 2. Form Submission Logic
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $pdo->beginTransaction();
    try {
        // Delete existing questions for this exam to prevent duplicates
        $pdo->prepare("DELETE FROM questions WHERE exam_id = ?")->execute([$exam_id]);

        $sql = "INSERT INTO questions (exam_id, question_text, option_a, option_b, option_c, option_d, correct_option) VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);

        // Loop to save each question
        for ($i = 0; $i < count($_POST['q']); $i++) {
            if(!empty($_POST['q'][$i])) {
                $stmt->execute([
                    $exam_id, 
                    $_POST['q'][$i], 
                    $_POST['oa'][$i], 
                    $_POST['ob'][$i], 
                    $_POST['oc'][$i], 
                    $_POST['od'][$i], 
                    $_POST['ans'][$i]
                ]);
            }
        }
        
        $pdo->commit();
        header("Location: manage_exams.php?status=updated");
        exit;
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = "Error: " . $e->getMessage();
    }
}

// 3. Include UI Components
include 'includes/header.php'; 
include 'includes/sidebar.php'; 

// 4. English Date
$current_date = date('d F Y, l');
?>

<style>
    /* Premium Theme Colors */
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 25px; border-left: 6px solid var(--theme-green); }
    .question-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 18px; box-shadow: 0 10px 40px rgba(0,0,0,0.03); padding: 30px; margin-bottom: 30px; border-left: 6px solid var(--theme-gold); }
    
    .date-badge { background: rgba(6, 78, 59, 0.05); color: var(--theme-green); padding: 7px 18px; border-radius: 50px; font-size: 13px; font-weight: 700; border: 1px solid rgba(6, 78, 59, 0.1); display: inline-block; }
    
    .form-label { font-weight: 700; color: #64748b; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; }
    .form-control, .form-select { border-radius: 12px; padding: 12px 18px; border: 2px solid #f1f5f9; background-color: var(--bg-soft); transition: 0.3s; font-size: 14px; font-weight: 500;}
    .form-control:focus, .form-select:focus { border-color: var(--theme-green); background-color: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); outline: none; }
    
    .option-prefix { min-width: 45px; background: #fff; border: 2px solid #f1f5f9; border-right: 0; border-radius: 12px 0 0 12px; display: flex; align-items: center; justify-content: center; font-weight: 800; color: var(--theme-green); }
    .option-input { border-left: 0; border-radius: 0 12px 12px 0; }

    .btn-submit { background: var(--theme-green); color: #fff; padding: 16px 50px; border-radius: 12px; font-weight: 800; font-size: 17px; border: none; transition: 0.3s; box-shadow: 0 8px 20px rgba(6, 78, 59, 0.2); }
    .btn-submit:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-3px); }

    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } }

    /* --- 📱 Mobile Responsive Fixes --- */
    @media (max-width: 768px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { flex-direction: column; align-items: flex-start !important; gap: 15px; padding: 15px 20px; }
        .dashboard-header .d-flex { width: 100%; align-items: center; }
        .dashboard-header > a { width: 100%; justify-content: center; } 
        
        #sidebarToggle { width: 42px !important; height: 42px !important; padding: 0; display: inline-flex !important; align-items: center; justify-content: center; flex-shrink: 0; border-radius: 8px;}
        .question-card { padding: 20px !important; }
    }
</style>

<div class="main-content p-4" style="background: var(--bg-soft); min-height: 100vh;">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="d-flex align-items-center">
            <button class="btn btn-light border d-md-none me-3 shadow-sm" id="sidebarToggle">
                <i class="fas fa-bars text-dark"></i>
            </button>
            <div>
                <h4 class="mb-1 fw-bold text-dark"><i class="fas fa-edit me-2" style="color: var(--theme-green);"></i> Create Questions</h4>
                <div class="date-badge"><i class="far fa-calendar-alt me-2"></i><?= $current_date; ?></div>
            </div>
        </div>
        <a href="manage_exams.php" class="btn btn-light border px-4 py-2 rounded-pill fw-bold shadow-sm text-dark text-decoration-none mt-3 mt-md-0">
            <i class="fas fa-arrow-left me-2"></i> Back to List
        </a>
    </div>

    <div class="mb-4 fade-up">
        <h5 class="fw-bold" style="color: var(--theme-dark);">Exam: <span style="color: var(--theme-green);"><?= htmlspecialchars($exam_data['exam_title']) ?></span></h5>
        <span class="badge bg-danger px-3 py-2 rounded-pill shadow-sm">Required Questions: <?= $exam_data['total_questions'] ?></span>
    </div>

    <?php if(isset($error)): ?> 
        <div class="alert alert-danger border-0 border-start border-4 border-danger shadow-sm bg-white fw-bold mb-4">
            <i class="fas fa-exclamation-triangle me-2"></i> <?= $error ?>
        </div>
    <?php endif; ?>

    <form action="" method="POST" class="fade-up" style="animation-delay: 0.1s;">
        <?php for ($i = 1; $i <= $exam_data['total_questions']; $i++): ?>
        <div class="question-card">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h6 class="fw-bold m-0" style="color: var(--theme-green);">Question Number: <?= sprintf("%02d", $i); ?></h6>
            </div>
            
            <div class="mb-4">
                <label class="form-label">Question Text</label>
                <textarea name="q[]" class="form-control" rows="2" placeholder="Type your question here..." required></textarea>
            </div>
            
            <div class="row g-4 mb-4">
                <div class="col-md-6">
                    <label class="form-label">Option A</label>
                    <div class="d-flex">
                        <div class="option-prefix">A</div>
                        <input type="text" name="oa[]" class="form-control option-input" placeholder="Enter option A" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Option B</label>
                    <div class="d-flex">
                        <div class="option-prefix">B</div>
                        <input type="text" name="ob[]" class="form-control option-input" placeholder="Enter option B" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Option C</label>
                    <div class="d-flex">
                        <div class="option-prefix">C</div>
                        <input type="text" name="oc[]" class="form-control option-input" placeholder="Enter option C" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Option D</label>
                    <div class="d-flex">
                        <div class="option-prefix">D</div>
                        <input type="text" name="od[]" class="form-control option-input" placeholder="Enter option D" required>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-4">
                    <label class="form-label" style="color: #ef4444;">Select Correct Answer</label>
                    <select name="ans[]" class="form-select fw-bold" style="color: var(--theme-green);" required>
                        <option value="a">Option A</option>
                        <option value="b">Option B</option>
                        <option value="c">Option C</option>
                        <option value="d">Option D</option>
                    </select>
                </div>
            </div>
        </div>
        <?php endfor; ?>

        <div class="text-center pb-5 mt-4">
            <button type="submit" class="btn-submit">
                <i class="fas fa-save me-2"></i> Save All Questions
            </button>
        </div>
    </form>
</div>

<script>
    // Mobile Sidebar Toggle Script
    document.addEventListener("DOMContentLoaded", function() {
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const sidebar = document.querySelector('.sidebar');
                if (sidebar) { sidebar.classList.toggle('active'); }
            });
        }
    });
</script>

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