<?php
require_once __DIR__ . '/../models/MapelModel.php';

class MapelController {
    private $model;

    public function __construct() {
        $this->model = new MapelModel();
    }

    public function index() {
        $search = sanitize($_GET['search'] ?? '');
        $mapel  = $this->model->getAll($search);
        $flash  = getFlash();
        $pageTitle = 'Mata Pelajaran';
        include __DIR__ . '/../views/mapel/index.php';
    }

    public function tambah() {
        $errors = [];
        $data   = [];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!validateCSRF($_POST['csrf_token'] ?? '')) {
                $errors[] = 'Token tidak valid.';
            } else {
                $data = [
                    'kode' => strtoupper(sanitize($_POST['kode'] ?? '')),
                    'nama' => sanitize($_POST['nama'] ?? ''),
                    'kkm'  => (int)($_POST['kkm'] ?? 70),
                ];
                if (empty($data['kode'])) $errors[] = 'Kode mapel wajib diisi.';
                if (empty($data['nama'])) $errors[] = 'Nama mapel wajib diisi.';
                if ($this->model->isKodeExists($data['kode'])) $errors[] = 'Kode mapel sudah digunakan.';

                if (empty($errors)) {
                    $this->model->insert($data);
                    setFlash('success', 'Mata pelajaran berhasil ditambahkan.');
                    redirect(BASE_URL . '/index.php?page=mapel');
                }
            }
        }

        $pageTitle = 'Tambah Mata Pelajaran';
        $csrfToken = generateCSRF();
        include __DIR__ . '/../views/mapel/form.php';
    }

    public function edit() {
        $id = (int)($_GET['id'] ?? 0);
        if (!$id) redirect(BASE_URL . '/index.php?page=mapel');

        $mapel = $this->model->getById($id);
        if (!$mapel) {
            setFlash('danger', 'Data tidak ditemukan.');
            redirect(BASE_URL . '/index.php?page=mapel');
        }

        $errors = [];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!validateCSRF($_POST['csrf_token'] ?? '')) {
                $errors[] = 'Token tidak valid.';
            } else {
                $data = [
                    'kode' => strtoupper(sanitize($_POST['kode'] ?? '')),
                    'nama' => sanitize($_POST['nama'] ?? ''),
                    'kkm'  => (int)($_POST['kkm'] ?? 70),
                ];
                if (empty($data['kode'])) $errors[] = 'Kode mapel wajib diisi.';
                if (empty($data['nama'])) $errors[] = 'Nama mapel wajib diisi.';
                if ($this->model->isKodeExists($data['kode'], $id)) $errors[] = 'Kode mapel sudah digunakan.';

                if (empty($errors)) {
                    $this->model->update($id, $data);
                    setFlash('success', 'Mata pelajaran berhasil diperbarui.');
                    redirect(BASE_URL . '/index.php?page=mapel');
                }
            }
        }

        $pageTitle = 'Edit Mata Pelajaran';
        $csrfToken = generateCSRF();
        $isEdit    = true;
        include __DIR__ . '/../views/mapel/form.php';
    }

    public function hapus() {
        $id = (int)($_GET['id'] ?? 0);
        if (!$id) redirect(BASE_URL . '/index.php?page=mapel');

        if (!validateCSRF($_GET['csrf'] ?? '')) {
            setFlash('danger', 'Token tidak valid.');
            redirect(BASE_URL . '/index.php?page=mapel');
        }

        // Cek apakah mapel digunakan di tabel nilai
        $db = getDB();
        $stmt = $db->prepare("SELECT COUNT(*) as c FROM nilai WHERE mapel_id=?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $count = stmt_get_result($stmt)->fetch_assoc()['c'];

        if ($count > 0) {
            setFlash('danger', 'Mata pelajaran tidak dapat dihapus karena sudah memiliki data nilai.');
        } else {
            $this->model->delete($id);
            setFlash('success', 'Mata pelajaran berhasil dihapus.');
        }
        redirect(BASE_URL . '/index.php?page=mapel');
    }
}
