<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\DosenModel;
use App\Models\UserModel;
use App\Services\NeoFeederService;

class Dosen extends BaseController
{
    protected DosenModel $dosenModel;
    protected UserModel $userModel;

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

    public function index()
    {
        // Parameter GET
        $search = $this->request->getGet('search');
        $jenis = $this->request->getGet('jenis');
        $status = $this->request->getGet('status');
        $perPage = $this->request->getGet('per_page') ?: 10;

        $this->dosenModel->select('dosen.*, users.username');
        $this->dosenModel->join('users', 'users.id = dosen.user_id', 'left');

        // Filter: Search (Nama / NIDN / NUPTK)
        if (!empty($search)) {
            $this->dosenModel->groupStart()
                ->like('dosen.nama_lengkap', $search)
                ->orLike('dosen.nidn', $search)
                ->orLike('dosen.nuptk', $search)
                ->groupEnd();
        }

        // Filter: Jenis Dosen
        if (!empty($jenis)) {
            $this->dosenModel->where('dosen.jenis_dosen', $jenis);
        }

        // Filter: Status
        if (!empty($status)) {
            $this->dosenModel->where('dosen.status_aktif', $status);
        }

        $this->dosenModel->orderBy('dosen.nama_lengkap', 'ASC');

        // Untuk Dropdown Filter
        $db = \Config\Database::connect();
        
        $queryJenis = $db->query("SELECT DISTINCT jenis_dosen FROM dosen WHERE jenis_dosen IS NOT NULL AND jenis_dosen != '' ORDER BY jenis_dosen ASC");
        $listJenis = $queryJenis->getResultArray();
        
        $queryStatus = $db->query("SELECT DISTINCT status_aktif FROM dosen WHERE status_aktif IS NOT NULL AND status_aktif != '' ORDER BY status_aktif ASC");
        $listStatus = $queryStatus->getResultArray();

        $data = [
            'title'     => 'Data Dosen | siAkad ITKA',
            'dosen'     => $this->dosenModel->paginate($perPage, 'dosen'),
            'pager'     => $this->dosenModel->pager,
            'search'    => $search,
            'jenis'     => $jenis,
            'status'    => $status,
            'per_page'  => $perPage,
            'listJenis' => $listJenis,
            'listStatus'=> $listStatus
        ];

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

    public function syncPddikti()
    {
        $neoFeeder = new NeoFeederService();
        $response = $neoFeeder->request('GetListDosen');

        if (isset($response['error_code']) && $response['error_code'] == 0 && !empty($response['data'])) {
            $countNew = 0;
            $countUpdate = 0;
            $roleDosenId = 6; // Role Dosen

            foreach ($response['data'] as $dosenPddikti) {
                // Determine Username (NIDN -> NUPTK -> NIP -> Random string as fallback)
                $username = !empty($dosenPddikti['nidn']) ? $dosenPddikti['nidn'] : 
                            (!empty($dosenPddikti['nuptk']) ? $dosenPddikti['nuptk'] : 
                            (!empty($dosenPddikti['nip']) ? $dosenPddikti['nip'] : null));
                
                // Determine Password (YYYYMMDD)
                $passwordPlain = '123456'; // fallback default
                if (!empty($dosenPddikti['tanggal_lahir'])) {
                    // Format from PDDIKTI is usually YYYY-MM-DD or DD-MM-YYYY
                    $tl = explode('-', $dosenPddikti['tanggal_lahir']);
                    if (count($tl) == 3) {
                        if (strlen($tl[0]) == 4) { // YYYY-MM-DD
                            $passwordPlain = $tl[0] . $tl[1] . $tl[2];
                        } else if (strlen($tl[2]) == 4) { // DD-MM-YYYY
                            $passwordPlain = $tl[2] . $tl[1] . $tl[0];
                        }
                    }
                }

                // Cek dosen existing
                $existingDosen = $this->dosenModel->where('id_dosen_pddikti', $dosenPddikti['id_dosen'])->first();
                $userId = null;

                $statusMapping = [
                    'aktif' => 'Aktif',
                    'cuti' => 'Cuti',
                    'tugas belajar' => 'Tugas Belajar',
                    'keluar' => 'Keluar',
                ];
                $statusPddikti = strtolower(trim($dosenPddikti['nama_status_aktif'] ?? ''));
                $status_aktif = isset($statusMapping[$statusPddikti]) ? $statusMapping[$statusPddikti] : 'Keluar';

                if (!$existingDosen) {
                    // User creation ONLY for new dosen
                    if ($username) {
                        $existingUser = $this->userModel->where('username', $username)->first();
                        if (!$existingUser) {
                            $this->userModel->save([
                                'username'      => $username,
                                'email'         => $username . '@itka.ac.id', // Dummy unique email
                                'password_hash' => password_hash($passwordPlain, PASSWORD_DEFAULT),
                                'role_id'       => $roleDosenId,
                                'is_active'     => 1
                            ]);
                            $userId = $this->userModel->getInsertID();
                        } else {
                            $userId = $existingUser['id'];
                        }
                    }

                    $this->dosenModel->save([
                        'user_id'          => $userId,
                        'nidn'             => $dosenPddikti['nidn'],
                        'nuptk'            => $dosenPddikti['nuptk'],
                        'nama_lengkap'     => $dosenPddikti['nama_dosen'],
                        'jenis_kelamin'    => $dosenPddikti['jenis_kelamin'],
                        'status_aktif'     => $status_aktif,
                        'id_dosen_pddikti' => $dosenPddikti['id_dosen']
                    ]);
                    $countNew++;
                } else {
                    $this->dosenModel->save([
                        'id'               => $existingDosen['id'],
                        'nidn'             => $dosenPddikti['nidn'],
                        'nuptk'            => $dosenPddikti['nuptk'],
                        'nama_lengkap'     => $dosenPddikti['nama_dosen'],
                        'jenis_kelamin'    => $dosenPddikti['jenis_kelamin'],
                        'status_aktif'     => $status_aktif,
                        'id_dosen_pddikti' => $dosenPddikti['id_dosen']
                    ]);
                    $countUpdate++;
                }
            }

            session()->setFlashdata('success', "Berhasil sinkronisasi. $countNew Dosen baru ditambahkan, $countUpdate Dosen diperbarui.");
        } else {
            session()->setFlashdata('error', 'Gagal menarik data dari PDDIKTI. Pastikan koneksi dan pengaturan Neo Feeder sudah benar.');
        }

        return redirect()->to('/dosen');
    }

    public function edit(string $id)
    {
        $dosen = $this->dosenModel->find($id);
        if (!$dosen) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException("Data Dosen tidak ditemukan");
        }

        $data = [
            'title' => 'Edit Dosen | siAkad ITKA',
            'dosen' => $dosen
        ];

        return view('dosen/edit', $data);
    }

