<?php 
ini_set('display_errors', 1); error_reporting(E_ALL);
require_once '../db_connect.php';
include 'includes/header.php'; 
include 'includes/sidebar.php'; 

if (!isset($_GET['exam_id'])) {
    echo "<script>window.location.href='manage_exams.php';</script>";
    exit;
}

$exam_id = (int)$_GET['exam_id'];
$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>");

$msg = "";

if (isset($_POST["import"])) {
    $filename = $_FILES["csv_file"]["tmp_name"];

    if ($_FILES["csv_file"]["size"] > 0) {
        $file = fopen($filename, "r");
        
        // Skip header line
        fgetcsv($file); 

        $count = 0;
        $pdo->beginTransaction();

        try {
            // Clear existing questions for this exam to allow clean re-upload
            $pdo->prepare("DELETE FROM questions WHERE exam_id = ?")->execute([$exam_id]);

            while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {
                // Check column count (Question + 4 options + correct option)
                if (count($column) < 6) continue;

                $sql = "INSERT INTO questions (exam_id, question_text, option_a, option_b, option_c, option_d, correct_option) 
                        VALUES (?, ?, ?, ?, ?, ?, ?)";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    $exam_id, 
                    $column[0], // Question Text
                    $column[1], // Option A
                    $column[2], // Option B
                    $column[3], // Option C
                    $column[4], // Option D
                    strtolower(trim($column[5])) // Correct Option (a, b, c, or d)
                ]);
                $count++;
            }

            // Validation message based on required questions count
            if ($count != $exam_data['total_questions']) {
                $msg = "<div class='alert alert-warning border-0 border-start border-4 border-warning shadow-sm bg-white fw-bold fade-up'><i class='fas fa-exclamation-triangle me-2'></i>Warning: You imported {$count} questions, but this exam requires exactly {$exam_data['total_questions']} questions.</div>";
            } else {
                $msg = "<div class='alert alert-success border-0 border-start border-4 border-success shadow-sm bg-white text-success fw-bold fade-up'><i class='fas fa-check-circle me-2'></i>Success: {$count} questions have been imported successfully!</div>";
            }

            $pdo->commit();
        } catch (Exception $e) {
            $pdo->rollBack();
            $msg = "<div class='alert alert-danger border-0 border-start border-4 border-danger shadow-sm bg-white text-danger fw-bold fade-up'><i class='fas fa-times-circle me-2'></i>Error: " . $e->getMessage() . "</div>";
        }
        fclose($file);
    }
}
?>

<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); }
    .custom-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 18px; box-shadow: 0 10px 40px rgba(0,0,0,0.03); padding: 40px; border-top: 6px solid var(--theme-green); }
    
    .instruction-box { background: rgba(6, 78, 59, 0.05); border: 1px solid rgba(6, 78, 59, 0.1); border-radius: 15px; padding: 20px; margin-bottom: 30px; border-left: 5px solid var(--theme-gold); }
    .instruction-box h6 { color: var(--theme-green); font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; }

    .upload-area { border: 2px dashed #cbd5e1; background: var(--bg-soft); border-radius: 20px; padding: 40px 20px; transition: 0.3s; text-align: center; }
    .upload-area:hover { border-color: var(--theme-gold); background: #fff; }
    
    .form-control { border-radius: 10px; padding: 12px 15px; border: 1px solid #cbd5e1; background-color: #fff; transition: 0.3s; }
    .form-control:focus { border-color: var(--theme-green); box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); outline: none; }
    
    .btn-theme { background: var(--theme-green); color: #fff; border: none; transition: 0.3s; padding: 14px 40px; border-radius: 12px; font-weight: 800; font-size: 16px; box-shadow: 0 8px 20px rgba(6, 78, 59, 0.2); }
    .btn-theme: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;}
        .custom-card { padding: 25px !important; }
        .upload-area { padding: 30px 15px; }
        .btn-theme { width: 100%; }
    }
</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>
            <h4 class="mb-0 fw-bold" style="color: var(--theme-green);">
                <i class="fas fa-file-import me-2" style="color: var(--theme-gold);"></i> Bulk Import Questions
            </h4>
        </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> Go Back
        </a>
    </div>

    <div class="row justify-content-center fade-up" style="animation-delay: 0.1s;">
        <div class="col-xl-8 col-lg-10">
            <div class="custom-card">
                
                <?= $msg; ?>

                <div class="instruction-box">
                    <h6><i class="fas fa-info-circle me-2"></i>Instructions:</h6>
                    <ul class="small mb-0 mt-2 text-muted fw-bold">
                        <li class="mb-1">Your file must be in <strong>CSV (Comma Delimited)</strong> format.</li>
                        <li class="mb-1">File must have 6 columns: <strong>Question, Opt A, Opt B, Opt C, Opt D, Correct Option (a/b/c/d)</strong>.</li>
                        <li>Required questions for this exam: <strong><?= $exam_data['total_questions']; ?></strong>.</li>
                    </ul>
                </div>

                <form action="" method="post" enctype="multipart/form-data">
                    <div class="upload-area mb-4">
                        <i class="fas fa-file-csv fa-4x mb-3" style="color: var(--theme-gold); opacity: 0.7;"></i>
                        <h5 class="fw-bold text-dark mb-3">Select CSV File to Upload</h5>
                        <div class="d-flex justify-content-center">
                            <input type="file" name="csv_file" class="form-control w-75 w-md-50" accept=".csv" required>
                        </div>
                    </div>
                    
                    <div class="text-center">
                        <button type="submit" name="import" class="btn btn-theme">
                            <i class="fas fa-upload me-2"></i> Start Importing Questions
                        </button>
                    </div>
                </form>

                <div class="mt-5 text-center border-top pt-4">
                    <p class="text-muted small fw-bold">Need a template? Download our standardized format below:</p>
                    <a href="sample_questions.csv" class="text-decoration-none fw-bold" style="color: var(--theme-gold);">
                        <i class="fas fa-download me-1"></i> Download CSV Sample Format
                    </a>
                </div>
            </div>
        </div>
    </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'; ?>