<?php
session_start();
require_once "../includes/db.php";
if (!isset($_SESSION['admin'])) { header("Location: index.php"); exit; }

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

$message = "";

// helpers
function safe_name($s){ return preg_replace('/[^A-Za-z0-9._-]/','_', $s); }

function open_zip_if_any(array $file): ?ZipArchive {
    if (empty($file['name'])) return null;
    if ($file['error'] !== UPLOAD_ERR_OK) return null;
    if (!class_exists('ZipArchive')) return null;
    $zip = new ZipArchive();
    if ($zip->open($file['tmp_name']) === TRUE) return $zip;
    return null;
}

function store_file_from_zip(ZipArchive $zip, string $zipPath, string $targetDir): ?string {
    $zipPath = ltrim($zipPath, "/\\");
    $stream = $zip->getStream($zipPath);
    if (!$stream) return null;

    if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);
    $base = pathinfo($zipPath, PATHINFO_BASENAME);
    $name = time().'_'.mt_rand(1000,9999).'_'.safe_name($base);
    $outPath = rtrim($targetDir, '/\\').'/'.$name;

    $fp = fopen($outPath, 'wb');
    while (!feof($stream)) { fwrite($fp, fread($stream, 8192)); }
    fclose($fp);
    fclose($stream);

    return $name; // filename saved in /uploads
}

function normalize_correct($raw): string {
    $raw = strtoupper(trim((string)$raw));
    $parts = array_map('trim', explode(',', $raw));
    $parts = array_values(array_filter($parts, fn($x)=>$x!==''));
    return implode(',', $parts);
}

// Load exams for dropdowns
$exams = $conn->query("SELECT id, title, course_name, unit_exam FROM exams ORDER BY course_name, unit_exam, id DESC");

/* =========================
   CSV FORM SUBMIT HANDLER
   ========================= */
if (isset($_POST['do_csv'])) {
    $exam_id = (int)($_POST['exam_id_csv'] ?? 0);
    if ($exam_id <= 0) {
        $message = "<div class='alert alert-warning'>Please select an exam for CSV import.</div>";
    } elseif (!isset($_FILES['csv']) || $_FILES['csv']['error'] !== UPLOAD_ERR_OK) {
        $message = "<div class='alert alert-warning'>Please choose a valid CSV file.</div>";
    } else {
        $targetDir = "../uploads/";
        $zip = open_zip_if_any($_FILES['media_zip']);

        $fh = fopen($_FILES['csv']['tmp_name'], 'r');
        if (!$fh) {
            $message = "<div class='alert alert-danger'>Unable to read CSV file.</div>";
        } else {
            $header = fgetcsv($fh);
            if (!$header) {
                $message = "<div class='alert alert-danger'>CSV has no header row.</div>";
            } else {
                $header = array_map('trim', $header);
                $has_local_exam = in_array('exam_id', $header, true);

                // Prepare insert
                $sql = "INSERT INTO questions
                        (exam_id, question_text, question_file,
                         option_1, option_1_file, option_2, option_2_file,
                         option_3, option_3_file, option_4, option_4_file,
                         correct_option)
                        VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
                $ins = $conn->prepare($sql);
                if (!$ins) {
                    $message = "<div class='alert alert-danger'>Prepare failed: ".$conn->error."</div>";
                } else {
                    $ok=0; $fail=0; $rownum=1;
                    while(($row = fgetcsv($fh)) !== false){
                        $rownum++;
                        // Map by header
                        $data = [];
                        foreach ($header as $i=>$h) { $data[$h] = $row[$i] ?? ''; }

                        // Decide exam_id per row
                        $q_exam_id = $has_local_exam ? (int)($data['exam_id'] ?? 0) : $exam_id;
                        if ($q_exam_id <= 0) $q_exam_id = $exam_id;

                        $q_text    = $data['question_text'] ?? '';
                        $q_file_in = trim($data['question_file'] ?? '');

                        $A_text = $data['option_A'] ?? '';
                        $A_file = trim($data['option_A_file'] ?? '');

                        $B_text = $data['option_B'] ?? '';
                        $B_file = trim($data['option_B_file'] ?? '');

                        $C_text = $data['option_C'] ?? '';
                        $C_file = trim($data['option_C_file'] ?? '');

                        $D_text = $data['option_D'] ?? '';
                        $D_file = trim($data['option_D_file'] ?? '');

                        $correct = normalize_correct($data['correct_option'] ?? '');

                        // Save files from zip (if provided)
                        $q_file = null;
                        $A_store = $B_store = $C_store = $D_store = null;

                        if ($zip && $q_file_in !== '') $q_file = store_file_from_zip($zip, $q_file_in, $targetDir);
                        if ($zip && $A_file    !== '') $A_store = store_file_from_zip($zip, $A_file, $targetDir);
                        if ($zip && $B_file    !== '') $B_store = store_file_from_zip($zip, $B_file, $targetDir);
                        if ($zip && $C_file    !== '') $C_store = store_file_from_zip($zip, $C_file, $targetDir);
                        if ($zip && $D_file    !== '') $D_store = store_file_from_zip($zip, $D_file, $targetDir);

                        $ins->bind_param("issssssssssi",
                            $q_exam_id, $q_text, $q_file,
                            $A_text, $A_store,
                            $B_text, $B_store,
                            $C_text, $C_store,
                            $D_text, $D_store,
                            $correct
                        );
                        if ($ins->execute()) $ok++; else $fail++;
                    }
                    if ($zip) $zip->close();
                    fclose($fh);

                    $message = "<div class='alert alert-".($fail? "warning":"success")."'>CSV import: $ok inserted".($fail? ", $fail failed.":" successfully.")."</div>";
                }
            }
        }
    }
}

