<?php

namespace App\Controllers;

use App\Models\SoalPMBModel;
use Core\Controller;

class SoalPMBController extends Controller
{
    protected $model;

    public function __construct()
    {
        $this->model = new SoalPMBModel();
        // Mulai session kalau belum jalan (pastikan session_start() dipanggil di awal aplikasi)
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }

public function uploadSoal()
{
    if (isset($_FILES['excelFile']) && $_FILES['excelFile']['error'] === UPLOAD_ERR_OK) {
        if (!class_exists('PHPExcel_IOFactory')) {
            $_SESSION['flash_message'] = "Error: PHPExcel library tidak ditemukan. Pastikan sudah diinstall dan di-autoload.";
            header('Location: /dashboard/admin-manage_pmb');
            exit;
        }

        $fileTmpPath = $_FILES['excelFile']['tmp_name'];

        try {
            $inputFileType = \PHPExcel_IOFactory::identify($fileTmpPath);
            $reader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $reader->load($fileTmpPath);
        } catch (\Exception $e) {
            $_SESSION['flash_message'] = "Error membaca file Excel: " . $e->getMessage();
            header('Location: /dashboard/admin-manage_pmb');
            exit;
        }

        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestDataRow();
        $highestColumn = $sheet->getHighestDataColumn();

        $totalBaru = 0;

        for ($row = 2; $row <= $highestRow; $row++) {
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);

            if (!isset($rowData[0]) || count($rowData[0]) < 9) {
                error_log("⚠️ Baris $row dilewati karena data tidak lengkap.");
                continue;
            }

            $pertanyaan = trim($rowData[0][1]);
            $pilihan_a = trim($rowData[0][2]);
            $pilihan_b = trim($rowData[0][3]);
            $pilihan_c = trim($rowData[0][4]);
            $pilihan_d = trim($rowData[0][5]);
            $pilihan_e = trim($rowData[0][6]);
            $jawaban = trim($rowData[0][7]);
            $status = trim($rowData[0][8]);

            $pertanyaanNorm = strtolower(preg_replace('/\s+/', ' ', $pertanyaan));

            if (!$this->model->soalExists($pertanyaanNorm)) {
                $success = $this->model->insertSoal(
                    $pertanyaan,
                    $pilihan_a,
                    $pilihan_b,
                    $pilihan_c,
                    $pilihan_d,
                    $pilihan_e,
                    $jawaban,
                    $status
                );
                if ($success) {
                    $totalBaru++;
                    error_log("✅ Soal dari baris $row berhasil dimasukkan.");
                } else {
                    error_log("❌ Gagal memasukkan soal dari baris $row.");
                }
            } else {
                error_log("ℹ️ Soal duplikat di baris $row, dilewati.");
            }
        }

        $_SESSION['flash_message'] = "Data berhasil diupload. Total soal baru: $totalBaru";
        header('Location: /dashboard/admin-manage_pmb');
        exit;
    } else {
        $_SESSION['flash_message'] = "Tidak ada file yang diupload atau terjadi kesalahan upload.";
        header('Location: /dashboard/admin-manage_pmb');
        exit;
    }
}

}
