<?php
/**
 * Controller Pengaturan
 */
class PengaturanController {

    public function sekolah() {
        $db = getDB();
        $data = query_fetch_assoc($db, "SELECT * FROM pengaturan LIMIT 1") ?? [];
        $errors = [];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!validateCSRF($_POST['csrf_token'] ?? '')) {
                $errors[] = 'Token tidak valid.';
            } else {
                $namaSekolah   = sanitize($_POST['nama_sekolah'] ?? '');
                $npsn          = sanitize($_POST['npsn'] ?? '');
                $alamat        = sanitize($_POST['alamat'] ?? '');
                $telepon       = sanitize($_POST['telepon'] ?? '');
                $email         = sanitize($_POST['email'] ?? '');
                $website       = sanitize($_POST['website'] ?? '');
                $kepalaSekolah = sanitize($_POST['kepala_sekolah'] ?? '');
                $nipKepala     = sanitize($_POST['nip_kepala'] ?? '');
                $tahunAjaran   = sanitize($_POST['tahun_ajaran'] ?? '2024/2025');
                $semester      = sanitize($_POST['semester'] ?? 'Ganjil');

                if (empty($namaSekolah)) {
                    $errors[] = 'Nama sekolah wajib diisi.';
                }

                if (empty($errors)) {
                    // Handle logo upload
                    $logo = $data['logo'] ?? null;
                    if (!empty($_FILES['logo']['name']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
                        $newLogo = uploadFile($_FILES['logo'], 'sekolah');
                        if ($newLogo) {
                            if (!empty($data['logo'])) @unlink(UPLOAD_PATH . $data['logo']);
                            $logo = $newLogo;
                        }
                    }

                    if (empty($data)) {
                        // Insert
                        $stmt = $db->prepare(
                            "INSERT INTO pengaturan (nama_sekolah, npsn, alamat, telepon, email,
                             website, kepala_sekolah, nip_kepala, tahun_ajaran, semester, logo)
                             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
                        );
                        $stmt->bind_param('sssssssssss',
                            $namaSekolah, $npsn, $alamat, $telepon, $email,
                            $website, $kepalaSekolah, $nipKepala, $tahunAjaran, $semester, $logo
                        );
                    } else {
                        // Update
                        $stmt = $db->prepare(
                            "UPDATE pengaturan SET nama_sekolah=?, npsn=?, alamat=?, telepon=?,
                             email=?, website=?, kepala_sekolah=?, nip_kepala=?,
                             tahun_ajaran=?, semester=?, logo=? WHERE id=?"
                        );
                        $stmt->bind_param('sssssssssssi',
                            $namaSekolah, $npsn, $alamat, $telepon, $email,
                            $website, $kepalaSekolah, $nipKepala, $tahunAjaran, $semester,
                            $logo, $data['id']
                        );
                    }

                    $stmt->execute();
                    setFlash('success', 'Pengaturan sekolah berhasil disimpan.');
                    redirect(BASE_URL . '/index.php?page=pengaturan_sekolah');
                }
            }
        }

        $pageTitle = 'Profil Sekolah';
        $csrfToken = generateCSRF();
        $flash = getFlash();
        include __DIR__ . '/../views/pengaturan/sekolah.php';
    }

    public function sandi() {
        $errors = [];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!validateCSRF($_POST['csrf_token'] ?? '')) {
                $errors[] = 'Token tidak valid.';
            } else {
                $sandiLama  = $_POST['sandi_lama'] ?? '';
                $sandiBaru  = $_POST['sandi_baru'] ?? '';
                $konfirmasi = $_POST['konfirmasi'] ?? '';

                if (empty($sandiLama) || empty($sandiBaru) || empty($konfirmasi)) {
                    $errors[] = 'Semua field wajib diisi.';
                } elseif (strlen($sandiBaru) < 6) {
                    $errors[] = 'Password baru minimal 6 karakter.';
                } elseif ($sandiBaru !== $konfirmasi) {
                    $errors[] = 'Konfirmasi password tidak cocok.';
                } else {
                    $db = getDB();
                    $userId = (int)$_SESSION['user_id'];
                    $stmt = $db->prepare("SELECT password FROM users WHERE id = ?");
                    $stmt->bind_param('i', $userId);
                    $stmt->execute();
                    $user = stmt_get_result($stmt)->fetch_assoc();

                    if (!$user || !password_verify($sandiLama, $user['password'])) {
                        $errors[] = 'Password lama tidak benar.';
                    } else {
                        $hash = password_hash($sandiBaru, PASSWORD_DEFAULT);
                        $stmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
                        $stmt->bind_param('si', $hash, $userId);
                        $stmt->execute();
                        setFlash('success', 'Password berhasil diubah.');
                        redirect(BASE_URL . '/index.php?page=pengaturan_sandi');
                    }
                }
            }
        }

        $pageTitle = 'Ubah Sandi';
        $csrfToken = generateCSRF();
        $flash = getFlash();
        include __DIR__ . '/../views/pengaturan/sandi.php';
    }

    public function backup() {
        if (isset($_GET['download'])) {
            $this->downloadBackup();
            return;
        }

        $pageTitle = 'Backup Data';
        $flash = getFlash();
        include __DIR__ . '/../views/pengaturan/backup.php';
    }

    private function downloadBackup() {
        $filename = 'backup_siakad_' . date('Ymd_His') . '.sql';

        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: no-cache');

        $db = getDB();
        $tables = ['users', 'pengaturan', 'kelas', 'guru', 'siswa',
                   'alamat_siswa', 'orang_tua', 'wali', 'mata_pelajaran', 'nilai'];

        echo "-- ============================================================\n";
        echo "-- SIAKAD Database Backup\n";
        echo "-- Date: " . date('Y-m-d H:i:s') . "\n";
        echo "-- ============================================================\n\n";
        echo "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\n";
        echo "SET FOREIGN_KEY_CHECKS = 0;\n\n";

        foreach ($tables as $table) {
            // Get CREATE TABLE
            $res = $db->query("SHOW CREATE TABLE `$table`");
            if (!$res) continue;
            $row = $res->fetch_row();
            echo "-- Table: $table\n";
            echo "DROP TABLE IF EXISTS `$table`;\n";
            echo $row[1] . ";\n\n";

            // Get data
            $res = $db->query("SELECT * FROM `$table`");
            if (!$res || $res->num_rows === 0) {
                echo "-- (no data)\n\n";
                continue;
            }

            $rows = [];
            while ($dataRow = $res->fetch_row()) {
                $vals = array_map(function($v) use ($db) {
                    return $v === null ? 'NULL' : "'" . $db->real_escape_string($v) . "'";
                }, $dataRow);
                $rows[] = '(' . implode(', ', $vals) . ')';
            }

            // Split into chunks of 100 rows
            $chunks = array_chunk($rows, 100);
            foreach ($chunks as $chunk) {
                echo "INSERT INTO `$table` VALUES\n";
                echo implode(",\n", $chunk) . ";\n";
            }
            echo "\n";
        }

        echo "SET FOREIGN_KEY_CHECKS = 1;\n";
        exit;
    }
}