/* =========================
   PASTE FORM SUBMIT HANDLER
   ========================= */
if (isset($_POST['do_paste'])) {
    $exam_id = (int)($_POST['exam_id_paste'] ?? 0);
    $raw     = trim($_POST['paste_text'] ?? '');
    if ($exam_id <= 0) {
        $message = "<div class='alert alert-warning'>Please select an exam for Paste mode.</div>";
    } elseif ($raw === '') {
        $message = "<div class='alert alert-warning'>Paste area is empty.</div>";
    } else {
        $blocks = preg_split('/\R{2,}/', $raw); // split by blank lines
        $sql = "INSERT INTO questions
                (exam_id, question_text, question_file,
                 option_1, option_1_file, option_2, option_2_file,
                 option_3, option_3_file, option_4, option_4_file,
                 correct_option)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
        $ins = $conn->prepare($sql);
        if (!$ins) {
            $message = "<div class='alert alert-danger'>Prepare failed: ".$conn->error."</div>";
        } else {
            $ok=0; $fail=0;
            foreach ($blocks as $b) {
                $lines = preg_split('/\R/', trim($b));
                $q=''; $A=''; $B=''; $C=''; $D=''; $correct='';
                foreach ($lines as $ln) {
                    if (stripos($ln,'Question:')===0) $q = trim(substr($ln,9));
                    elseif (preg_match('/^A\s*:\s*(.*)$/i',$ln,$m)) $A = trim($m[1]);
                    elseif (preg_match('/^B\s*:\s*(.*)$/i',$ln,$m)) $B = trim($m[1]);
                    elseif (preg_match('/^C\s*:\s*(.*)$/i',$ln,$m)) $C = trim($m[1]);
                    elseif (preg_match('/^D\s*:\s*(.*)$/i',$ln,$m)) $D = trim($m[1]);
                    elseif (stripos($ln,'Correct:')===0) $correct = trim(substr($ln,8));
                }
                $correct = normalize_correct($correct);
                $null = null;
                $ins->bind_param("issssssssssi",
                    $exam_id, $q, $null,
                    $A, $null,
                    $B, $null,
                    $C, $null,
                    $D, $null,
                    $correct
                );
                if ($ins->execute()) $ok++; else $fail++;
            }
            $message = "<div class='alert alert-".($fail? "warning":"success")."'>Paste import: $ok inserted".($fail? ", $fail failed.":" successfully.")."</div>";
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Import Questions</title>
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-4" style="max-width:980px">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="m-0">Import Questions</h3>
    <div class="d-flex gap-2">
      <a href="dashboard.php" class="btn btn-outline-secondary btn-sm">Dashboard</a>
      <a href="add_question_select.php" class="btn btn-outline-info btn-sm">Add Single Question</a>
    </div>
  </div>

  <?= $message ?>

  <div class="row g-4">
    <!-- CSV FORM -->
    <div class="col-lg-6">
      <div class="card">
        <div class="card-header">CSV Import</div>
        <div class="card-body">
          <form method="post" enctype="multipart/form-data">
            <div class="mb-3">
              <label class="form-label">Exam</label>
              <select name="exam_id_csv" class="form-select" required>
                <option value="">-- Select Exam --</option>
                <?php if ($exams) while($e=$exams->fetch_assoc()): ?>
                  <option value="<?= (int)$e['id'] ?>">
                    <?= htmlspecialchars($e['title']." — ".$e['course_name']." / ".$e['unit_exam']) ?>
                  </option>
                <?php endwhile; ?>
              </select>
            </div>

            <div class="mb-3">
              <label class="form-label">CSV File</label>
              <input type="file" name="csv" accept=".csv" class="form-control" required>
              <div class="form-text">
                Headers (case-sensitive): <code>exam_id,question_text,question_file,option_A,option_A_file,option_B,option_B_file,option_C,option_C_file,option_D,option_D_file,correct_option</code><br>
                You can omit <code>exam_id</code> column; the selected exam will be used.
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label">Optional Media ZIP</label>
              <input type="file" name="media_zip" accept=".zip" class="form-control">
              <div class="form-text">Put image/audio files in a ZIP and reference filenames in the CSV (e.g. <code>q1.png</code>, <code>optA1.mp3</code>). We store them in <code>/uploads</code>.</div>
            </div>

            <button class="btn btn-primary" name="do_csv" value="1">Import CSV</button>
            <a class="btn btn-outline-secondary" href="#">Cancel</a>
          </form>
        </div>
      </div>
    </div>

    <!-- PASTE FORM -->
    <div class="col-lg-6">
      <div class="card">
        <div class="card-header">Paste Mode</div>
        <div class="card-body">
          <form method="post">
            <div class="mb-3">
              <label class="form-label">Exam</label>
              <select name="exam_id_paste" class="form-select" required>
                <option value="">-- Select Exam --</option>
                <?php
                // Reload exams because prior loop consumed result set
                $exams2 = $conn->query("SELECT id, title, course_name, unit_exam FROM exams ORDER BY course_name, unit_exam, id DESC");
                if ($exams2) while($e=$exams2->fetch_assoc()):
                ?>
                  <option value="<?= (int)$e['id'] ?>">
                    <?= htmlspecialchars($e['title']." — ".$e['course_name']." / ".$e['unit_exam']) ?>
                  </option>
                <?php endwhile; ?>
              </select>
            </div>

            <div class="mb-3">
              <label class="form-label">Paste Questions</label>
              <textarea name="paste_text" rows="12" class="form-control" placeholder="Example:
Question: What is 2+2?
A: 4
B: 3
C: 2
D: 5
Correct: A

Question: Select prime numbers.
A: 2
B: 3
C: 4
D: 5
Correct: B, D"></textarea>
              <div class="form-text">Multiple correct answers supported (e.g. <code>Correct: A,B</code>).</div>
            </div>

            <button class="btn btn-primary" name="do_paste" value="1">Import Pasted Text</button>
            <a class="btn btn-outline-secondary" href="#">Cancel</a>
          </form>
        </div>
      </div>
    </div>
  </div>

  <div class="alert alert-info mt-4">
    <strong>Tip:</strong> If uploads fail, increase <code>upload_max_filesize</code> and <code>post_max_size</code> in <code>php.ini</code> (e.g., 32M), then restart Apache.
  </div>
</div>
</body>
</html>
