<?php
error_reporting(E_ALL); ini_set('display_errors', 1); session_start(); require_once 'db.php';

$message = ''; $msg_type = '';

// Handle CSV Parsing on Upload Trigger
if (isset($_POST['import_csv_btn'])) {
    // File validation checks
    if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        $message = "Error: Please upload a valid CSV file dataset configuration resource."; $msg_type = 'error';
    } else {
        $file_tmp = $_FILES['csv_file']['tmp_name'];
        $file_ext = strtolower(pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION));
        
        if ($file_ext !== 'csv') {
            $message = "Validation Error: Upload format denied. Resource must use a format extension (.csv)."; $msg_type = 'error';
        } else {
            if (($handle = fopen($file_tmp, "r")) !== FALSE) {
                // Read and skip header line row track entry index map properties
                $header = fgetcsv($handle, 1000, ",");
                
                try {
                    $pdo->beginTransaction(); // Enable database transaction wrapper for performance safety
                    
                    // FIXED: Dynamic course_id column insertion directly from row streams
                    $stmt = $pdo->prepare("INSERT INTO questions (course_id, question_text, option_a, option_b, option_c, option_d, correct_option) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $inserted_count = 0;

                    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
                        // Skip empty rows safely
                        if (empty($row) || count($row) < 8) continue;

                        // FIXED: Adjusted column arrays index references to accommodate [0 => id] and [1 => course_id]
                        $course_id      = intval($row[1]); // Pulls course allocation indicator directly from CSV index row
                        $question_text  = trim($row[2]);
                        $option_a       = trim($row[3]);
                        $option_b       = trim($row[4]);
                        $option_c       = trim($row[5]);
                        $option_d       = trim($row[6]);
                        $correct_option = strtoupper(trim($row[7])); // Enforce uppercase parameter formatting: A, B, C, D

                        // Prevent blank question rows from parsing errors
                        if (empty($question_text)) continue;

                        $stmt->execute([$course_id, $question_text, $option_a, $option_b, $option_c, $option_d, $correct_option]);
                        $inserted_count++;
                    }
                    
                    $pdo->commit(); // Confirm bulk entries transaction write operations
                    fclose($handle);
                    $message = "Success: {$inserted_count} questions successfully parsed and added to respective course banks."; $msg_type = 'success';
                } catch (\Exception $e) {
                    $pdo->rollBack(); // Wipe transactions tracking entries state if failures occur
                    fclose($handle);
                    $message = "Runtime Entry Error: " . $e->getMessage(); $msg_type = 'error';
                }
            } else { $message = "Error: Failed to safely parse file data streams."; $msg_type = 'error'; }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><title>CBT Examination Questions Manager</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f4f6f9; margin: 0; padding: 20px; }
        .manager-container { display: grid; grid-template-columns: 260px 1fr; gap: 20px; max-width: 1300px; margin: 0 auto; }
        .sidebar { background: #007bff; padding: 15px; border-radius: 6px; min-height: 80vh; }
        .sidebar-btn { width: 100%; text-align: left; padding: 12px; background: none; border: none; color: white; cursor: pointer; font-size: 14px; font-weight: bold; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-btn:hover { background: rgba(255,255,255,0.15); }
        .workspace-card { background: white; padding: 30px; border-radius: 6px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .btn-tab { padding: 10px 20px; font-size: 14px; font-weight: bold; border: 1px solid #ccc; border-radius: 4px; cursor: pointer; background: #f8f9fa; margin-right: 10px; }
        .btn-tab.active { background: #fff; border-bottom: 2px solid white; border-top: 3px solid #28a745; margin-bottom: -1px; position: relative; z-index: 2; }
        .form-group { margin-bottom: 20px; text-align: left; }
        label { font-size: 14px; font-weight: bold; display: block; margin-bottom: 8px; color: #333; }
        input[type="file"] { width: 100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
        .submit-btn { padding: 12px 24px; font-weight: bold; font-size: 14px; color: white; background: #9b51e0; border: none; border-radius: 4px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; }
        .banner { padding: 12px; border-radius: 4px; font-size: 14px; margin-bottom: 20px; text-align: left; font-weight: bold; }
        .banner.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .banner.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .download-template { font-size: 12px; color: #007bff; display: inline-block; margin-top: 8px; text-decoration: none; }
    </style>
</head>
<body>

<h2 style="text-align: left; margin: 0 0 20px 0; color:#333; font-size:24px; padding-left:10px;">CBT Examination Questions Manager</h2>

     <!-- MAIN INTERFACE WORKSPACE CONTAINER -->
    <div class="workspace-card">
        <div style="border-bottom: 1px solid #ccc; margin-bottom: 25px; padding-bottom: 10px;">
             
            <button class="btn-tab active">📊 Bulk Import via CSV File</button>
        </div>

        <?php if(!empty($message)): ?>
            <div class="banner <?php echo $msg_type; ?>"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>

        <h3 style="color:#28a745; margin-top:0; font-size:18px;">Method B: Import Bulk Questions Matrix From CSV Dataset Sheet</h3>
        
        <form method="POST" action="" enctype="multipart/form-data">
            <div class="form-group">
                <label for="csv_file">Choose Data Resource Target File (.csv):</label>
                <input type="file" name="csv_file" id="csv_file" accept=".csv" required>
                <a href="data:text/csv;charset=utf-8,id,course_id,question_text,option_a,option_b,option_c,option_d,correct_option%0A1,1,What%20is%20RAM%3F,Random%20Access%20Memory,Read%20Access%20Memory,Real%20Action%20Mode,Rate%20Active%20Map,A" download="cbt_template_with_course.csv" class="download-template">📥 Download Sample Multi-Course Template blueprint (.csv)</a>
            </div>

            <div style="text-align: left; margin-top:30px;">
                <button type="submit" name="import_csv_btn" class="submit-btn">📥 Process Bulk CSV Import Processing</button>
            </div>
        </form>
    </div>
</div>

</body>
</html>
