<?php
chdir('../');
session_start();
require_once('public/connection.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Load PhpSpreadsheet
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;

// ===== EXPORT FUNCTIONALITY =====
if (isset($_GET['export'])) {
    if ($_GET['export'] === 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="questions_template.csv"');
        header('Cache-Control: no-store, no-cache');

        $output = fopen('php://output', 'w');

        // Instruction row
        fputcsv($output, [
            'NOTE: For formulas/equations, type them in MS Word (with subscript/superscript) and copy-paste here.'
        ]);

        // CSV Header row
        fputcsv($output, [
            'exam_id', 'question_text', 'question_type',
            'option_a', 'option_b', 'option_c', 'option_d',
            'correct_answer', 'marks'
        ]);

        // Sample row
        fputcsv($output, [
            1,
            'Sample Question: H₂O is water. (Type formulas in Word, then paste here)',
            'mcq',
            'Option A', 'Option B', 'Option C', 'Option D',
            'a', 5
        ]);
        fclose($output);
        exit;
    }

    if ($_GET['export'] === 'xlsx') {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // Instruction note in first row
        $sheet->mergeCells('A1:I1');
        $sheet->setCellValue('A1', 'NOTE: For formulas/equations, type them in MS Word (with subscript/superscript) and copy-paste here.');

        // Headers in second row
        $headers = [
            'exam_id', 'question_text', 'question_type',
            'option_a', 'option_b', 'option_c', 'option_d',
            'correct_answer', 'marks'
        ];
        $col = 'A';
        foreach ($headers as $header) {
            $sheet->setCellValue($col . '2', $header);
            $col++;
        }

        // Sample row in third row
        $sampleRow = [
            1,
            'Sample Question: H₂O is water. (Type formulas in Word, then paste here)',
            'mcq',
            'Option A', 'Option B', 'Option C', 'Option D',
            'a',
            5
        ];
        $col = 'A';
        foreach ($sampleRow as $value) {
            $sheet->setCellValue($col . '3', $value);
            $col++;
        }

        // Auto-size columns
        foreach (range('A', $col) as $columnID) {
            $sheet->getColumnDimension($columnID)->setAutoSize(true);
        }

        if (ob_get_length()) ob_end_clean();

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="questions_template.xlsx"');
        header('Cache-Control: max-age=0');
        header('Pragma: public');

        $writer = new Xlsx($spreadsheet);
        $writer->save("php://output");
        exit;
    }
}


// ===== IMPORT FUNCTIONALITY =====
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $imported = 0;

    // --- CSV Upload ---
    if (isset($_POST['import_csv_mcq'])) {
        if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
            $csvFile = fopen($_FILES['csv_file']['tmp_name'], 'r');

            $rowIndex = 0;
            while (($row = fgetcsv($csvFile)) !== false) {
                $rowIndex++;

                // Skip instruction row (first line) and header row (second line)
                if ($rowIndex <= 2) continue;

                if (count($row) < 9) continue;

                [$exam_id, $question_text, $question_type, $option_a, $option_b, $option_c, $option_d, $correct_answer, $marks] = $row;

                $stmt = $conn->prepare("INSERT INTO questions (
                    exam_id, question_text, question_type, 
                    option_a, option_b, option_c, option_d, 
                    correct_answer, marks
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");

                $stmt->bind_param("isssssssd", 
                    $exam_id, $question_text, $question_type, 
                    $option_a, $option_b, $option_c, $option_d, 
                    $correct_answer, $marks
                );

                if ($stmt->execute()) $imported++;
            }
            fclose($csvFile);
        }
    }

    // --- Excel Upload ---
    if (isset($_POST['import_xlsx_mcq'])) {
        if (isset($_FILES['xlsx_file']) && $_FILES['xlsx_file']['error'] === UPLOAD_ERR_OK) {
            $fileTmpPath = $_FILES['xlsx_file']['tmp_name'];
            $spreadsheet = IOFactory::load($fileTmpPath);
            $sheet = $spreadsheet->getActiveSheet();
            $rows = $sheet->toArray();

            foreach ($rows as $index => $row) {
                // Skip instruction row (index 0) and header row (index 1)
                if ($index <= 1) continue;
                if (count($row) < 9) continue;

                [$exam_id, $question_text, $question_type, $option_a, $option_b, $option_c, $option_d, $correct_answer, $marks] = $row;

                $stmt = $conn->prepare("INSERT INTO questions (
                    exam_id, question_text, question_type, 
                    option_a, option_b, option_c, option_d, 
                    correct_answer, marks
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");

                $stmt->bind_param("isssssssd", 
                    $exam_id, $question_text, $question_type, 
                    $option_a, $option_b, $option_c, $option_d, 
                    $correct_answer, $marks
                );

                if ($stmt->execute()) $imported++;
            }
        }
    }

    $_SESSION['msg'] = "$imported question(s) imported successfully.";
    $_SESSION['type'] = "success";
    header("Location: manage_questions.php");
    exit;
}
?>
