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

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

    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' => 'Módulo no disponible',
            ]));
        }

        $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' => 'Escribe tu clave (Secret) para verificarla.',
            ]));
        }

        $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']) ? 'Clave vÃ¡lida' : (isset($res['message']) ? $res['message'] : 'VerificaciÃ³n fallida');

        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' => 'No hay clave guardada', '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]));
    }
}


