<?php

namespace App\Controllers;

use App\Models\MataKuliahModel;
use App\Models\ProgramStudiModel;
use App\Models\KurikulumModel;
use App\Services\NeoFeederService;

class MataKuliah extends BaseController
{
    protected $mataKuliahModel;
    protected $programStudiModel;
    protected $kurikulumModel;
    protected $neoFeederService;

    public function __construct()
    {
        $this->mataKuliahModel = new MataKuliahModel();
        $this->programStudiModel = new ProgramStudiModel();
        $this->kurikulumModel = new KurikulumModel();
        $this->neoFeederService = new NeoFeederService();
    }

    public function index()
    {
        $search = $this->request->getGet('search');
        $prodi = $this->request->getGet('prodi');
        $kurikulum = $this->request->getGet('kurikulum');
        $semester = $this->request->getGet('semester');
        $perPage = $this->request->getGet('per_page') ?? 10;

        $this->mataKuliahModel->select('mata_kuliah.*, program_studi.nama_prodi, kurikulum.nama_kurikulum');
        $this->mataKuliahModel->join('program_studi', 'program_studi.id = mata_kuliah.id_program_studi', 'left');
        $this->mataKuliahModel->join('kurikulum', 'kurikulum.id = mata_kuliah.id_kurikulum', 'left');

        if (!empty($search)) {
            $this->mataKuliahModel->groupStart()
                ->like('mata_kuliah.kode_mata_kuliah', $search)
                ->orLike('mata_kuliah.nama_mata_kuliah', $search)
                ->groupEnd();
        }

        if (!empty($prodi)) {
            $this->mataKuliahModel->where('mata_kuliah.id_program_studi', $prodi);
        }

        if (!empty($kurikulum)) {
            $this->mataKuliahModel->where('mata_kuliah.id_kurikulum', $kurikulum);
        }

        if (!empty($semester)) {
            $this->mataKuliahModel->where('mata_kuliah.semester', $semester);
        }

        $data = [
            'title' => 'Data Mata Kuliah | SIAKAD ITKA',
            'mata_kuliah' => $this->mataKuliahModel->paginate($perPage, 'mata_kuliah'),
            'pager' => $this->mataKuliahModel->pager,
            'list_prodi' => $this->programStudiModel->findAll(),
            'list_kurikulum' => $this->kurikulumModel->findAll(),
            'per_page' => $perPage
        ];

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

    public function sync()
    {
        if (!$this->neoFeederService->isConfigured()) {
            session()->setFlashdata('error', 'Konfigurasi PDDIKTI belum diatur. Silakan atur di menu Pengaturan PDDIKTI.');
            return redirect()->to('/mata-kuliah');
        }

        $resultMK = $this->neoFeederService->request('GetListMataKuliah');

        if (isset($resultMK['error_code']) && $resultMK['error_code'] == 0 && isset($resultMK['data'])) {
            $prodiLocal = $this->programStudiModel->findAll();
            $prodiMap = [];
            foreach ($prodiLocal as $p) {
                if(!empty($p['id_prodi_pddikti'])) {
                    $prodiMap[$p['id_prodi_pddikti']] = $p['id'];
                }
            }

            $successCount = 0;
            $updateCount = 0;

            foreach ($resultMK['data'] as $pddikti) {
                $idProdiPddikti = $pddikti['id_prodi'] ?? '';
                $idProdi = $prodiMap[$idProdiPddikti] ?? null;

                $existing = $this->mataKuliahModel->where('id_matkul_pddikti', $pddikti['id_matkul'])->first();

                $data = [
                    'id_matkul_pddikti' => $pddikti['id_matkul'],
                    'kode_mata_kuliah'   => $pddikti['kode_mata_kuliah'] ?? '',
                    'nama_mata_kuliah'   => $pddikti['nama_mata_kuliah'] ?? '',
                    'id_program_studi'   => $idProdi,
                    'sks_mata_kuliah'    => $pddikti['sks_mata_kuliah'] ?? 0,
                    'sks_tatap_muka'     => $pddikti['sks_tatap_muka'] ?? 0,
                    'sks_praktek'        => $pddikti['sks_praktek'] ?? 0,
                    'jenis_mata_kuliah'  => $pddikti['nama_jenis_mata_kuliah'] ?? '', // or id_jenis_mata_kuliah
                ];

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

            session()->setFlashdata('pesan', "Sinkronisasi berhasil. $successCount data baru ditambahkan, $updateCount data diperbarui.");
        } else {
            $errorMsg = $resultMK['error_desc'] ?? 'Unknown Error';
            session()->setFlashdata('error', "Sinkronisasi gagal: " . $errorMsg);
        }

        return redirect()->to('/mata-kuliah');
    }
}
