<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\TeacherModel;
use App\Models\UserModel;

class Teacher extends BaseController
{
    protected $teacherModel;
    protected $userModel;

    public function __construct()
    {
        $this->teacherModel = new TeacherModel();
        $this->userModel    = new UserModel();
    }

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        return null;
    }

    private function checkAdmin()
    {
        $role = session()->get('user_role');
        if (!in_array($role, ['superadmin', 'admin'])) {
            return redirect()->to('/dashboard')->with('error', 'Akses ditolak!');
        }
        return null;
    }

    public function index()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        if ($redirect = $this->checkAdmin()) return $redirect;

        $data = [
            'title'            => 'Manajemen Guru',
            'teachers'         => $this->teacherModel->getAllWithUser(),
            'teachers_inactive' => $this->teacherModel->getInactiveWithUser(),
        ];

        return view('teacher/index', $data);
    }

    public function create()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        if ($redirect = $this->checkAdmin()) return $redirect;

        return view('teacher/create', ['title' => 'Tambah Guru']);
    }

    public function store()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        if ($redirect = $this->checkAdmin()) return $redirect;

        $rules = [
            'name'   => 'required|min_length[3]|max_length[100]',
            'gender' => 'required|in_list[L,P]',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        $nip   = $this->request->getPost('nip');
        $pegId = $this->request->getPost('peg_id');
        $status = $this->request->getPost('status_kepegawaian') ?: null;

        if (!empty($pegId) && !preg_match('/^[0-9]+$/', $pegId)) {
            return redirect()->back()
                ->with('error', 'PEG ID / NPK / NUPTK hanya boleh berisi angka!')
                ->withInput();
        }

        if (in_array($status, ['PNS', 'PPPK']) && empty($nip)) {
            return redirect()->back()
                ->with('error', 'NIP wajib diisi untuk status PNS / PPPK!')
                ->withInput();
        }

        if (!in_array($status, ['PNS', 'PPPK', null, '']) && empty($pegId)) {
            return redirect()->back()
                ->with('error', 'PEG ID / NPK / NUPTK wajib diisi untuk status selain PNS / PPPK!')
                ->withInput();
        }

        if (!empty($nip)) {
            $existingNip = $this->teacherModel->where('nip', $nip)->withDeleted()->first();
            if ($existingNip) {
                return redirect()->back()
                    ->with('error', 'NIP sudah terdaftar!')
                    ->withInput();
            }
        }

        if (!empty($pegId)) {
            $existingPeg = $this->teacherModel->where('peg_id', $pegId)->withDeleted()->first();
            if ($existingPeg) {
                return redirect()->back()
                    ->with('error', 'PEG ID / NPK / NUPTK sudah terdaftar!')
                    ->withInput();
            }
        }

        $shortCode = $this->request->getPost('short_code');
        if (!empty($shortCode)) {
            $existingCode = $this->teacherModel->where('short_code', $shortCode)->withDeleted()->first();
            if ($existingCode) {
                return redirect()->back()
                    ->with('error', "Kode guru '{$shortCode}' sudah terdaftar!")
                    ->withInput();
            }
        }

        $teacherId = $this->teacherModel->insert([
            'nip'                => $nip ?: null,
            'peg_id'             => $pegId ?: null,
            'short_code'         => $shortCode ?: null,
            'name'               => $this->request->getPost('name'),
            'gender'             => $this->request->getPost('gender'),
            'phone'              => $this->request->getPost('phone') ?: null,
            'email'              => $this->request->getPost('email') ?: null,
            'golongan'           => $this->request->getPost('golongan') ?: null,
            'jabatan'            => $this->request->getPost('jabatan') ?: null,
            'status_kepegawaian' => $status,
            'is_sertifikasi'     => (int)$this->request->getPost('is_sertifikasi'),
            'is_active'          => 1,
        ]);

        if ($this->request->getPost('create_account') && $teacherId) {
            $teacher = $this->teacherModel->find($teacherId);
            $username = teacher_login_identifier($teacher);

            if (!empty($username)) {
                $existingUser = $this->userModel->where('username', $username)->withDeleted()->first();
                if (!$existingUser) {
                    $loginEmail = $this->request->getPost('login_email') ?: $teacher['email'];
                    $password   = $this->request->getPost('login_password') ?: $username;

                    $userId = $this->userModel->insert([
                        'username'  => $username,
                        'name'      => $teacher['name'],
                        'email'     => $loginEmail ?: null,
                        'password'  => password_hash($password, PASSWORD_DEFAULT),
                        'role'      => 'guru',
                        'is_active' => 1,
                    ]);

                    $this->teacherModel->update($teacherId, ['user_id' => $userId]);
                }
            }
        }

        if ($teacherId) {
            log_activity('create', 'guru', $teacherId, "Menambahkan guru baru: " . $this->request->getPost('name') . " (NIP: " . ($this->request->getPost('nip') ?: '-') . ")");
        }

        return redirect()->to('/teacher')
            ->with('success', 'Data guru berhasil ditambahkan!');
    }

    public function edit($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        if ($redirect = $this->checkAdmin()) return $redirect;

        $teacher = $this->teacherModel->getWithUser($id);
        if (!$teacher) {
            return redirect()->to('/teacher')->with('error', 'Data guru tidak ditemukan!');
        }

        return view('teacher/edit', [
            'title'   => 'Edit Guru',
            'teacher' => $teacher,
        ]);
    }

    public function update($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        if ($redirect = $this->checkAdmin()) return $redirect;

        $rules = [
            'name'   => 'required|min_length[3]|max_length[100]',
            'gender' => 'required|in_list[L,P]',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        $nip    = $this->request->getPost('nip');
        $pegId  = $this->request->getPost('peg_id');
        $status = $this->request->getPost('status_kepegawaian') ?: null;

        if (!empty($pegId) && !preg_match('/^[0-9]+$/', $pegId)) {
            return redirect()->back()
                ->with('error', 'PEG ID / NPK / NUPTK hanya boleh berisi angka!')
                ->withInput();
        }

        if (in_array($status, ['PNS', 'PPPK']) && empty($nip)) {
            return redirect()->back()
                ->with('error', 'NIP wajib diisi untuk status PNS / PPPK!')
                ->withInput();
        }

        if (!in_array($status, ['PNS', 'PPPK', null, '']) && empty($pegId)) {
            return redirect()->back()
                ->with('error', 'PEG ID / NPK / NUPTK wajib diisi untuk status selain PNS / PPPK!')
                ->withInput();
        }

        $shortCode = $this->request->getPost('short_code');
        if (!empty($shortCode)) {
            $existing = $this->teacherModel->where('short_code', $shortCode)
                                           ->where('id !=', $id)
                                           ->withDeleted()
                                           ->first();
            if ($existing) {
                return redirect()->back()
                    ->with('error', "Kode guru '{$shortCode}' sudah terdaftar!")
                    ->withInput();
            }
        }

        if (!empty($pegId)) {
            $existingPeg = $this->teacherModel->where('peg_id', $pegId)
                                              ->where('id !=', $id)
                                              ->withDeleted()
                                              ->first();
            if ($existingPeg) {
                return redirect()->back()
                    ->with('error', 'PEG ID / NPK / NUPTK sudah terdaftar!')
                    ->withInput();
            }
        }

        $oldTeacher = $this->teacherModel->find($id);

        $this->teacherModel->update($id, [
            'nip'                => $nip ?: null,
            'peg_id'             => $pegId ?: null,
            'short_code'         => $shortCode ?: null,
            'name'               => $this->request->getPost('name'),
            'gender'             => $this->request->getPost('gender'),
            'phone'              => $this->request->getPost('phone') ?: null,
            'email'              => $this->request->getPost('email') ?: null,
            'golongan'           => $this->request->getPost('golongan') ?: null,
            'jabatan'            => $this->request->getPost('jabatan') ?: null,
            'status_kepegawaian' => $status,
            'is_sertifikasi'     => (int)$this->request->getPost('is_sertifikasi'),
            'is_active'          => $this->request->getPost('is_active') ? 1 : 0,
        ]);

        $newUsername = teacher_login_identifier(['nip' => $nip, 'peg_id' => $pegId, 'status_kepegawaian' => $status]);
        $oldUsername = teacher_login_identifier($oldTeacher);

        if ($oldTeacher['user_id'] && $newUsername && $oldUsername !== $newUsername) {
            $this->userModel->update($oldTeacher['user_id'], [
                'username' => $newUsername,
                'name'     => $this->request->getPost('name'),
            ]);
        }

        if ($oldTeacher['user_id'] && $oldTeacher['name'] !== $this->request->getPost('name')) {
            $this->userModel->update($oldTeacher['user_id'], [
                'name' => $this->request->getPost('name'),
            ]);
        }

        if ($this->request->getPost('create_account')) {
            $teacher = $this->teacherModel->find($id);
            if (!$teacher['user_id']) {
                $this->createUserAccount($id);
            }
        }

        log_activity('update', 'guru', $id, "Mengubah data guru: " . $this->request->getPost('name') . " (NIP: " . ($this->request->getPost('nip') ?: '-') . ")");

        return redirect()->to('/teacher')
            ->with('success', 'Data guru berhasil diupdate!');
    }

    public function delete($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        if ($redirect = $this->checkAdmin()) return $redirect;

        $teacher = $this->teacherModel->find($id);
        if (!$teacher) {
            return redirect()->to('/teacher')->with('error', 'Data guru tidak ditemukan!');
        }

        if ($teacher['user_id']) {
            $this->userModel->update($teacher['user_id'], ['is_active' => 0]);
        }

        $this->teacherModel->delete($id);

        log_activity('delete', 'guru', $id, "Menonaktifkan guru: " . $teacher['name'] . " (NIP: " . ($teacher['nip'] ?: '-') . ")");

        return redirect()->to('/teacher')
            ->with('success', 'Guru berhasil dinonaktifkan dan dipindah ke tab Non-Aktif.');
    }

    public function restore($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        if ($redirect = $this->checkAdmin()) return $redirect;

        $teacher = $this->teacherModel->withDeleted()->find($id);
        if (!$teacher || $teacher['deleted_at'] === null) {
            return redirect()->to('/teacher')->with('error', 'Data guru tidak ditemukan atau sudah aktif!');
        }

        $this->teacherModel->db->table('teachers')
            ->where('id', $id)
            ->update(['deleted_at' => null]);

        if ($teacher['user_id']) {
            $this->userModel->update($teacher['user_id'], ['is_active' => 1]);
        }

        log_activity('update', 'guru', $id, "Mengaktifkan kembali guru: " . $teacher['name'] . " (NIP: " . ($teacher['nip'] ?: '-') . ")");

        return redirect()->to('/teacher')
            ->with('success', 'Guru ' . esc($teacher['name']) . ' berhasil diaktifkan kembali!');
    }

    public function forceDelete($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        if ($redirect = $this->checkAdmin()) return $redirect;

        $teacher = $this->teacherModel->withDeleted()->find($id);
        if (!$teacher) {
            return redirect()->to('/teacher')->with('error', 'Data guru tidak ditemukan!');
        }

        if ($teacher['user_id']) {
            $this->teacherModel->db->table('users')
                ->where('id', $teacher['user_id'])
                ->delete();
        }

        log_activity('delete', 'guru', $id, "Menghapus permanen data guru: " . $teacher['name'] . " (NIP: " . ($teacher['nip'] ?: '-') . ")");

        $this->teacherModel->db->table('teachers')
            ->where('id', $id)
            ->delete();

        return redirect()->to('/teacher')
            ->with('success', 'Data guru ' . esc($teacher['name']) . ' dihapus permanen!');
    }

    public function createAccount($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teacher = $this->teacherModel->find($id);
        if (!$teacher) {
            return $this->response->setJSON(['success' => false, 'message' => 'Guru tidak ditemukan!']);
        }
        if ($teacher['user_id']) {
            return $this->response->setJSON(['success' => false, 'message' => 'Guru sudah memiliki akun login!']);
        }

        $username = teacher_login_identifier($teacher);
        if (empty($username)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Guru harus memiliki NIP atau PEG ID/NPK/NUPTK untuk dibuatkan akun!',
                'csrf_token' => csrf_hash()
            ]);
        }

        $existing = $this->userModel->where('username', $username)->withDeleted()->first();
        if ($existing) {
            return $this->response->setJSON([
                'success' => false,
                'message' => $username . ' sudah terdaftar sebagai username akun lain!',
                'csrf_token' => csrf_hash()
            ]);
        }

        $password = $this->request->getPost('password');
        if (empty($password)) {
            $password = $username;
        }

        $email = $this->request->getPost('email') ?: $teacher['email'];

        $userId = $this->userModel->insert([
            'username'  => $username,
            'name'      => $teacher['name'],
            'email'     => $email ?: null,
            'password'  => password_hash($password, PASSWORD_DEFAULT),
            'role'      => 'guru',
            'is_active' => 1,
        ]);

        $this->teacherModel->update($id, ['user_id' => $userId]);

        return $this->response->setJSON([
            'success'    => true,
            'message'    => 'Akun login berhasil dibuat! Username: ' . $username . ' | Password: ' . $password,
            'csrf_token' => csrf_hash(),
        ]);
    }

    public function createAccountBulk()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teacherIds = $this->request->getPost('teacher_ids');

        if (empty($teacherIds)) {
            return $this->response->setJSON([
                'success'    => false,
                'message'    => 'Pilih minimal satu guru!',
                'csrf_token' => csrf_hash(),
            ]);
        }

        $success = 0;
        $skipped = 0;
        $errors  = [];

        foreach ($teacherIds as $teacherId) {
            $teacher = $this->teacherModel->find($teacherId);

            if (!$teacher || $teacher['user_id']) {
                $skipped++;
                continue;
            }

            $username = teacher_login_identifier($teacher);
            if (empty($username)) {
                $errors[] = $teacher['name'] . ' (NIP/PEG ID kosong)';
                continue;
            }

            $existing = $this->userModel->where('username', $username)->withDeleted()->first();
            if ($existing) {
                $errors[] = $teacher['name'] . ' (' . $username . ' sudah dipakai akun lain)';
                continue;
            }

            $password = $username;

            $userId = $this->userModel->insert([
                'username'  => $username,
                'name'      => $teacher['name'],
                'email'     => $teacher['email'] ?: null,
                'password'  => password_hash($password, PASSWORD_DEFAULT),
                'role'      => 'guru',
                'is_active' => 1,
            ]);

            $this->teacherModel->update($teacherId, ['user_id' => $userId]);
            $success++;
        }

        $msg = "{$success} akun berhasil dibuat.";
        if ($skipped) $msg .= " {$skipped} dilewati (sudah punya akun).";
        if (!empty($errors)) $msg .= " Gagal: " . implode(', ', $errors) . ".";

        return $this->response->setJSON([
            'success'    => $success > 0,
            'message'    => $msg,
            'csrf_token' => csrf_hash(),
        ]);
    }

    public function resetPassword($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teacher = $this->teacherModel->find($id);
        if (!$teacher || !$teacher['user_id']) {
            return $this->response->setJSON(['success' => false, 'message' => 'Guru tidak punya akun login!', 'csrf_token' => csrf_hash()]);
        }

        $newPassword = teacher_login_identifier($teacher) ?: 'guru123';

        $this->userModel->update($teacher['user_id'], [
            'password' => password_hash($newPassword, PASSWORD_DEFAULT),
        ]);

        return $this->response->setJSON([
            'success'    => true,
            'message'    => 'Password direset ke: ' . $newPassword,
            'csrf_token' => csrf_hash(),
        ]);
    }

    public function importExcel()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        if ($redirect = $this->checkAdmin()) return $redirect;

        return view('teacher/import', ['title' => 'Import Excel Guru']);
    }

    public function importProcess()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        if ($redirect = $this->checkAdmin()) return $redirect;

        $file = $this->request->getFile('excel_file');

        if (!$file || !$file->isValid()) {
            return redirect()->back()->with('error', 'File tidak valid!');
        }

        $ext = strtolower($file->getClientExtension());
        if (!in_array($ext, ['xlsx', 'xls'])) {
            return redirect()->back()->with('error', 'File harus .xlsx atau .xls!');
        }

        try {
            $reader      = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($file->getTempName());
            $spreadsheet = $reader->load($file->getTempName());
            $rows        = $spreadsheet->getActiveSheet()->toArray();

            array_shift($rows);

            $success = 0;
            $errors  = [];

            foreach ($rows as $i => $row) {
                $rowNum = $i + 2;
                if (empty($row[0]) && empty($row[1])) continue;

                $nip               = trim($row[0] ?? '');
                $pegId             = trim($row[1] ?? '');
                $name              = trim($row[2] ?? '');
                $gender            = strtoupper(trim($row[3] ?? ''));
                $phone             = trim($row[4] ?? '');
                $email             = trim($row[5] ?? '');
                $shortCode         = trim($row[6] ?? '');
                $golongan          = trim($row[7] ?? '');
                $jabatan           = trim($row[8] ?? '');
                $statusKepegawaian = trim($row[9] ?? '');
                $sertifikasiText   = strtolower(trim($row[10] ?? ''));
                $isSertifikasi     = (in_array($sertifikasiText, ['sudah', 'ya', '1', 'sertifikasi'])) ? 1 : 0;

                if (empty($name)) {
                    $errors[] = "Baris {$rowNum}: Nama kosong";
                    continue;
                }
                if (!in_array($gender, ['L', 'P'])) {
                    $errors[] = "Baris {$rowNum}: JK harus L atau P";
                    continue;
                }

                if (!empty($pegId) && !preg_match('/^[0-9]+$/', $pegId)) {
                    $errors[] = "Baris {$rowNum}: PEG ID harus berupa angka saja";
                    continue;
                }

                $this->teacherModel->insert([
                    'nip'                => $nip ?: null,
                    'peg_id'             => $pegId ?: null,
                    'short_code'         => $shortCode ?: null,
                    'name'               => $name,
                    'gender'             => $gender,
                    'phone'              => $phone ?: null,
                    'email'              => $email ?: null,
                    'golongan'           => $golongan ?: null,
                    'jabatan'            => $jabatan ?: null,
                    'status_kepegawaian' => $statusKepegawaian ?: null,
                    'is_sertifikasi'     => $isSertifikasi,
                    'is_active'          => 1,
                ]);

                $success++;
            }

            $message = "Berhasil import {$success} guru.";
            if (!empty($errors)) {
                session()->setFlashdata('import_errors', $errors);
            }

            log_activity('import', 'guru', null, "Melakukan import data guru sebanyak {$success} records");

            return redirect()->to('/teacher/import')->with('success', $message);

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Gagal membaca file: ' . $e->getMessage());
        }
    }

    public function downloadTemplate()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Data Guru');

        $headers = ['NIP', 'PEG ID/NPK/NUPTK', 'Nama Lengkap *', 'JK * (L/P)', 'No. HP', 'Email', 'Kode Guru (aSc)', 'Pangkat/Golongan', 'Jabatan', 'Status Kepegawaian (PNS/PPPK/Honorer)', 'Status Sertifikasi (Sudah/Belum)'];
        $widths  = [20, 25, 30, 12, 18, 30, 15, 25, 25, 25, 25];

        foreach ($headers as $i => $h) {
            $col  = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($i + 1);
            $sheet->setCellValue($col . '1', $h);
            $sheet->getStyle($col . '1')->applyFromArray([
                'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 10],
                'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '0D6EFD']],
                'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
                'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'CCCCCC']]],
            ]);
            $sheet->getColumnDimension($col)->setWidth($widths[$i]);
        }

        $example = ['197001001234', '', 'Ahmad Fauzi, S.Pd', 'L', '081234567890', 'ahmad@sekolah.id', '01', 'Penata Muda, III/a', 'Guru', 'PNS', 'Sudah'];
        foreach ($example as $i => $val) {
            $col = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($i + 1);
            $sheet->setCellValue($col . '2', $val);
            $sheet->getStyle($col . '2')->applyFromArray([
                'font'    => ['size' => 9, 'color' => ['rgb' => '888888'], 'italic' => true],
                'fill'    => ['fillType' => 'solid', 'startColor' => ['rgb' => 'FAFAFA']],
                'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'CCCCCC']]],
            ]);
        }

        $sheet->getRowDimension(1)->setRowHeight(24);

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="template_import_guru.xlsx"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }

    public function exportExcel()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        if ($redirect = $this->checkAdmin()) return $redirect;

        $teachers = $this->teacherModel->getAllWithUser();

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Daftar Guru');

        $headers = ['No', 'Kode Guru', 'Nama Lengkap', 'NIP', 'PEG ID/NPK/NUPTK', 'Pangkat/Golongan', 'Jabatan', 'Status Kepegawaian', 'Sertifikasi', 'JK', 'No. HP', 'Email', 'Status Akun'];
        $widths  = [6, 15, 35, 25, 25, 25, 25, 20, 15, 8, 20, 30, 20];

        foreach ($headers as $i => $h) {
            $col  = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($i + 1);
            $sheet->setCellValue($col . '1', $h);
            $sheet->getStyle($col . '1')->applyFromArray([
                'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 10],
                'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '198754']],
                'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
                'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'CCCCCC']]],
            ]);
            $sheet->getColumnDimension($col)->setWidth($widths[$i]);
        }

        $rowNum = 2;
        foreach ($teachers as $idx => $t) {
            $status = 'Belum Punya';
            if ($t['user_id']) {
                $status = $t['user_active'] ? 'Akun Aktif' : 'Akun Nonaktif';
            }

            $dataRow = [
                $idx + 1,
                $t['short_code'] ?: '—',
                $t['name'],
                $t['nip'] ?: '—',
                $t['peg_id'] ?: '—',
                $t['golongan'] ?: '—',
                $t['jabatan'] ?: '—',
                $t['status_kepegawaian'] ?: '—',
                $t['is_sertifikasi'] ? 'Sudah' : 'Belum',
                $t['gender'],
                $t['phone'] ?: '—',
                $t['email'] ?: '—',
                $status
            ];

            foreach ($dataRow as $colIdx => $val) {
                $col = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIdx + 1);
                $sheet->setCellValue($col . $rowNum, $val);

                $hAlign = 'left';
                if (in_array($colIdx, [0, 1, 7, 8, 9, 12])) {
                    $hAlign = 'center';
                }

                $sheet->getStyle($col . $rowNum)->applyFromArray([
                    'font'      => ['size' => 9],
                    'alignment' => ['horizontal' => $hAlign, 'vertical' => 'center'],
                    'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'E0E0E0']]],
                ]);
            }
            $sheet->getRowDimension($rowNum)->setRowHeight(20);
            $rowNum++;
        }

        $sheet->getRowDimension(1)->setRowHeight(26);

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="daftar_guru_' . date('Ymd_His') . '.xlsx"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }

    private function createUserAccount($teacherId)
    {
        $teacher  = $this->teacherModel->find($teacherId);
        $username = teacher_login_identifier($teacher);
        $email    = $this->request->getPost('login_email') ?: $teacher['email'];
        $password = $this->request->getPost('login_password') ?: ($username ?: 'guru123');

        if (empty($email)) return;

        $existing = $this->userModel->where('email', $email)->withDeleted()->first();
        if ($existing) return;

        $userId = $this->userModel->insert([
            'name'      => $teacher['name'],
            'email'     => $email,
            'password'  => password_hash($password, PASSWORD_DEFAULT),
            'role'      => 'guru',
            'is_active' => 1,
        ]);

        $this->teacherModel->update($teacherId, ['user_id' => $userId]);
    }
}
