<?php
require_once __DIR__ . '/../models/KelasModel.php';
require_once __DIR__ . '/../models/GuruModel.php';

/**
 * Controller Kelas
 */
class KelasController {
    private $model;
    private $guruModel;

    public function __construct() {
        $this->model = new KelasModel();
        $this->guruModel = new GuruModel();
    }

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

    public function tambah() {
        $guruList = $this->guruModel->getAllActive();
        $errors = [];
        $data = [];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!validateCSRF($_POST['csrf_token'] ?? '')) {
                $errors[] = 'Token tidak valid.';
            } else {
                $data = $this->collectFormData();
                $errors = $this->validateData($data);

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

        $pageTitle = 'Tambah Kelas';
        $csrfToken = generateCSRF();
        include __DIR__ . '/../views/kelas/form.php';
    }

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

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

        $guruList = $this->guruModel->getAllActive();
        $errors = [];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!validateCSRF($_POST['csrf_token'] ?? '')) {
                $errors[] = 'Token tidak valid.';
            } else {
                $data = $this->collectFormData();
                $errors = $this->validateData($data);

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

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

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

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

        // Check if kelas has students
        $db = getDB();
        $stmt = $db->prepare("SELECT COUNT(*) as c FROM siswa WHERE kelas_id = ?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $count = stmt_get_result($stmt)->fetch_assoc()['c'];

        if ($count > 0) {
            setFlash('danger', 'Kelas tidak dapat dihapus karena masih memiliki siswa.');
        } else {
            $this->model->delete($id);
            setFlash('success', 'Kelas berhasil dihapus.');
        }
        redirect(BASE_URL . '/index.php?page=kelas');
    }

    public function anggota() {
        $kelasId = (int)($_GET['kelas_id'] ?? 0);
        $kelasList = $this->model->getAllSimple();
        $siswa = [];
        $kelas = null;

        if ($kelasId) {
            $kelas = $this->model->getById($kelasId);
            $siswa = $this->model->getSiswaByKelas($kelasId);
        }

        $pageTitle = 'Anggota Kelas';
        include __DIR__ . '/../views/kelas/anggota.php';
    }

    private function collectFormData() {
        return [
            'nama_kelas'    => sanitize($_POST['nama_kelas'] ?? ''),
            'tingkat'       => sanitize($_POST['tingkat'] ?? ''),
            'jurusan'       => sanitize($_POST['jurusan'] ?? ''),
            'wali_kelas_id' => (int)($_POST['wali_kelas_id'] ?? 0) ?: null,
            'tahun_ajaran'  => sanitize($_POST['tahun_ajaran'] ?? '2024/2025'),
            'kapasitas'     => (int)($_POST['kapasitas'] ?? 30),
        ];
    }

    private function validateData($data) {
        $errors = [];
        if (empty($data['nama_kelas'])) $errors[] = 'Nama kelas wajib diisi.';
        if (empty($data['tingkat'])) $errors[] = 'Tingkat wajib diisi.';
        return $errors;
    }
}
