<?php

namespace App\Controllers;

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

class Kurikulum extends BaseController
{
    protected $kurikulumModel;
    protected $programStudiModel;
    protected $neoFeederService;

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

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

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

        if (!empty($search)) {
            $this->kurikulumModel->groupStart()
                ->like('kurikulum.nama_kurikulum', $search)
                ->groupEnd();
        }

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

        $data = [
            'title' => 'Data Kurikulum | SIAKAD ITKA',
            'kurikulum' => $this->kurikulumModel->paginate($perPage, 'kurikulum'),
            'pager' => $this->kurikulumModel->pager,
            'list_prodi' => $this->programStudiModel->findAll(),
            'per_page' => $perPage
        ];

        return view('kurikulum/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('/kurikulum');
        }

        $resultKurikulum = $this->neoFeederService->request('GetKurikulum');

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

            $successCount = 0;
            $updateCount = 0;

            foreach ($resultKurikulum['data'] as $pddikti) {
                $idProdiPddikti = $pddikti['id_prodi'] ?? '';
                $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;
                        }
                    }
                }

                $existing = $this->kurikulumModel->where('id_kurikulum_pddikti', $pddikti['id_kurikulum'])->first();

                $data = [
                    'id_kurikulum_pddikti' => $pddikti['id_kurikulum'],
                    'nama_kurikulum'       => $pddikti['nama_kurikulum'] ?? '',
                    'id_program_studi'     => $idProdi,
                    'nama_program_studi'   => $namaProdiPddikti,
                    'mulai_berlaku'        => $pddikti['id_semester'] ?? '',
                    'sks_lulus'            => $pddikti['jumlah_sks_lulus'] ?? 0,
                    'sks_wajib'            => $pddikti['jumlah_sks_wajib'] ?? 0,
                    'sks_pilihan'          => $pddikti['jumlah_sks_pilihan'] ?? 0,
                ];

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

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

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