<?php
// teacher/add_questions_manual.php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../config/database.php';

// 1. SECURITY: Teachers only
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'teacher') {
    header("Location: ../auth/login.php"); exit();
}

$teacher_id = (int)$_SESSION['user_id'];
$exam_id = isset($_GET['exam_id']) ? (int)$_GET['exam_id'] : null;

if (!$exam_id) {
    header("Location: manage_exams.php"); exit();
}

// 2. VERIFY OWNERSHIP & FETCH EXAM DETAILS
$stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ? AND teacher_id = ? AND is_deleted = 0");
$stmt->execute([$exam_id, $teacher_id]);
$exam = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$exam) {
    die("Unauthorized or Exam not found.");
}

$message = "";

// 3. ACTION: SUBMIT ENTIRE EXAM TO ADMIN
if (isset($_POST['submit_to_admin'])) {
    // Update exam status to 0 (This makes it visible in the Admin's Vetting Queue)
    $update = $pdo->prepare("UPDATE exams SET status = 0 WHERE id = ?");
    $update->execute([$exam_id]);
    
    header("Location: manage_exams.php?msg=submitted");
    exit();
}

// 4. HANDLE ADD QUESTION FORM
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_question'])) {
    $question_text = trim($_POST['question_text']);
    $opt_a = trim($_POST['option_a']);
    $opt_b = trim($_POST['option_b']);
    $opt_c = trim($_POST['option_c']);
    $opt_d = trim($_POST['option_d']);
    $correct = $_POST['correct_option'];

    try {
        $sql = "INSERT INTO questions (exam_id, question_text, option_a, option_b, option_c, option_d, correct_option, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')";
        $pdo->prepare($sql)->execute([$exam_id, $question_text, $opt_a, $opt_b, $opt_c, $opt_d, $correct]);
        $message = "Question added successfully!";
    } catch (PDOException $e) {
        $message = "Error: " . $e->getMessage();
    }
}

