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

/**
 * Controller Guru
 */
class GuruController {
    private $model;
    private $perPage = 15;

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

    public function index() {
        $search  = sanitize($_GET['search'] ?? '');
        $status  = sanitize($_GET['status'] ?? '');
        $curPage = max(1, (int)($_GET['p'] ?? 1));
        $offset  = ($curPage - 1) * $this->perPage;

        $guru    = $this->model->getAll($search, $status, $this->perPage, $offset);
        $total   = $this->model->countAll($search, $status);

        $baseUrl = BASE_URL . '/index.php?page=guru&search=' . urlencode($search) . '&status=' . urlencode($status);
        $pagination = paginate($total, $this->perPage, $curPage, $baseUrl);

        $pageTitle = 'Data Guru';
        $flash = getFlash();
        include __DIR__ . '/../views/guru/index.php';
    }

    public function tambah() {
        $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)) {
                    $data['foto'] = null;
                    if (!empty($_FILES['foto']['name'])) {
                        $foto = uploadFile($_FILES['foto'], 'guru');
                        if ($foto) $data['foto'] = $foto;
                    }

                    $id = $this->model->insert($data);
                    if ($id) {
                        if ($data['foto']) $this->model->updateFoto($id, $data['foto']);
                        // Update guru_id di tabel mata_pelajaran
                        $this->updateMapelGuru($id, $data['mapel_id']);
                        setFlash('success', 'Data guru berhasil ditambahkan.');
                        redirect(BASE_URL . '/index.php?page=guru');
                    } else {
                        $errors[] = 'Gagal menyimpan data.';
                    }
                }
            }
        }

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

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

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

        $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)) {
                    if (!empty($_FILES['foto']['name'])) {
                        $foto = uploadFile($_FILES['foto'], 'guru');
                        if ($foto) {
                            if (!empty($guru['foto'])) @unlink(UPLOAD_PATH . $guru['foto']);
                            $this->model->updateFoto($id, $foto);
                        }
                    }
                    $this->model->update($id, $data);
                    // Update guru_id di tabel mata_pelajaran
                    $this->updateMapelGuru($id, $data['mapel_id']);
                    setFlash('success', 'Data guru berhasil diperbarui.');
                    redirect(BASE_URL . '/index.php?page=guru');
                }
            }
        }

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

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

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

        $guru = $this->model->getById($id);
        if ($guru) {
            if (!empty($guru['foto'])) @unlink(UPLOAD_PATH . $guru['foto']);
            $this->model->delete($id);
            setFlash('success', 'Data guru berhasil dihapus.');
        } else {
            setFlash('danger', 'Data tidak ditemukan.');
        }
        redirect(BASE_URL . '/index.php?page=guru');
    }

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

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

        // Kelas yang diajar
        $db = getDB();
        $stmt = $db->prepare("SELECT * FROM kelas WHERE wali_kelas_id = ?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $kelasWali = stmt_get_result($stmt)->fetch_all(MYSQLI_ASSOC);

        $pageTitle = 'Detail Guru - ' . e($guru['nama']);
        include __DIR__ . '/../views/guru/detail.php';
    }

    public function import() {
        $pageTitle = 'Import Guru';
        $csrfToken = generateCSRF();
        $flash     = getFlash();
        $errors    = [];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!validateCSRF($_POST['csrf_token'] ?? '')) {
                $errors[] = 'Token tidak valid.';
            } elseif (empty($_FILES['file']['name']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
                $errors[] = 'Pilih file CSV terlebih dahulu.';
            } else {
                $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
                if ($ext !== 'csv') {
                    $errors[] = 'Hanya file CSV yang didukung. Simpan Excel sebagai CSV UTF-8.';
                } else {
                    // Baca & hapus BOM UTF-8
                    $content = file_get_contents($_FILES['file']['tmp_name']);
                    $content = ltrim($content, "\xEF\xBB\xBF");
                    $tmp     = tmpfile();
                    fwrite($tmp, $content);
                    rewind($tmp);

                    // Baca baris pertama — cek apakah baris info (diawali #) atau header
                    $firstLine = fgetcsv($tmp);
                    // Jika baris pertama adalah info (diawali #), skip dan baca header berikutnya
                    if (!empty($firstLine[0]) && strpos(trim($firstLine[0]), '#') === 0) {
                        fgetcsv($tmp); // skip baris header kolom
                    }
                    // Jika baris pertama adalah header langsung (tidak ada #), sudah di-skip

                    // Build map kode mapel => id
                    $db = getDB();
                    $mapelRes = $db->query("SELECT id, kode FROM mata_pelajaran");
                    $mapelMap = []; // kode uppercase => id
                    while ($mp = $mapelRes->fetch_assoc()) {
                        $mapelMap[strtoupper(trim($mp['kode']))] = $mp['id'];
                    }

                    $imported = 0;
                    $skipped  = 0;

                    while (($row = fgetcsv($tmp)) !== false) {
                        // Kolom 1 = Nama (wajib)
                        if (empty(trim($row[1] ?? ''))) { $skipped++; continue; }

                        // Cari mapel_id dari kode (kolom 8)
                        $kodeMapel = strtoupper(trim($row[8] ?? ''));
                        $mapelId   = $mapelMap[$kodeMapel] ?? null;
                        $mapelNama = $kodeMapel; // simpan kode sebagai nama

                        $data = [
                            'nip'               => trim($row[0] ?? ''),
                            'nama'              => trim($row[1] ?? ''),
                            'jenis_kelamin'     => trim($row[2] ?? 'Laki-laki'),
                            'tempat_lahir'      => trim($row[3] ?? ''),
                            'tanggal_lahir'     => !empty($row[4]) ? trim($row[4]) : null,
                            'agama'             => trim($row[5] ?? 'Islam'),
                            'pendidikan'        => trim($row[6] ?? ''),
                            'jurusan_pendidikan'=> trim($row[7] ?? ''),
                            'mata_pelajaran'    => $mapelNama,
                            'mapel_id'          => $mapelId,
                            'status_kepegawaian'=> trim($row[9] ?? 'GTT'),
                            'no_hp'             => trim($row[10] ?? ''),
                            'email'             => trim($row[11] ?? ''),
                            'alamat'            => trim($row[12] ?? ''),
                            'tahun_masuk'       => !empty($row[13]) ? (int)$row[13] : null,
                            'status'            => trim($row[14] ?? 'Aktif') ?: 'Aktif',
                        ];

                        $guruId = $this->model->insert($data);

                        if ($guruId) {
                            // Assign guru ke mata pelajaran
                            if ($mapelId) {
                                $this->updateMapelGuru($guruId, $mapelId);
                            }
                            $imported++;
                        } else {
                            $skipped++;
                        }
                    }
                    fclose($tmp);

                    $msg = "$imported data guru berhasil diimport.";
                    if ($skipped > 0) $msg .= " $skipped baris dilewati.";
                    setFlash('success', $msg);
                    redirect(BASE_URL . '/index.php?page=guru');
                }
            }
        }

        include __DIR__ . '/../views/guru/import.php';
    }

    public function export() {
        // Export dengan format sama persis seperti template import
        $db   = getDB();
        $data = query_fetch_all($db,
            "SELECT g.*, mp.kode AS kode_mapel
             FROM guru g
             LEFT JOIN mata_pelajaran mp ON mp.guru_id = g.id
             ORDER BY g.nama"
        );

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="data_guru_' . date('Ymd_His') . '.csv"');
        header('Cache-Control: no-cache');

        $output = fopen('php://output', 'w');
        fputs($output, "\xEF\xBB\xBF"); // BOM UTF-8

        // Header — urutan sama dengan template import
        fputcsv($output, [
            'NIP', 'Nama', 'Jenis Kelamin', 'Tempat Lahir', 'Tanggal Lahir',
            'Agama', 'Pendidikan', 'Jurusan Pendidikan', 'Mata Pelajaran',
            'Status Kepegawaian', 'No HP', 'Email', 'Alamat', 'Tahun Masuk', 'Status'
        ]);

        foreach ($data as $row) {
            fputcsv($output, [
                $row['nip']               ?? '',
                $row['nama']              ?? '',
                $row['jenis_kelamin']     ?? '',
                $row['tempat_lahir']      ?? '',
                $row['tanggal_lahir']     ?? '',
                $row['agama']             ?? '',
                $row['pendidikan']        ?? '',
                $row['jurusan_pendidikan']?? '',
                $row['kode_mapel']        ?? $row['mata_pelajaran'] ?? '',
                $row['status_kepegawaian']?? '',
                $row['no_hp']             ?? '',
                $row['email']             ?? '',
                $row['alamat']            ?? '',
                $row['tahun_masuk']       ?? '',
                $row['status']            ?? '',
            ]);
        }
        fclose($output);
        exit;
    }

    // ----------------------------------------------------------------
    // Download Template CSV Guru
    // ----------------------------------------------------------------
    public function templateDownload() {
        // Ambil daftar kode mapel untuk info di template
        $db = getDB();
        $mapelRes  = $db->query("SELECT kode, nama FROM mata_pelajaran ORDER BY kode");
        $mapelList = [];
        if ($mapelRes) {
            while ($mp = $mapelRes->fetch_assoc()) $mapelList[] = $mp;
        }
        $kodeMapel = implode(', ', array_column($mapelList, 'kode'));

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="template_guru.csv"');
        header('Cache-Control: no-cache');

        $out = fopen('php://output', 'w');
        fputs($out, "\xEF\xBB\xBF"); // BOM UTF-8

        // Baris info kode mapel (sebagai komentar di baris pertama)
        fputcsv($out, ['# Kode Mapel tersedia: ' . ($kodeMapel ?: 'Belum ada — tambah dulu di menu Mata Pelajaran')]);

        // Header kolom
        fputcsv($out, [
            'NIP', 'Nama', 'Jenis Kelamin', 'Tempat Lahir', 'Tanggal Lahir',
            'Agama', 'Pendidikan', 'Jurusan Pendidikan', 'Mata Pelajaran',
            'Status Kepegawaian', 'No HP', 'Email', 'Alamat', 'Tahun Masuk', 'Status'
        ]);

        // Contoh data
        fputcsv($out, [
            '197001011995011001', 'Drs. Ahmad Fauzi', 'Laki-laki', 'Jakarta', '1970-01-01',
            'Islam', 'S1', 'Pendidikan Matematika', 'MTK',
            'PNS', '081234567890', 'guru@sekolah.sch.id', 'Jl. Mawar No. 1', '1995', 'Aktif'
        ]);
        fputcsv($out, [
            '197505152000122001', 'Siti Rahayu S.Pd', 'Perempuan', 'Bandung', '1975-05-15',
            'Islam', 'S1', 'Pendidikan Bahasa Indonesia', 'BIND',
            'PNS', '081234567891', 'siti@sekolah.sch.id', 'Jl. Melati No. 2', '2000', 'Aktif'
        ]);
        fputcsv($out, [
            '', 'Nama Guru Baru', 'Laki-laki', '', '',
            'Islam', 'S1', '', '',
            'GTT', '', '', '', '', 'Aktif'
        ]);

        fclose($out);
        exit;
    }

    private function collectFormData() {
        $mapelId = (int)($_POST['mapel_id'] ?? 0);

        // Ambil nama mapel dari tabel untuk disimpan di kolom mata_pelajaran (text)
        $mapelNama = '';
        if ($mapelId) {
            $db = getDB();
            $stmt = $db->prepare("SELECT nama FROM mata_pelajaran WHERE id=?");
            $stmt->bind_param('i', $mapelId);
            $stmt->execute();
            $row = stmt_get_result($stmt)->fetch_assoc();
            $mapelNama = $row['nama'] ?? '';
        }

        return [
            'nip'               => sanitize($_POST['nip'] ?? ''),
            'nama'              => sanitize($_POST['nama'] ?? ''),
            'jenis_kelamin'     => sanitize($_POST['jenis_kelamin'] ?? ''),
            'tempat_lahir'      => sanitize($_POST['tempat_lahir'] ?? ''),
            'tanggal_lahir'     => sanitize($_POST['tanggal_lahir'] ?? '') ?: null,
            'agama'             => sanitize($_POST['agama'] ?? ''),
            'pendidikan'        => sanitize($_POST['pendidikan'] ?? ''),
            'jurusan_pendidikan'=> sanitize($_POST['jurusan_pendidikan'] ?? ''),
            'mata_pelajaran'    => $mapelNama, // nama singkat dari tabel
            'mapel_id'          => $mapelId,   // id untuk update guru_id di mapel
            'status_kepegawaian'=> sanitize($_POST['status_kepegawaian'] ?? 'GTT'),
            'no_hp'             => sanitize($_POST['no_hp'] ?? ''),
            'email'             => sanitize($_POST['email'] ?? ''),
            'alamat'            => sanitize($_POST['alamat'] ?? ''),
            'tahun_masuk'       => sanitize($_POST['tahun_masuk'] ?? '') ?: null,
            'status'            => sanitize($_POST['status'] ?? 'Aktif'),
        ];
    }

    private function validateData($data) {
        $errors = [];
        if (empty($data['nama'])) $errors[] = 'Nama guru wajib diisi.';
        if (empty($data['jenis_kelamin'])) $errors[] = 'Jenis kelamin wajib dipilih.';
        return $errors;
    }

    // Update guru_id di tabel mata_pelajaran
    private function updateMapelGuru($guruId, $mapelId) {
        $db = getDB();
        // Lepas guru ini dari mapel lama
        $stmt = $db->prepare("UPDATE mata_pelajaran SET guru_id = NULL WHERE guru_id = ?");
        $stmt->bind_param('i', $guruId);
        $stmt->execute();

        // Assign ke mapel baru jika dipilih
        if ($mapelId) {
            $stmt = $db->prepare("UPDATE mata_pelajaran SET guru_id = ? WHERE id = ?");
            $stmt->bind_param('ii', $guruId, $mapelId);
            $stmt->execute();
        }
    }
}
