<?php

namespace App\Controllers;

use App\Models\PengaturanModel;
use App\Services\NeoFeederService;

class Pddikti extends BaseController
{
    protected PengaturanModel $pengaturanModel;
    protected NeoFeederService $neoFeederService;

    public function __construct()
    {
        $this->pengaturanModel = new PengaturanModel();
        $this->neoFeederService = new NeoFeederService();
    }

    public function setting()
    {
        $data = [
            'title'            => 'Pengaturan PDDIKTI | SIAKAD ITKA',
            'pddikti_url'      => $this->pengaturanModel->getValue('pddikti_url', 'http://localhost:3003/ws/live2.php'),
            'pddikti_username' => $this->pengaturanModel->getValue('pddikti_username', ''),
            'pddikti_password' => $this->pengaturanModel->getValue('pddikti_password', ''),
        ];

        return view('pddikti/setting', $data);
    }

    public function saveSetting()
    {
        $this->pengaturanModel->setValue('pddikti_url', $this->request->getPost('pddikti_url'));
        $this->pengaturanModel->setValue('pddikti_username', $this->request->getPost('pddikti_username'));
        $this->pengaturanModel->setValue('pddikti_password', $this->request->getPost('pddikti_password'));

        // Reset token session in case password changed
        session()->remove('pddikti_token');

        session()->setFlashdata('pesan', 'Pengaturan koneksi PDDIKTI berhasil disimpan.');
        return redirect()->to('/pddikti/setting');
    }

    public function testConnection()
    {
        if (!$this->neoFeederService->isConfigured()) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Konfigurasi PDDIKTI belum diisi.'
            ]);
        }

        $result = $this->neoFeederService->testConnection();

        if ($result && isset($result['error_code']) && $result['error_code'] == 0) {
            $namaPT = $result['data'][0]['nama_perguruan_tinggi'] ?? 'Unknown PT';
            return $this->response->setJSON([
                'success' => true,
                'message' => "Koneksi Berhasil! Terhubung dengan: " . $namaPT
            ]);
        } else {
            $errorMsg = $result['error_desc'] ?? 'Unknown Error';
            return $this->response->setJSON([
                'success' => false,
                'message' => "Koneksi Gagal: " . $errorMsg
            ]);
        }
    }

    public function debugKurikulum()
    {
        $resKurikulum = $this->neoFeederService->request('GetKurikulum', ['limit' => 1]);
        $resMK = $this->neoFeederService->request('GetListMataKuliah', ['limit' => 1]);
        
        return $this->response->setJSON([
            'kurikulum' => $resKurikulum['data'][0] ?? null,
            'mata_kuliah' => $resMK['data'][0] ?? null
        ]);
    }
}
