<?php 
require_once '../db_connect.php';
include 'includes/header.php'; 
include 'includes/sidebar.php'; 

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

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

$id = (int)$_GET['id'];
$msg = "";

// 2. Fetch Current Exam Data and Course List
try {
    $stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ?");
    $stmt->execute([$id]);
    $exam = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$exam) { die("<div class='p-5 text-center fw-bold text-danger'>Sorry, Exam not found!</div>"); }

    $course_stmt = $pdo->query("SELECT id, title FROM courses ORDER BY title ASC");
    $courses = $course_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}

// 3. Update Handling
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $banner = $exam['banner']; 
    
    if (!empty($_FILES['banner']['name'])) {
        $upload_dir = "uploads/exams/";
        if (!is_dir("../" . $upload_dir)) { mkdir("../" . $upload_dir, 0777, true); }
        
        $banner_path = $upload_dir . time() . "_" . $_FILES['banner']['name'];
        if (move_uploaded_file($_FILES['banner']['tmp_name'], "../" . $banner_path)) {
            $banner = $banner_path;
        }
    }

    $sql = "UPDATE exams SET 
            course_id = ?, exam_title = ?, banner = ?, duration_minutes = ?, total_questions = ?, 
            pass_percentage = ?, total_marks = ?, per_question_mark = ?, negative_marking_enabled = ?, 
            negative_marks = ?, retake_count = ?, pricing_model = ?, price = ?, 
            start_date = ?, end_date = ?, result_date = ?, instructions = ?, status = ? 
            WHERE id = ?";
    
    $stmt = $pdo->prepare($sql);
    $result = $stmt->execute([
        $_POST['course_id'], $_POST['exam_title'], $banner, $_POST['duration'], $_POST['total_questions'],
        $_POST['pass_percentage'], $_POST['total_marks'], $_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'], $_POST['status'], $id
    ]);

    if ($result) {
        $msg = "<div class='alert alert-success border-0 border-start border-4 border-success shadow-sm rounded-3 bg-white text-success fw-bold fade-up'><i class='fas fa-check-circle me-2'></i>Exam details updated successfully!</div>";
        // Refresh local data
        $stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ?");
        $stmt->execute([$id]);
        $exam = $stmt->fetch(PDO::FETCH_ASSOC);
    }
}
?>

