<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\ProgramStudiModel;
use App\Models\FakultasModel;

class Prodi extends BaseController
{
    protected ProgramStudiModel $prodiModel;
    protected FakultasModel $fakultasModel;

    public function __construct()
    {
        $this->prodiModel = new ProgramStudiModel();
        $this->fakultasModel = new FakultasModel();
    }

    public function index()
    {
        // Join with fakultas table to get nama_fakultas
        $prodi = $this->prodiModel->select('program_studi.*, fakultas.nama_fakultas')
                                  ->join('fakultas', 'fakultas.id = program_studi.fakultas_id')
                                  ->findAll();

        $data = [
            'title' => 'Data Program Studi | siAkad ITKA',
            'prodi' => $prodi
        ];

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

    public function create()
    {
        $data = [
            'title' => 'Tambah Data Program Studi | siAkad ITKA',
            'validation' => \Config\Services::validation(),
            'fakultas' => $this->fakultasModel->findAll()
        ];

        return view('prodi/form', $data);
    }

    public function store()
    {
        // Validasi input
        if (!$this->validate([
            'fakultas_id' => [
                'rules' => 'required',
                'errors' => ['required' => 'Fakultas harus dipilih.']
            ],
            'kode_prodi' => [
                'rules' => 'required|is_unique[program_studi.kode_prodi]',
                'errors' => [
                    'required' => 'Kode Program Studi harus diisi.',
                    'is_unique' => 'Kode Program Studi sudah terdaftar.'
                ]
            ],
            'nama_prodi' => [
                'rules' => 'required',
                'errors' => ['required' => 'Nama Program Studi harus diisi.']
            ],
            'jenjang' => [
                'rules' => 'required',
                'errors' => ['required' => 'Jenjang harus diisi.']
            ]
        ])) {
            return redirect()->to('/prodi/create')->withInput();
        }

        $this->prodiModel->save([
            'fakultas_id' => $this->request->getPost('fakultas_id'),
            'kode_prodi'  => $this->request->getPost('kode_prodi'),
            'nama_prodi'  => $this->request->getPost('nama_prodi'),
            'jenjang'     => $this->request->getPost('jenjang'),
            'akreditasi'  => $this->request->getPost('akreditasi')
        ]);

        session()->setFlashdata('success', 'Data Program Studi berhasil ditambahkan.');
        return redirect()->to('/prodi');
    }

    public function edit(string $id)
    {
        $data = [
            'title' => 'Edit Data Program Studi | siAkad ITKA',
            'validation' => \Config\Services::validation(),
            'prodi' => $this->prodiModel->find($id),
            'fakultas' => $this->fakultasModel->findAll()
        ];

        if (empty($data['prodi'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Program Studi dengan ID ' . $id . ' tidak ditemukan');
        }

        return view('prodi/form', $data);
    }

    public function update(string $id)
    {
        $prodiLama = $this->prodiModel->find($id);
        $rule_kode = ($prodiLama['kode_prodi'] == $this->request->getPost('kode_prodi')) 
                     ? 'required' 
                     : 'required|is_unique[program_studi.kode_prodi]';

        if (!$this->validate([
            'fakultas_id' => [
                'rules' => 'required',
                'errors' => ['required' => 'Fakultas harus dipilih.']
            ],
            'kode_prodi' => [
                'rules' => $rule_kode,
                'errors' => [
                    'required' => 'Kode Program Studi harus diisi.',
                    'is_unique' => 'Kode Program Studi sudah terdaftar.'
                ]
            ],
            'nama_prodi' => [
                'rules' => 'required',
                'errors' => ['required' => 'Nama Program Studi harus diisi.']
            ],
            'jenjang' => [
                'rules' => 'required',
                'errors' => ['required' => 'Jenjang harus diisi.']
            ]
        ])) {
            return redirect()->to('/prodi/edit/' . $id)->withInput();
        }

        $this->prodiModel->save([
            'id'          => $id,
            'fakultas_id' => $this->request->getPost('fakultas_id'),
            'kode_prodi'  => $this->request->getPost('kode_prodi'),
            'nama_prodi'  => $this->request->getPost('nama_prodi'),
            'jenjang'     => $this->request->getPost('jenjang'),
            'akreditasi'  => $this->request->getPost('akreditasi')
        ]);

        session()->setFlashdata('success', 'Data Program Studi berhasil diubah.');
        return redirect()->to('/prodi');
    }

    public function delete(string $id)
    {
        $this->prodiModel->delete($id);
        session()->setFlashdata('success', 'Data Program Studi berhasil dihapus.');
        return redirect()->to('/prodi');
    }

    public function syncPddikti()
    {
        $neoFeeder = new \App\Services\NeoFeederService();
        $response = $neoFeeder->request('GetProdi');

        if (isset($response['error_code']) && $response['error_code'] == 0 && !empty($response['data'])) {
            $count = 0;
            
            // Get default Fakultas (first one)
            $defaultFakultas = $this->fakultasModel->first();
            $fakultasId = $defaultFakultas ? $defaultFakultas['id'] : null;

            foreach ($response['data'] as $prodiPddikti) {
                // Cari apakah prodi sudah ada berdasarkan id_prodi_pddikti
                $existing = $this->prodiModel->where('id_prodi_pddikti', $prodiPddikti['id_prodi'])->first();

                if (!$existing) {
                    $this->prodiModel->save([
                        'fakultas_id'      => $fakultasId,
                        'kode_prodi'       => $prodiPddikti['kode_program_studi'],
                        'nama_prodi'       => $prodiPddikti['nama_program_studi'],
                        'jenjang'          => $prodiPddikti['nama_jenjang_pendidikan'],
                        'id_prodi_pddikti' => $prodiPddikti['id_prodi']
                    ]);
                    $count++;
                } else {
                    // Update if exists to ensure data is synced
                    $this->prodiModel->save([
                        'id'               => $existing['id'],
                        'kode_prodi'       => $prodiPddikti['kode_program_studi'],
                        'nama_prodi'       => $prodiPddikti['nama_program_studi'],
                        'jenjang'          => $prodiPddikti['nama_jenjang_pendidikan'],
                        'id_prodi_pddikti' => $prodiPddikti['id_prodi']
                    ]);
                }
            }

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

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