<?php

namespace App\Services;

use App\Models\PengaturanModel;
use CodeIgniter\HTTP\CURLRequest;

class NeoFeederService
{
    protected CURLRequest $client;
    protected string $url = '';
    protected string $username = '';
    protected string $password = '';
    protected PengaturanModel $pengaturanModel;

    public function __construct()
    {
        $this->pengaturanModel = new PengaturanModel();
        
        // Ambil pengaturan dari database
        $this->url      = $this->pengaturanModel->getValue('pddikti_url', '');
        $this->username = $this->pengaturanModel->getValue('pddikti_username', '');
        $this->password = $this->pengaturanModel->getValue('pddikti_password', '');

        $this->client = \Config\Services::curlrequest([
            'baseURI' => $this->url,
            'timeout' => 30,
            'verify'  => false, // Disable SSL verification just in case using self-signed cert
        ]);
    }

    /**
     * Mengecek apakah konfigurasi dasar sudah diisi
     */
    public function isConfigured()
    {
        return !empty($this->url) && !empty($this->username) && !empty($this->password);
    }

    /**
     * Mendapatkan Token dari WS Neo Feeder
     */
    public function getToken()
    {
        // Cek token di session terlebih dahulu
        if (session()->has('pddikti_token')) {
            return session()->get('pddikti_token');
        }

        if (!$this->isConfigured()) {
            return false;
        }

        try {
            $response = $this->client->post('', [
                'json' => [
                    'act'      => 'GetToken',
                    'username' => $this->username,
                    'password' => $this->password
                ]
            ]);

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

            if (isset($result['error_code']) && $result['error_code'] == 0 && isset($result['data']['token'])) {
                $token = $result['data']['token'];
                // Simpan token di session sementara
                session()->set('pddikti_token', $token);
                return $token;
            }

            // Return the specific error from API if any
            if (isset($result['error_desc'])) {
                return 'API Error: ' . $result['error_desc'];
            }

            return false;
        } catch (\Exception $e) {
            log_message('error', 'NeoFeederService getToken Error: ' . $e->getMessage());
            return 'Exception: ' . $e->getMessage();
        }
    }

    /**
     * Melakukan request standard ke WS Neo Feeder
     * 
     * @param string $act Nama aksi (contoh: GetProfilPT, GetListMahasiswa)
     * @param array $payload Data tambahan (record, key, filter, limit, offset, order)
     */
    public function request($act, $payload = [])
    {
        $token = $this->getToken();

        // If getToken returned an error message string or false
        if (!$token || strpos($token, 'Error:') !== false || strpos($token, 'Exception:') !== false) {
            return [
                'error_code' => 999,
                'error_desc' => 'Gagal mendapatkan token. Detail: ' . ($token ?: 'Respons API tidak valid atau konfigurasi belum diset.')
            ];
        }

        $data = array_merge([
            'act'   => $act,
            'token' => $token
        ], $payload);

        try {
            $response = $this->client->post('', [
                'json' => $data
            ]);

            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            log_message('error', 'NeoFeederService request Error [' . $act . ']: ' . $e->getMessage());
            return [
                'error_code' => 500,
                'error_desc' => 'Gagal menghubungi Web Service: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Helper khusus untuk Test Koneksi (GetProfilPT)
     */
    public function testConnection()
    {
        return $this->request('GetProfilPT');
    }
}
