<?php
namespace App\Controllers;

use Core\Controller;
use Core\Database;

class UploadSoalController extends Controller
{
    private $db;

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

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

        // Generate CSRF token jika belum ada
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
    }

    public function index()
    {
		$niy = $_SESSION['user']['niy'];
        $message = "";
        if (!empty($_SESSION['message'])) {
            $message = $_SESSION['message'];
            unset($_SESSION['message']);
        }

        $akademik = $this->db->query("SELECT * FROM tb_akademik WHERE status = 'Aktif' LIMIT 1")->fetch(\PDO::FETCH_OBJ);
        $tahun_akademik = $akademik ? $akademik->tahun_akademik : null;
        $niy = $_SESSION['user']['niy'];

        $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);

        return $this->view('dosen/upload_soal', [
            'courses' => $courses,
            'jenis_soal' => $jenis_soal,
            'message' => $message,
            'csrf_token' => $_SESSION['csrf_token']
        ]);
    }

    public function upload()
    {
		$niy = $_SESSION['user']['niy'];
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            exit("Method not allowed.");
        }

        // Validasi CSRF token
        if (empty($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
            http_response_code(403);
            exit("CSRF token tidak valid.");
        }

        $niy = $_SESSION['user']['niy'];
        $akademik = $this->db->query("SELECT * FROM tb_akademik WHERE status = 'Aktif' LIMIT 1")->fetch(\PDO::FETCH_OBJ);
        $tahun_akademik = $akademik ? $akademik->tahun_akademik : null;

        list($kode_mk, $kode_kelas) = explode('|', $_POST['kode_mk']);
        $tipe_soal = $_POST['tipe_soal'];
        $soal_array = $_POST['soal'] ?? [];

        if (count($soal_array) > 50) {
            $_SESSION['message'] = "Jumlah soal terlalu banyak (maks 50).";
            header("Location: /dashboard/dosen-upload-soal");
            exit;
        }

        $insertStmt = $this->db->prepare("
            INSERT INTO tb_soal (kode_mk, kode_kelas, niy, tahun_akademik, tipe_soal, soal, tanggal_upload)
            VALUES (:kode_mk, :kode_kelas, :niy, :tahun_akademik, :tipe_soal, :soal, :tanggal_upload)
        ");

        $jumlahSukses = 0;

        foreach ($soal_array as $soal) {
            $soal = trim(strip_tags($soal)); // Sanitasi input
            if (!empty($soal) && strlen($soal) <= 1000) {
                $insertStmt->execute([
                    'kode_mk' => $kode_mk,
                    'kode_kelas' => $kode_kelas,
                    'niy' => $niy,
                    'tahun_akademik' => $tahun_akademik,
                    'tipe_soal' => $tipe_soal,
                    'soal' => $soal,
                    'tanggal_upload' => date('Y-m-d H:i:s'),
                ]);
                $jumlahSukses++;
            }
        }

        $_SESSION['message'] = "<div class='alert alert-success'>Berhasil upload {$jumlahSukses} soal.</div>";
        header("Location: /dashboard/dosen-upload-soal");
        exit;
    }
}