<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; }
    
    .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: 16px; 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; }
    
    .status-panel { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 15px; padding: 20px; }

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

    .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 .btn-back { width: 100%; justify-content: center; margin-top: 10px; } 
        
        #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-edit me-2" style="color: var(--theme-green);"></i> Edit 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 btn-back mt-3 mt-md-0">
            <i class="fas fa-arrow-left me-2"></i> Back to List
        </a>
    </div>

    <div class="fade-up" style="animation-delay: 0.1s;">
        <?= $msg; ?>

        <form action="" method="POST" enctype="multipart/form-data">
            <div class="row g-4">
                <div class="col-lg-8">
                    <div class="form-card mb-4">
                        <div class="section-title">1. Basic 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" value="<?= htmlspecialchars($exam['exam_title']); ?>" required>
                        </div>
                        
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Assign to Course <span class="text-danger">*</span></label>
                                <select name="course_id" class="form-select fw-bold" style="color: var(--theme-green);" required>
                                    <?php foreach($courses as $course): ?>
                                        <option value="<?= $course['id']; ?>" <?= ($course['id'] == $exam['course_id']) ? 'selected' : ''; ?>>
                                            <?= htmlspecialchars($course['title']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Update Banner</label>
                                <input type="file" name="banner" class="form-control bg-white">
                                <?php if($exam['banner']): ?>
                                    <div class="mt-2 small text-success fw-bold"><i class="fas fa-image me-1"></i> Current: <?= basename($exam['banner']); ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <div class="form-card">
                        <div class="section-title">2. Configuration & Timing</div>
                        
                        <div class="row g-3 mb-4">
                            <div class="col-md-3">
                                <label class="form-label">Duration (Min)</label>
                                <input type="number" name="duration" class="form-control" value="<?= $exam['duration_minutes']; ?>" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Total Questions</label>
                                <input type="number" name="total_questions" class="form-control" value="<?= $exam['total_questions']; ?>" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Mark Per Question</label>
                                <input type="number" step="0.01" name="per_question_mark" class="form-control" value="<?= $exam['per_question_mark']; ?>">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Pass Percentage (%)</label>
                                <input type="number" name="pass_percentage" class="form-control" value="<?= $exam['pass_percentage']; ?>">
                            </div>
                        </div>

                        <div class="row g-3 mb-4">
                            <div class="col-md-4">
                                <label class="form-label">Start Date & Time</label>
                                <input type="datetime-local" name="start_date" class="form-control" value="<?= date('Y-m-d\TH:i', strtotime($exam['start_date'])); ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">End Date & Time</label>
                                <input type="datetime-local" name="end_date" class="form-control" value="<?= date('Y-m-d\TH:i', strtotime($exam['end_date'])); ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Result Publish Date</label>
                                <input type="datetime-local" name="result_date" class="form-control" value="<?= date('Y-m-d\TH:i', strtotime($exam['result_date'])); ?>">
                            </div>
                        </div>

                        <div class="mb-0">
                            <label class="form-label">Exam Instructions</label>
                            <textarea name="instructions" class="form-control" rows="4"><?= htmlspecialchars($exam['instructions']); ?></textarea>
                        </div>
                    </div>
                </div>

                <div class="col-lg-4">
                    <div class="status-panel mb-4 shadow-sm bg-white">
                        <div class="section-title">3. Status & Pricing</div>
                        
                        <div class="mb-4">
                            <label class="form-label">Visibility Status</label>
                            <select name="status" class="form-select fw-bold border-2">
                                <option value="active" <?= ($exam['status'] == 'active') ? 'selected' : ''; ?> class="text-success">Active (Live)</option>
                                <option value="inactive" <?= ($exam['status'] == 'inactive') ? 'selected' : ''; ?> class="text-danger">Inactive (Draft)</option>
                            </select>
                        </div>
                        
                        <div class="mb-4">
                            <label class="form-label">Access Model</label>
                            <select name="pricing_model" class="form-select">
                                <option value="free" <?= ($exam['pricing_model'] == 'free') ? 'selected' : ''; ?>>Free / Plan Only</option>
                                <option value="paid" <?= ($exam['pricing_model'] == 'paid') ? 'selected' : ''; ?>>Paid (Single Sale)</option>
                            </select>
                        </div>

                        <div class="mb-4">
                            <label class="form-label">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="<?= $exam['price']; ?>">
                            </div>
                        </div>

                        <div class="mb-0">
                            <label class="form-label">Retake Limit</label>
                            <input type="number" name="retake_count" class="form-control" value="<?= $exam['retake_count']; ?>">
                        </div>
                    </div>

                    <div class="status-panel shadow-sm bg-white">
                        <div class="section-title">4. Negative Marking</div>
                        <div class="form-check form-switch mb-3">
                            <input class="form-check-input" type="checkbox" name="neg_enable" id="neg" <?= ($exam['negative_marking_enabled']) ? 'checked' : ''; ?>>
                            <label class="form-check-label fw-bold" for="neg">Enable Negative Marking</label>
                        </div>
                        <div>
                            <label class="form-label">Negative Mark Value</label>
                            <input type="text" name="negative_marks" class="form-control" value="<?= $exam['negative_marks']; ?>" placeholder="e.g. 0.25">
                        </div>
                    </div>

                    <div class="mt-4">
                        <button type="submit" class="btn-save w-100">
                            <i class="fas fa-save me-2"></i> Update Exam Information
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</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'; ?>