<?php

namespace App\Controllers;

use App\Models\PenugasanDosenModel;
use App\Models\DosenModel;
use App\Models\ProgramStudiModel;
use App\Models\PengaturanModel;

class PenugasanDosen extends BaseController
{
    protected $penugasanDosenModel;
    protected $dosenModel;
    protected $programStudiModel;
    protected $pengaturanModel;

    public function __construct()
    {
        $this->penugasanDosenModel = new PenugasanDosenModel();
        $this->dosenModel = new DosenModel();
        $this->programStudiModel = new ProgramStudiModel();
        $this->pengaturanModel = new PengaturanModel();
    }

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

        // Join with dosen table to get nama_dosen, nidn, etc
        $this->penugasanDosenModel->select('penugasan_dosen.*, dosen.nama_lengkap, dosen.nidn, dosen.nuptk, dosen.jenis_kelamin');
        $this->penugasanDosenModel->join('dosen', 'dosen.id = penugasan_dosen.id_dosen', 'left');

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

        // Filter: Tahun Ajaran
        if (!empty($tahun_ajaran)) {
            $this->penugasanDosenModel->where('penugasan_dosen.nama_tahun_ajaran', $tahun_ajaran);
        }

        // Filter: Prodi
        if (!empty($prodi)) {
            $this->penugasanDosenModel->where('penugasan_dosen.id_program_studi', $prodi);
        }

        // Filter: Homebase
        if (!empty($homebase)) {
            $this->penugasanDosenModel->where('penugasan_dosen.is_homebase', $homebase);
        }

        $this->penugasanDosenModel->orderBy('penugasan_dosen.nama_tahun_ajaran', 'DESC');
        $this->penugasanDosenModel->orderBy('dosen.nama_lengkap', 'ASC');

        // Untuk Dropdown Filter
        $db = \Config\Database::connect();
        
        $queryTahun = $db->query("SELECT DISTINCT nama_tahun_ajaran FROM penugasan_dosen WHERE nama_tahun_ajaran IS NOT NULL AND nama_tahun_ajaran != '' ORDER BY nama_tahun_ajaran DESC");
        $listTahun = $queryTahun->getResultArray();
        
        $listProdi = $this->programStudiModel->findAll();

        $data = [
            'title'        => 'Penugasan Dosen',
            'penugasan'    => $this->penugasanDosenModel->paginate($perPage, 'penugasan'),
            'pager'        => $this->penugasanDosenModel->pager,
            'search'       => $search,
            'tahun_ajaran' => $tahun_ajaran,
            'prodi_id'     => $prodi,
            'homebase'     => $homebase,
            'per_page'     => $perPage,
            'listTahun'    => $listTahun,
            'listProdi'    => $listProdi
        ];

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

