<?php
if (!defined('_PS_VERSION_')) { exit; }

class AdminWhatsboostAjaxController extends ModuleAdminController
{
    public function __construct()
    {
        parent::__construct();
        $this->ajax = true;
    }

    protected function isEN()
    {
        try {
            $ctx = Context::getContext();
            if (isset($ctx->language) && isset($ctx->language->iso_code)) {
                $iso = Tools::strtolower((string)$ctx->language->iso_code);
                return Tools::substr($iso, 0, 2) === 'en';
            }
        } catch (\Throwable $e) {}
        return false;
    }

    protected function tr($key)
    {
        $en = $this->isEN();
        $map = [
            'module_unavailable' => [
                'es' => 'Módulo no disponible',
                'en' => 'Module not available',
            ],
            'enter_secret' => [
                'es' => 'Escribe tu clave (Secret) para verificarla.',
                'en' => 'Enter your key (Secret) to verify it.',
            ],
            'valid_key' => [
                'es' => 'Clave válida',
                'en' => 'Valid key',
            ],
            'verify_failed' => [
                'es' => 'Verificación fallida',
                'en' => 'Verification failed',
            ],
            'no_key_saved' => [
                'es' => 'No hay clave guardada',
                'en' => 'No key saved',
            ],
            'save_ok' => [
                'es' => 'Guardado: usaremos este número para enviar WhatsApps.',
                'en' => 'Saved: we will use this number to send WhatsApps.',
            ],
            'save_fail' => [
                'es' => 'No se pudo guardar la selección.',
                'en' => 'Could not save the selection.',
            ],
            'missing_unique' => [
                'es' => 'Falta el identificador único de la cuenta.',
                'en' => 'Missing account unique identifier.',
            ],
        ];
        if (isset($map[$key])) {
            return $en ? $map[$key]['en'] : $map[$key]['es'];
        }
        return $key;
    }

    public function ajaxProcessVerify()
    {
        header('Content-Type: application/json; charset=utf-8');

        $module = Module::getInstanceByName('whatsboost');
        if (!$module || !method_exists($module, 'verifySecret')) {
            die(json_encode([
                'ok' => false,
                'message' => $this->tr('module_unavailable'),
            ]));
        }

        $secret = (string)Tools::getValue('secret', '');
        $confirm = (int)Tools::getValue('confirm_overwrite') ? 1 : 0;
        $endpoint = (string)Configuration::get('WHATSBOOST_VERIFY_ENDPOINT');
        $current = (string)Configuration::get('WHATSBOOST_SECRET');

        if ($secret === '') {
            die(json_encode([
                'ok' => false,
                'message' => $this->tr('enter_secret'),
            ]));
        }

        $res = $module->verifySecret($secret, $endpoint);
        $saved = false;
        $needConfirm = false;

        if ($current === '') {
            if (!empty($res['ok'])) {
                Configuration::updateValue('WHATSBOOST_SECRET', $secret);
                Configuration::updateValue('WHATSBOOST_VERIFIED', 1);
                if (method_exists($module, 'fetchAccounts')) {
                    $acc = $module->fetchAccounts($secret);
                    if (!empty($acc['unique'])) {
                        Configuration::updateValue('WHATSBOOST_UNIQUE', $acc['unique']);
                        Configuration::updateValue('WHATSBOOST_NEEDS_UNIQUE', 0);
                    } else {
                        Configuration::updateValue('WHATSBOOST_UNIQUE', '');
                        Configuration::updateValue('WHATSBOOST_NEEDS_UNIQUE', 1);
                    }
                }
                $saved = true;
            } else {
                Configuration::updateValue('WHATSBOOST_VERIFIED', 0);
            }
        } else {
            if ($secret !== $current) {
                if ($confirm === 1) {
                    Configuration::updateValue('WHATSBOOST_SECRET', $secret);
                    Configuration::updateValue('WHATSBOOST_VERIFIED', !empty($res['ok']) ? 1 : 0);
                    if (!empty($res['ok']) && method_exists($module, 'fetchAccounts')) {
                        $acc = $module->fetchAccounts($secret);
                        if (!empty($acc['unique'])) {
                            Configuration::updateValue('WHATSBOOST_UNIQUE', $acc['unique']);
                            Configuration::updateValue('WHATSBOOST_NEEDS_UNIQUE', 0);
                        } else {
                            Configuration::updateValue('WHATSBOOST_UNIQUE', '');
                            Configuration::updateValue('WHATSBOOST_NEEDS_UNIQUE', 1);
                        }
                    }
                    $saved = true;
                } else {
                    $needConfirm = true;
                }
            } else {
                Configuration::updateValue('WHATSBOOST_VERIFIED', !empty($res['ok']) ? 1 : 0);
                if (!empty($res['ok']) && method_exists($module, 'fetchAccounts')) {
                    $acc = $module->fetchAccounts($secret);
                    if (!empty($acc['unique'])) {
                        Configuration::updateValue('WHATSBOOST_UNIQUE', $acc['unique']);
                        Configuration::updateValue('WHATSBOOST_NEEDS_UNIQUE', 0);
                    } else {
                        Configuration::updateValue('WHATSBOOST_UNIQUE', '');
                        Configuration::updateValue('WHATSBOOST_NEEDS_UNIQUE', 1);
                    }
                }
            }
        }

        $message = !empty($res['ok']) ? $this->tr('valid_key') : (isset($res['message']) ? $res['message'] : $this->tr('verify_failed'));

        die(json_encode([
            'ok' => (bool)!empty($res['ok']),
            'saved' => $saved,
            'need_confirm' => $needConfirm,
            'message' => $message,
            'unique' => (string)Configuration::get('WHATSBOOST_UNIQUE'),
            'needs_unique' => (int)Configuration::get('WHATSBOOST_NEEDS_UNIQUE'),
        ]));
    }

