<?php

namespace App\Controllers;

use Core\Database;
use PDO;

class UploadSoalExcelController
{
    private $db;

    public function __construct()
    {
        $this->db = Database::getConnection();

        // Hanya untuk user dosen
        if (empty($_SESSION['user']) || !in_array($_SESSION['user']['level'], ['Dosen', 'Dosen/Kaprodi'])) {
            http_response_code(403);
            exit('Akses ditolak.');
        }
    }

    public function index()
    {
        $niy = $_SESSION['user']['niy'] ?? null;
        if (!$niy) {
            header("Location: /login");
            exit();
        }

        // Kalau ada upload Excel
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['uploadsoalexcel'])) {
            $this->prosesUpload();
            return;
        }

        // Data untuk dropdown
        $akademik = $this->db->query("SELECT * FROM tb_akademik WHERE status='Aktif' LIMIT 1")->fetch(PDO::FETCH_OBJ);
        $tahun_akademik = $akademik ? $akademik->tahun_akademik : null;

        $stmt = $this->db->prepare("
            SELECT dm.kode_mk, mk.nama_mk, dm.kode_kelas
            FROM tb_dosen_mk AS dm
            JOIN tb_mk AS mk ON dm.kode_mk = mk.kode_mk
            WHERE dm.niy = :niy AND dm.tahun_akademik = :tahun_akademik
        ");
        $stmt->execute(['niy' => $niy, 'tahun_akademik' => $tahun_akademik]);
        $courses = $stmt->fetchAll(PDO::FETCH_OBJ);

        $jenis_soal = $this->db->query("SELECT * FROM tb_jenis_soal WHERE status='Aktif'")->fetchAll(PDO::FETCH_OBJ);

        require __DIR__ . '/../Views/dosen/upload_soal_excel.php';
    }

    public function prosesUpload()
    {
        ini_set('upload_tmp_dir', '/home/babunnaj/tmp');
        require_once __DIR__ . '/../libraries/PHPExcel/PHPExcel.php';
        require_once __DIR__ . '/../libraries/PHPExcel/IOFactory.php';
    
        try {
            if (!isset($_FILES['excelFile']) || $_FILES['excelFile']['error'] !== UPLOAD_ERR_OK) {
                $_SESSION['message'] = "File Excel belum dipilih atau rusak.";
                header("Location: /dashboard/dosen-upload-soal-excel");
                exit();
            }
    
            $file = $_FILES['excelFile']['tmp_name'];
            $excelType = \PHPExcel_IOFactory::identify($file);
            $reader = \PHPExcel_IOFactory::createReader($excelType);
            $excel = $reader->load($file);
            $sheet = $excel->getSheet(0);
            $highestRow = $sheet->getHighestDataRow();
    
            // Data tambahan
            $niy = $_SESSION['user']['niy'];
            list($kode_mk, $kode_kelas) = explode('|', $_POST['kode_mk']);
            $tipe_soal = $_POST['tipe_soal'];
    
            $akademik = $this->db->query("SELECT * FROM tb_akademik WHERE status='Aktif' LIMIT 1")->fetch(PDO::FETCH_OBJ);
            $tahun_akademik = $akademik ? $akademik->tahun_akademik : null;
    
            $insertCount = 0;
    
            // Loop mulai baris ke-2 (header di baris 1)
            for ($row = 2; $row <= $highestRow; $row++) {
                // Ambil kolom B (index ke-1)
                $rowData = $sheet->rangeToArray('A' . $row . ':B' . $row, NULL, TRUE, FALSE);
                $soal = trim($rowData[0][1] ?? ''); // kolom B
    
                if ($soal === '') continue;
    
                $stmt = $this->db->prepare("
                    INSERT INTO tb_soal (kode_mk, kode_kelas, niy, tahun_akademik, tipe_soal, soal, tanggal_upload)
                    VALUES (?, ?, ?, ?, ?, ?, NOW())
                ");
                $stmt->execute([$kode_mk, $kode_kelas, $niy, $tahun_akademik, $tipe_soal, $soal]);
                $insertCount++;
            }
    
            $_SESSION['message'] = "<div class='alert alert-success'>Berhasil upload {$insertCount} soal dari Excel.</div>";
            header("Location: /dashboard/dosen-upload-soal-excel");
            exit();
    
        } catch (\Exception $e) {
            $_SESSION['message'] = "<div class='alert alert-danger'>Terjadi kesalahan: " . $e->getMessage() . "</div>";
            header("Location: /dashboard/dosen-upload-soal-excel");
            exit();
        }
    }

}