    public function update(string $id)
    {
        $dosen = $this->dosenModel->find($id);
        if (!$dosen) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException("Data Dosen tidak ditemukan");
        }

        $this->dosenModel->update($id, [
            'jenis_dosen' => $this->request->getPost('jenis_dosen'),
            'no_hp'       => $this->request->getPost('no_hp')
        ]);

        session()->setFlashdata('success', 'Data Dosen berhasil diperbarui.');
        return redirect()->to('/dosen');
    }
    public function create()
    {
        $data = [
            'title' => 'Tambah Dosen | siAkad ITKA',
            'validation' => \Config\Services::validation()
        ];
        return view('dosen/create', $data);
    }

    public function store()
    {
        $jenis_dosen = $this->request->getPost('jenis_dosen');
        
        $rules = [
            'nama_lengkap' => 'required',
            'jenis_kelamin' => 'required',
            'status_aktif' => 'required',
            'jenis_dosen' => 'required'
        ];

        if ($jenis_dosen == 'Internal') {
            $rules['nidn'] = 'required|is_unique[dosen.nidn]';
        } else {
            $rules['email'] = 'required|valid_email|is_unique[users.email]';
        }

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

        $nidn = $this->request->getPost('nidn');
        $email = $this->request->getPost('email');
        
        $username = ($jenis_dosen == 'Internal') ? $nidn : $email;
        $passwordPlain = '123456';
        $roleDosenId = 6;

        // Cek apakah user sudah ada berdasarkan username
        $existingUser = $this->userModel->where('username', $username)->first();
        
        $userId = null;
        if (!$existingUser) {
            $this->userModel->insert([
                'username'      => $username,
                'email'         => ($jenis_dosen == 'Eksternal') ? $email : ($username . '@itka.ac.id'),
                'password_hash' => password_hash($passwordPlain, PASSWORD_DEFAULT),
                'role_id'       => $roleDosenId,
                'is_active'     => 1
            ]);
            $userId = $this->userModel->getInsertID();
        } else {
            $userId = $existingUser['id'];
        }

        $this->dosenModel->insert([
            'user_id'          => $userId,
            'nidn'             => empty($nidn) ? null : $nidn,
            'nuptk'            => $this->request->getPost('nuptk') ?: null,
            'nama_lengkap'     => $this->request->getPost('nama_lengkap'),
            'gelar_depan'      => $this->request->getPost('gelar_depan'),
            'gelar_belakang'   => $this->request->getPost('gelar_belakang'),
            'jenis_kelamin'    => $this->request->getPost('jenis_kelamin'),
            'no_hp'            => $this->request->getPost('no_hp'),
            'status_aktif'     => $this->request->getPost('status_aktif'),
            'jenis_dosen'      => $jenis_dosen
        ]);

        session()->setFlashdata('success', 'Data Dosen berhasil ditambahkan.');
        return redirect()->to('/dosen');
    }

    public function delete(string $id)
    {
        $dosen = $this->dosenModel->find($id);
        
        if (!$dosen) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException("Data Dosen tidak ditemukan");
        }

        // Jika dosen memiliki user_id, hapus user-nya juga
        if (!empty($dosen['user_id'])) {
            $this->userModel->delete($dosen['user_id']);
        }

        // Hapus dosen
        $this->dosenModel->delete($id);

        session()->setFlashdata('success', 'Data Dosen berhasil dihapus beserta akunnya (jika ada).');
        return redirect()->to('/dosen');
    }
}
