<?php
// FILE PATH: C:\xampp\htdocs\Project\Teacher\upload_questions_bulk.php
session_start();
require_once "../config/database.php";

// 1. SECURITY & ACCESS CONTROL
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['superadmin', 'admin', 'teacher'])) {
    header("Location: ../auth/login.php");
    exit();
}

// 2. FETCH ACTIVE EXAMS
$exams = $pdo->query("SELECT id, exam_title FROM exams WHERE is_deleted = 0 ORDER BY id DESC")->fetchAll();

$message = "";
$message_type = "";

// 3. PROCESSING THE FORM SUBMISSION (DATABASE SAVE)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_questions'])) {
    $exam_id = (int)$_POST['exam_id'];
    $raw_text = trim($_POST['bulk_data']);
    
    // Split by double newlines to isolate question blocks
    $blocks = preg_split('/\n\s*\n/', $raw_text);
    $import_count = 0;
    $error_count = 0;

    if (!empty($raw_text)) {
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("INSERT INTO questions (exam_id, question_text, option_a, option_b, option_c, option_d, correct_option) VALUES (?, ?, ?, ?, ?, ?, ?)");

            foreach ($blocks as $block) {
                // Clean lines and remove empty ones
                $lines = array_values(array_filter(array_map('trim', explode("\n", $block))));
                
                // Need Question + 4 Options + Answer = 6 lines
                if (count($lines) < 6) {
                    $error_count++;
                    continue; 
                }

                $question = $lines[0];
                // Strip "A. ", "A) ", etc. from options
                $optA = preg_replace('/^[A]\s*[\.\)]\s*/i', '', $lines[1]);
                $optB = preg_replace('/^[B]\s*[\.\)]\s*/i', '', $lines[2]);
                $optC = preg_replace('/^[C]\s*[\.\)]\s*/i', '', $lines[3]);
                $optD = preg_replace('/^[D]\s*[\.\)]\s*/i', '', $lines[4]);
                
                // Find the line starting with ANSWER:
                $correct = '';
                foreach($lines as $line) {
                    if (stripos($line, 'ANSWER:') === 0) {
                        $correct = strtoupper(trim(str_ireplace('ANSWER:', '', $line)));
                        $correct = trim($correct, '. '); 
                    }
                }

                if (!empty($question) && !empty($correct)) {
                    $stmt->execute([$exam_id, $question, $optA, $optB, $optC, $optD, $correct]);
                    $import_count++;
                } else {
                    $error_count++;
                }
            }
            $pdo->commit();
            $message = "Success! $import_count questions added to the exam.";
            if($error_count > 0) $message .= " ($error_count errors found).";
            $message_type = "success";
        } catch (Exception $e) {
            $pdo->rollBack();
            $message = "Error: " . $e->getMessage();
            $message_type = "error";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bulk Upload & AI Assistant</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #2563eb; --ai-pink: #db2777; --bg: #f8fafc; --dark: #1e293b; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); margin: 0; padding: 20px; }
        .container { max-width: 900px; margin: auto; }
        
        /* Header Styling */
        .header-area { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
        .btn-back { text-decoration: none; color: var(--dark); background: #fff; padding: 10px 18px; border-radius: 10px; font-size: 14px; font-weight: 600; border: 1px solid #e2e8f0; transition: 0.2s; }
        .btn-back:hover { background: #f1f5f9; border-color: #cbd5e1; }

        .card { background: white; padding: 30px; border-radius: 16px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); margin-bottom: 20px; }
        .ai-box { background: #fdf2f8; border: 1px solid #fbcfe8; padding: 20px; border-radius: 12px; margin-bottom: 25px; }
        
        label { display: block; font-weight: 600; margin-bottom: 8px; font-size: 14px; color: #475569; }
        input, select, textarea { width: 100%; padding: 12px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 15px; box-sizing: border-box; margin-bottom: 15px; }
        textarea { height: 300px; font-family: 'Courier New', monospace; background: #fff; }
        
        .btn { border: none; padding: 14px 20px; border-radius: 8px; cursor: pointer; font-weight: 700; transition: 0.2s; }
        .btn-primary { background: var(--primary); color: white; width: 100%; }
        .btn-ai { background: var(--ai-pink); color: white; }
        .btn:disabled { opacity: 0.6; cursor: not-allowed; }

        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: 600; }
        .alert-success { background: #dcfce7; color: #166534; }
        .alert-error { background: #fee2e2; color: #991b1b; }
        
        .flex-row { display: flex; gap: 10px; align-items: flex-start; }
    </style>
</head>
<body>

<div class="container">
    
    <div class="header-area">
        <h2 style="margin:0;"><i class="fa fa-layer-group"></i> Question Importer</h2>
        <a href="dashboard.php" class="btn-back">
            <i class="fa fa-arrow-left"></i> Back to Dashboard
        </a>
    </div>

    <?php if($message): ?>
        <div class="alert alert-<?= $message_type ?>"><?= $message ?></div>
    <?php endif; ?>

    <div class="ai-box">
        <h3 style="margin-top:0; color: var(--ai-pink);"><i class="fa fa-robot"></i> Smart AI Question Setter</h3>
        <p style="font-size: 13px; color: #64748b; margin-top: -10px;">Type a topic and let AI draft the questions for you.</p>
        
        <div class="flex-row">
            <div style="flex: 2;">
                <label>Topic</label>
                <input type="text" id="ai_topic" placeholder="e.g. Computer Networking Fundamentals">
            </div>
            <div style="flex: 0.5;">
                <label>Qty</label>
                <input type="number" id="ai_count" value="5" min="1" max="15">
            </div>
            <div style="padding-top: 28px;">
                <button type="button" class="btn btn-ai" id="ai_btn" onclick="generateWithAI()">
                    <i class="fa fa-magic"></i> Generate
                </button>
            </div>
        </div>
        <p id="ai_status" style="font-size: 12px; margin: 0; color: #db2777; font-weight: bold;"></p>
    </div>

    <div class="card">
        <form method="POST">
            <label>1. Select Target Exam</label>
            <select name="exam_id" required>
                <option value="">-- Choose Exam --</option>
                <?php foreach($exams as $exam): ?>
                    <option value="<?= $exam['id'] ?>"><?= htmlspecialchars($exam['exam_title']) ?></option>
                <?php endforeach; ?>
            </select>

            <label>2. Review Questions (Paste or AI Output)</label>
            <textarea name="bulk_data" id="bulk_data" placeholder="Questions will appear here..." required></textarea>

            <button type="submit" name="import_questions" class="btn btn-primary">
                <i class="fa fa-save"></i> Save All Questions to Database
            </button>
        </form>
    </div>
</div>

<script>
function generateWithAI() {
    const topic = document.getElementById('ai_topic').value;
    const count = document.getElementById('ai_count').value;
    const btn = document.getElementById('ai_btn');
    const status = document.getElementById('ai_status');
    const textArea = document.getElementById('bulk_data');

    if(!topic) return alert("Please enter a topic first!");

    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Processing...';
    status.innerText = "Gemini is thinking... please wait.";

    const formData = new FormData();
    formData.append('topic', topic);
    formData.append('count', count);

    fetch('generate_ai.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(data => {
        textArea.value = data; 
        btn.disabled = false;
        btn.innerHTML = '<i class="fa fa-magic"></i> Generate';
        status.innerText = "Questions ready! Review and click Save below.";
    })
    .catch(error => {
        console.error(error);
        status.innerText = "Error connecting to AI. Try again.";
        btn.disabled = false;
    });
}
</script>

</body>
</html>