<?php 
// 1. Database connection and logic first (Before any HTML output)
require_once '../db_connect.php';

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

// 2. Form Submission Handling
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $banner = "";
    if (!empty($_FILES['banner']['name'])) {
        $target_dir = "../uploads/exams/";
        if (!is_dir($target_dir)) { mkdir($target_dir, 0777, true); }
        
        $banner_name = time() . "_" . basename($_FILES['banner']['name']);
        $target_file = $target_dir . $banner_name;
        
        if (move_uploaded_file($_FILES['banner']['tmp_name'], $target_file)) {
            $banner = "uploads/exams/" . $banner_name;
        }
    }

    try {
        $sql = "INSERT INTO exams (course_id, exam_title, banner, duration_minutes, total_questions, pass_percentage, per_question_mark, negative_marking_enabled, negative_marks, retake_count, pricing_model, price, start_date, end_date, result_date, instructions, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'inactive')";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $_POST['course_id'], 
            $_POST['exam_title'], 
            $banner, 
            $_POST['duration'], 
            $_POST['total_questions'],
            $_POST['pass_percentage'], 
            $_POST['per_question_mark'], 
            isset($_POST['neg_enable']) ? 1 : 0, 
            $_POST['negative_marks'], 
            $_POST['retake_count'],
            $_POST['pricing_model'], 
            $_POST['price'], 
            $_POST['start_date'], 
            $_POST['end_date'], 
            $_POST['result_date'], 
            $_POST['instructions']
        ]);

        $exam_id = $pdo->lastInsertId();
        
        // Redirect to question adding page
        header("Location: add_questions.php?exam_id=$exam_id");
        exit;
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

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

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

// 5. Fetch Courses for selection
try {
    $course_stmt = $pdo->query("SELECT id, title FROM courses ORDER BY title ASC");
    $courses = $course_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $courses = [];
}
?>

<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); }
    .form-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; }
    
    .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; }
    
    .section-title { font-weight: 800; color: var(--theme-dark); border-left: 4px solid var(--theme-gold); padding-left: 12px; margin-bottom: 25px; font-size: 14px; text-transform: uppercase; letter-spacing: 1px; }
    .form-label { font-weight: 700; color: var(--theme-dark); margin-bottom: 8px; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; }
    .form-control, .form-select { border-radius: 10px; 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; }
    
    .btn-submit { background: var(--theme-green); color: #fff; padding: 16px 50px; border-radius: 50px; 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; } 
        
        /* Fixed Square Menu Button */
        #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;}
        .form-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-file-signature me-2" style="color: var(--theme-green);"></i> Create New Exam</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>

    <?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" enctype="multipart/form-data" class="fade-up" style="animation-delay: 0.1s;">
        <div class="row g-4">
            <div class="col-lg-8">
                <div class="form-card h-100">
                    <div class="section-title">1. General Information</div>
                    
                    <div class="mb-4">
                        <label class="form-label">Exam Title <span class="text-danger">*</span></label>
                        <input type="text" name="exam_title" class="form-control" placeholder="e.g., HSC Physics Chapter 1 Weekly Exam" required>
                    </div>

                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Select Course <span class="text-danger">*</span></label>
                            <select name="course_id" class="form-select fw-bold" style="color: var(--theme-green);" required>
                                <option value="">Choose Course...</option>
                                <?php foreach($courses as $course): ?>
                                    <option value="<?= $course['id']; ?>"><?= htmlspecialchars($course['title']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Exam Banner (Optional)</label>
                            <input type="file" name="banner" class="form-control bg-white">
                        </div>
                    </div>

                    <div class="mb-0">
                        <label class="form-label">Exam Instructions</label>
                        <textarea name="instructions" class="form-control" rows="6" placeholder="Enter rules and guidelines for students..."></textarea>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="form-card mb-4" style="border-top: 5px solid var(--theme-gold);">
                    <div class="section-title">2. Pricing & Access</div>
                    <div class="mb-4">
                        <label class="form-label">Access Model</label>
                        <select name="pricing_model" class="form-select fw-bold">
                            <option value="free">Free (Subscription Members)</option>
                            <option value="paid">Paid (One-time Purchase)</option>
                        </select>
                    </div>
                    <div class="mb-0">
                        <label class="form-label">Individual Price (BDT)</label>
                        <div class="input-group">
                            <span class="input-group-text border-0 bg-light fw-bold">৳</span>
                            <input type="number" name="price" class="form-control border-0 bg-light fw-bold" value="0">
                        </div>
                    </div>
                </div>

                <div class="form-card" style="border-top: 5px solid var(--theme-green);">
                    <div class="section-title">3. Marking Scheme</div>
                    <div class="row g-2 mb-4">
                        <div class="col-6">
                            <label class="form-label">Per Qus. Mark</label>
                            <input type="number" step="0.01" name="per_question_mark" class="form-control" value="1">
                        </div>
                        <div class="col-6">
                            <label class="form-label">Pass %</label>
                            <input type="number" name="pass_percentage" class="form-control" value="40">
                        </div>
                    </div>
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" name="neg_enable" id="negSwitch">
                        <label class="form-check-label fw-bold small text-muted" for="negSwitch">ENABLE NEGATIVE MARKING</label>
                    </div>
                    <div class="mb-0">
                        <label class="form-label">Negative Mark Value</label>
                        <input type="text" name="negative_marks" class="form-control" value="0.25" placeholder="e.g., 0.25">
                    </div>
                </div>
            </div>

            <div class="col-12">
                <div class="form-card">
                    <div class="section-title">4. Scheduling & Limits</div>
                    <div class="row g-4 mb-4">
                        <div class="col-md-3">
                            <label class="form-label">Exam Duration (Min) *</label>
                            <input type="number" name="duration" class="form-control" placeholder="30" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Total Questions *</label>
                            <input type="number" name="total_questions" class="form-control" placeholder="50" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Retake Limit</label>
                            <input type="number" name="retake_count" class="form-control" value="0">
                            <small class="text-muted" style="font-size: 10px;">(Enter 0 for unlimited attempts)</small>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Result Publish Date</label>
                            <input type="datetime-local" name="result_date" class="form-control">
                        </div>
                    </div>
                    <div class="row g-4">
                        <div class="col-md-6">
                            <label class="form-label">Start Time (Availability)</label>
                            <input type="datetime-local" name="start_date" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">End Time (Availability)</label>
                            <input type="datetime-local" name="end_date" class="form-control">
                        </div>
                    </div>

                    <div class="text-center mt-5 pt-4 border-top">
                        <button type="submit" class="btn-submit">
                            Save Exam & Proceed to Questions <i class="fas fa-arrow-right ms-2"></i>
                        </button>
                    </div>
                </div>
            </div>
        </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'; ?>