    public function ajaxProcessAccounts()
    {
        header('Content-Type: application/json; charset=utf-8');
        $secret = (string)Configuration::get('WHATSBOOST_SECRET');
        if ($secret === '') {
            die(json_encode(['ok' => false, 'message' => $this->tr('no_key_saved'), 'accounts' => []]));
        }

        $url = 'https://whatsboost.net/api/get/wa.accounts?secret=' . urlencode($secret) . '&limit=10&page=1';
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => 7,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 3,
            CURLOPT_HTTPHEADER => [
                'Accept: application/json',
                'User-Agent: PrestaShop-WhatsBoost/' . Module::getInstanceByName('whatsboost')->version,
            ],
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
        ]);
        $body = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ((int)$code !== 200) {
            die(json_encode(['ok' => false, 'message' => 'HTTP ' . (int)$code, 'accounts' => []]));
        }

        $decoded = json_decode((string)$body, true);
        $accounts = [];
        if (is_array($decoded) && isset($decoded['data'])) {
            $d = $decoded['data'];
            if (isset($d['unique'])) {
                $accounts[] = [
                    'id' => isset($d['id']) ? (int)$d['id'] : null,
                    'phone' => isset($d['phone']) ? (string)$d['phone'] : '',
                    'unique' => isset($d['unique']) ? (string)$d['unique'] : '',
                    'status' => isset($d['status']) ? (string)$d['status'] : '',
                ];
            } elseif (is_array($d)) {
                foreach ($d as $item) {
                    if (!is_array($item)) continue;
                    $accounts[] = [
                        'id' => isset($item['id']) ? (int)$item['id'] : null,
                        'phone' => isset($item['phone']) ? (string)$item['phone'] : '',
                        'unique' => isset($item['unique']) ? (string)$item['unique'] : '',
                        'status' => isset($item['status']) ? (string)$item['status'] : '',
                    ];
                }
            }
        }

        die(json_encode(['ok' => true, 'accounts' => $accounts]));
    }

    public function ajaxProcessSaveUnique()
    {
        header('Content-Type: application/json; charset=utf-8');
        try {
            $unique = (string)Tools::getValue('unique', '');
            $accountId = (int)Tools::getValue('account_id', 0);
            $phone = (string)Tools::getValue('phone', '');

            if ($unique === '') {
                die(json_encode(['ok' => false, 'message' => $this->tr('missing_unique')]));
            }

            // Persist both for compatibility
            Configuration::updateValue('WHATSBOOST_UNIQUE', $unique);
            Configuration::updateValue('WHATSBOOST_NEEDS_UNIQUE', 0);
            if ($accountId > 0) {
                Configuration::updateValue('WHATSBOOST_ACCOUNT_ID', (int)$accountId);
            }

            $msg = $this->tr('save_ok');
            if ($phone !== '') {
                $msg .= ' ' . sprintf('( %s )', $phone);
            }

            die(json_encode([
                'ok' => true,
                'message' => $msg,
                'unique' => $unique,
                'account_id' => $accountId,
            ]));
        } catch (\Throwable $e) {
            die(json_encode(['ok' => false, 'message' => $this->tr('save_fail')]));
        }
    }

    public function ajaxProcessStatus()
    {
        header('Content-Type: application/json; charset=utf-8');
        try {
            $secret = (string)Configuration::get('WHATSBOOST_SECRET');
            $verified = (int)Configuration::get('WHATSBOOST_VERIFIED') === 1;
            $unique = (string)Configuration::get('WHATSBOOST_UNIQUE');
            $needsUnique = (int)Configuration::get('WHATSBOOST_NEEDS_UNIQUE') === 1;

            $show_key = (!$verified) || ($secret === '');
            $show_unique = ($verified && ($needsUnique || $unique === ''));

            die(json_encode([
                'ok' => true,
                'show_key' => (bool)$show_key,
                'show_unique' => (bool)$show_unique,
            ]));
        } catch (\Throwable $e) {
            die(json_encode(['ok' => false]));
        }
    }
}
