<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

if (!function_exists('opt')) {
    function opt($key, $default = null) {
        return function_exists('get_option') ? get_option($key) : $default;
    }
}

if (!function_exists('myinv_env')) {
    /**
     * Resolve MyInvois env, endpoints, credentials, and issuer profile.
     * - PRODUCTION: reads all values from Perfex options (get_option).
     * - STAGING   : uses hard-coded profile (as requested) + fixed staging endpoints/creds.
     *
     * @return array { mode, apiBase, envBaseUrl, submitUrl, tokenUrl, clientId, clientSecret, profile }
     */
    function myinv_env() {
        // Mode
        $mode = strtolower((string) opt('lhdn_mode', 'staging')) === 'production' ? 'production' : 'staging';

        if ($mode === 'production') {
            // --- PRODUCTION ---
            $apiBase    = 'https://api.myinvois.hasil.gov.my';
            $envBaseUrl = 'https://myinvois.hasil.gov.my/';

            $clientId     = (string) opt('lhdn_client_id', '');
            $clientSecret = (string) opt('lhdn_client_s', '');

            // Build issuer profile from Perfex options
            $profile = [
                'sst_no'           => opt('company_vat', ''),
                'tin'              => opt('lhdn_tin', ''),
                'id_type'          => opt('lhdn_id_type', ''),              // BRN | NRIC | PASSPORT
                'id_no'            => opt('lhdn_id_no', ''),
                'company_name'     => opt('invoice_company_name', ''),
                'company_phone'    => opt('invoice_company_phonenumber', ''),
                'company_email'    => opt('lhdn_company_email', ''),
                'msic_code'        => opt('lhdn_msic', ''),
                'company_address'  => opt('invoice_company_address', ''),
                'company_postcode' => opt('invoice_company_postal_code', ''),
                'company_city'     => opt('invoice_company_city', ''),
                'company_country'  => opt('invoice_company_country_code', ''), // ISO-3 e.g. MYS
            ];
        } else {
            // --- STAGING (hard-coded) ---
            $apiBase    = 'https://preprod-api.myinvois.hasil.gov.my';
            $envBaseUrl = 'https://preprod.myinvois.hasil.gov.my/';

            // Staging credentials (hard-code here as well)
            $clientId     = '3c6c52e7-e251-4d27-8aad-f2144ccc2592';
            $clientSecret = '8449b500-b6ac-4c40-9a46-5c661c61389b';

            // Your requested hard-coded staging profile
            $profile = [
                'sst_no'           => '',
                'tin'              => 'IG11852097000',
                'id_type'          => 'NRIC',               // BRN | NRIC | PASSPORT
                'id_no'            => '820206086289',
                'company_name'     => 'Staging Company Sdn Bhd',
                'company_phone'    => '01121156329',
                'company_email'    => 'staging@example.com',
                'msic_code'        => '85302',
                'company_address'  => 'Jalan Tun Ismail',
                'company_postcode' => '50480',
                'company_city'     => 'Kuala Lumpur',
                'company_country'  => 'MYS',
            ];
        }

        return [
            'mode'         => $mode,
            'apiBase'      => $apiBase,
            'envBaseUrl'   => $envBaseUrl,
            'submitUrl'    => rtrim($apiBase, '/') . '/api/v1.0/documentsubmissions/',
            'tokenUrl'     => rtrim($apiBase, '/') . '/connect/token',
            'clientId'     => $clientId,
            'clientSecret' => $clientSecret,
            'profile'      => $profile,
        ];
    }
}

if (!function_exists('myinv_submit_url')) {
    function myinv_submit_url() { return myinv_env()['submitUrl']; }
}
if (!function_exists('myinv_token_url')) {
    function myinv_token_url() { return myinv_env()['tokenUrl']; }
}
if (!function_exists('myinv_document_raw_url')) {
    function myinv_document_raw_url($uuid) { return rtrim(myinv_env()['apiBase'], '/') . "/api/v1.0/documents/{$uuid}/raw"; }
}
if (!function_exists('myinv_document_state_url')) {
    function myinv_document_state_url($uuid) { return rtrim(myinv_env()['apiBase'], '/') . "/api/v1.0/documents/state/{$uuid}/state"; }
}
if (!function_exists('myinv_credentials')) {
    function myinv_credentials() { $e = myinv_env(); return ['clientId' => $e['clientId'], 'clientSecret' => $e['clientSecret']]; }
}
if (!function_exists('myinv_portal_base')) {
    function myinv_portal_base() { return myinv_env()['envBaseUrl']; }
}
if (!function_exists('myinv_profile')) {
    function myinv_profile() { return myinv_env()['profile']; }
}
if (!function_exists('myinv_profile_get')) {
    function myinv_profile_get($key, $default = null) {
        $p = myinv_profile();
        return array_key_exists($key, $p) ? $p[$key] : $default;
    }
}
if (!function_exists('myinv_mode')) {
    function myinv_mode() { return myinv_env()['mode']; }
}