// 5. FETCH EXISTING QUESTIONS FOR LIVE PREVIEW
$q_stmt = $pdo->prepare("SELECT * FROM questions WHERE exam_id = ? ORDER BY id DESC");
$q_stmt->execute([$exam_id]);
$questions = $q_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Questions | <?= htmlspecialchars($exam['exam_title']) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #0f172a; --accent: #2563eb; --bg: #f8fafc; --success: #10b981; --text-muted: #64748b; }
        * { box-sizing: border-box; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background: var(--bg); color: var(--primary); margin: 0; padding: 0; overflow: hidden; }
        
        .layout { display: grid; grid-template-columns: 450px 1fr; height: 100vh; }
        
        /* LEFT SIDE: INPUT FORM */
        .sidebar { background: white; border-right: 1px solid #e2e8f0; padding: 30px; overflow-y: auto; box-shadow: 10px 0 15px -3px rgba(0,0,0,0.02); }
        .btn-back { text-decoration: none; color: var(--text-muted); font-size: 13px; font-weight: 700; display: flex; align-items: center; gap: 8px; margin-bottom: 20px; }
        
        h2 { font-size: 22px; font-weight: 800; margin-bottom: 5px; }
        .exam-meta { font-size: 13px; color: var(--text-muted); margin-bottom: 30px; }

        .form-group { margin-bottom: 18px; }
        label { display: block; font-weight: 700; font-size: 13px; margin-bottom: 8px; color: #334155; }
        textarea, input, select { width: 100%; padding: 12px; border: 1px solid #e2e8f0; border-radius: 10px; font-family: inherit; font-size: 14px; outline: none; }
        textarea:focus, input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1); }

        .options-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
        
        .btn-add { 
            width: 100%; background: var(--accent); color: white; padding: 15px; border: none; 
            border-radius: 12px; font-weight: 800; cursor: pointer; margin-top: 10px;
            box-shadow: 0 4px 6px -1px rgba(37, 99, 235, 0.2); transition: 0.2s;
        }
        .btn-add:hover { background: #1d4ed8; transform: translateY(-2px); }

        /* RIGHT SIDE: MAIN PREVIEW AREA */
        .preview-area { padding: 40px; overflow-y: auto; background: #f1f5f9; }
        .top-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; position: sticky; top: 0; z-index: 10; background: #f1f5f9; padding-bottom: 15px; }

        .btn-submit-all { 
            background: var(--success); color: white; padding: 12px 24px; border-radius: 12px; 
            text-decoration: none; font-weight: 800; border: none; cursor: pointer;
            box-shadow: 0 10px 15px -3px rgba(16, 185, 129, 0.3); display: flex; align-items: center; gap: 8px;
        }
        .btn-submit-all:hover { background: #059669; transform: translateY(-2px); }

        .q-card { background: white; border-radius: 16px; padding: 25px; margin-bottom: 20px; border: 1px solid #e2e8f0; position: relative; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02); }
        .q-num { position: absolute; top: 20px; right: 20px; font-weight: 800; color: #cbd5e1; font-size: 12px; }
        .q-text { font-weight: 700; font-size: 16px; margin-bottom: 15px; padding-right: 40px; }
        
        .preview-options { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
        .opt-box { background: #f8fafc; padding: 10px 15px; border-radius: 8px; font-size: 13px; border: 1px solid #f1f5f9; }
        .opt-box.correct { background: #dcfce7; border-color: #bbf7d0; color: #166534; font-weight: 700; }

        .empty-state { text-align: center; padding-top: 100px; color: #94a3b8; }
        .msg { background: #dcfce7; color: #166534; padding: 12px; border-radius: 10px; font-size: 13px; font-weight: 600; margin-bottom: 20px; border: 1px solid #bbf7d0; }

        @media (max-width: 950px) { .layout { grid-template-columns: 1fr; } .sidebar { height: auto; } body { overflow: auto; } }
    </style>
</head>
<body>

<div class="layout">
    <div class="sidebar">
        <a href="manage_exams.php" class="btn-back"><i class="fa fa-chevron-left"></i> Save as Draft & Exit</a>
        
        <h2>Add Question</h2>
        <div class="exam-meta">
            <i class="fa fa-file-lines"></i> <?= htmlspecialchars($exam['exam_title']) ?>
        </div>

        <?php if($message): ?>
            <div class="msg"><i class="fa fa-check-circle"></i> <?= $message ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group">
                <label>Question Text</label>
                <textarea name="question_text" rows="4" placeholder="Enter your question here..." required></textarea>
            </div>

            <div class="options-grid">
                <div class="form-group">
                    <label>Option A</label>
                    <input type="text" name="option_a" required>
                </div>
                <div class="form-group">
                    <label>Option B</label>
                    <input type="text" name="option_b" required>
                </div>
                <div class="form-group">
                    <label>Option C</label>
                    <input type="text" name="option_c" required>
                </div>
                <div class="form-group">
                    <label>Option D</label>
                    <input type="text" name="option_d" required>
                </div>
            </div>

            <div class="form-group">
                <label>Correct Answer</label>
                <select name="correct_option" 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>

            <button type="submit" name="add_question" class="btn-add">
                Save & Add Next <i class="fa fa-plus-circle" style="margin-left: 5px;"></i>
            </button>
        </form>
    </div>

    <div class="preview-area">
        <div class="top-bar">
            <div>
                <h3 style="margin:0;">Live Preview</h3>
                <span style="font-size: 12px; color: var(--text-muted); font-weight: 600;">
                    <?= count($questions) ?> Questions in Draft
                </span>
            </div>
            
            <?php if(count($questions) > 0): ?>
            <form method="POST">
                <button type="submit" name="submit_to_admin" class="btn-submit-all" onclick="return confirm('Ready to send this entire exam to the Admin for vetting?')">
                    <i class="fa fa-paper-plane"></i> Submit for Vetting
                </button>
            </form>
            <?php endif; ?>
        </div>

        <?php if(empty($questions)): ?>
            <div class="empty-state">
                <i class="fa fa-edit" style="font-size: 40px; margin-bottom: 15px; opacity: 0.3;"></i>
                <p>Questions you add will appear here in real-time.</p>
            </div>
        <?php else: ?>
            <?php foreach($questions as $index => $q): ?>
                <div class="q-card">
                    <span class="q-num">Q.<?= count($questions) - $index ?></span>
                    <div class="q-text"><?= htmlspecialchars($q['question_text']) ?></div>
                    
                    <div class="preview-options">
                        <div class="opt-box <?= $q['correct_option'] == 'A' ? 'correct' : '' ?>">A: <?= htmlspecialchars($q['option_a']) ?></div>
                        <div class="opt-box <?= $q['correct_option'] == 'B' ? 'correct' : '' ?>">B: <?= htmlspecialchars($q['option_b']) ?></div>
                        <div class="opt-box <?= $q['correct_option'] == 'C' ? 'correct' : '' ?>">C: <?= htmlspecialchars($q['option_c']) ?></div>
                        <div class="opt-box <?= $q['correct_option'] == 'D' ? 'correct' : '' ?>">D: <?= htmlspecialchars($q['option_d']) ?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

</body>
</html>