    public function syncPddikti()
    {
        $pddiktiUrl = $this->pengaturanModel->getValue('pddikti_url', '');
        $pddiktiUsername = $this->pengaturanModel->getValue('pddikti_username', '');
        $pddiktiPassword = $this->pengaturanModel->getValue('pddikti_password', '');

        if (empty($pddiktiUrl) || empty($pddiktiUsername) || empty($pddiktiPassword)) {
            session()->setFlashdata('error', 'Pengaturan PDDIKTI belum lengkap.');
            return redirect()->to('/penugasan-dosen');
        }

        try {
            $client = \Config\Services::curlrequest();

            // 1. Get Token
            $response = $client->post($pddiktiUrl, [
                'json' => [
                    'act' => 'GetToken',
                    'username' => $pddiktiUsername,
                    'password' => $pddiktiPassword
                ],
                'verify' => false
            ]);

            $result = json_decode($response->getBody(), true);

            if ($result['error_code'] != 0) {
                session()->setFlashdata('error', 'Gagal mendapatkan token: ' . $result['error_desc']);
                return redirect()->to('/penugasan-dosen');
            }

            $token = $result['data']['token'];

            // 2. Get List Penugasan Dosen
            // Note: we fetch up to a large number to ensure we get all assignments
            $responsePenugasan = $client->post($pddiktiUrl, [
                'json' => [
                    'act' => 'GetListPenugasanSemuaDosen',
                    'token' => $token,
                    'limit' => 5000 
                ],
                'verify' => false
            ]);

            $resultPenugasan = json_decode($responsePenugasan->getBody(), true);

            if ($resultPenugasan['error_code'] != 0) {
                session()->setFlashdata('error', 'Gagal mengambil data penugasan: ' . $resultPenugasan['error_desc']);
                return redirect()->to('/penugasan-dosen');
            }

            $penugasanPddikti = $resultPenugasan['data'];
            
            $dosenLocal = $this->dosenModel->findAll();
            $dosenMap = [];
            foreach ($dosenLocal as $d) {
                $dosenMap[$d['id_dosen_pddikti']] = $d['id'];
            }

            $prodiLocal = $this->programStudiModel->findAll();
            $prodiMap = [];
            $prodiNameMap = [];
            foreach ($prodiLocal as $p) {
                $prodiMap[$p['id_prodi_pddikti']] = $p['id'];
                $prodiNameMap[$p['id_prodi_pddikti']] = $p['nama_prodi'];
            }

            $successCount = 0;
            $updateCount = 0;

            foreach ($penugasanPddikti as $pddikti) {
                // Find matching dosen and prodi
                $idDosenPddikti = $pddikti['id_dosen'];
                $idProdiPddikti = $pddikti['id_prodi'];
                
                $idDosen = $dosenMap[$idDosenPddikti] ?? null;
                if (!$idDosen) {
                    continue; // Skip if dosen not found in local DB
                }
                
                $idProdi = $prodiMap[$idProdiPddikti] ?? null;
                $namaProdiPddikti = $pddikti['nama_program_studi'] ?? '';

                if (!$idProdi && !empty($namaProdiPddikti)) {
                    foreach ($prodiLocal as $pl) {
                        if (stripos($namaProdiPddikti, trim($pl['nama_prodi'])) !== false) {
                            $idProdi = $pl['id'];
                            break;
                        }
                    }
                }

                $existingPenugasan = $this->penugasanDosenModel->where('id_registrasi_dosen', $pddikti['id_registrasi_dosen'])->first();
                
                $isHomebase = 'Tidak';
                if (isset($pddikti['apakah_homebase'])) {
                    if ($pddikti['apakah_homebase'] == 1 || strtolower($pddikti['apakah_homebase']) == 'ya' || $pddikti['apakah_homebase'] === true) {
                        $isHomebase = 'Ya';
                    }
                }

                $data = [
                    'id_registrasi_dosen' => $pddikti['id_registrasi_dosen'] ?? null,
                    'id_dosen'            => $idDosen,
                    'id_program_studi'    => $idProdi,
                    'id_tahun_ajaran'     => $pddikti['id_tahun_ajaran'] ?? null,
                    'nama_tahun_ajaran'   => $pddikti['nama_tahun_ajaran'] ?? null,
                    'nama_program_studi'  => $pddikti['nama_program_studi'] ?? ($prodiNameMap[$idProdiPddikti] ?? '-'),
                    'no_surat_tugas'      => $pddikti['nomor_surat_tugas'] ?? null,
                    'tanggal_surat_tugas' => !empty($pddikti['tanggal_surat_tugas']) ? date('Y-m-d', strtotime($pddikti['tanggal_surat_tugas'])) : null,
                    'is_homebase'         => $isHomebase
                ];

                if ($existingPenugasan) {
                    $this->penugasanDosenModel->update($existingPenugasan['id'], $data);
                    $updateCount++;
                } else {
                    $this->penugasanDosenModel->insert($data);
                    $successCount++;
                }
            }

            session()->setFlashdata('success', "Berhasil menyinkronkan data penugasan dosen. {$successCount} data baru, {$updateCount} diperbarui.");
            return redirect()->to('/penugasan-dosen');

        } catch (\Exception $e) {
            session()->setFlashdata('error', 'Terjadi kesalahan sistem: ' . $e->getMessage());
            return redirect()->to('/penugasan-dosen');
        }
    }
}
