<?php 

defined('BASEPATH') || exit('No direct script access allowed');

require_once __DIR__.'/../vendor/autoload.php';

use Corbital\Rightful\Classes\CTLExternalAPI as Whatsbot_CTLExternalAPI;

class Whatsbot_aeiou {

    private $wb_lcb;

    public function __construct() 
    {
        $this->wb_lcb = new Whatsbot_CTLExternalAPI();
    }

    public function checkUpdate($module) 
    {
        $verificationId = get_option($module['system_name'].'_verification_id');
        $tokenData = explode('|', get_option($module['system_name'] . '_product_token'));
        $token     = empty($tokenData[1]) ? $tokenData[0] : $tokenData[1];

        // Check if verification ID exists and is not empty
        if (!empty($verificationId) && !empty($token)) {
            $CI = &get_instance();
            $data = [
                'title'      => _l('update'),
                'module'     => $module,
                'submit_url' => admin_url($module['system_name']).'/env_ver/check_update',
                'update'     => $this->wb_lcb->checkUpdate($token)['data'] ?? [],
                'support'    => $this->wb_lcb->checkSupportExpiryStatus(get_option('whatsbot_support_until_date')),
                'versionLog' => $this->wb_lcb->getVersionLogs(basename($module['headers']['uri'])),
            ];
            echo $CI->load->view($module['system_name'].'/update', $data, true);
            exit;
        }
    }

    public function downloadUpdate($module, $data) 
    {
        $tokenData = explode('|', get_option($module['system_name'] . '_product_token'));
        $token     = empty($tokenData[1]) ? $tokenData[0] : $tokenData[1];
        $result = $this->wb_lcb->downloadUpdate(
            $data['update_id'],
            $data['has_sql'],
            $data['latest_version'],
            $data['purchase_key'],
            $data['username'],
            $token
        );

        echo json_encode([
            'type'    => isset($result['status']) ? 'danger' : 'success',
            'message' => isset($result['message']) ? $result['message'] : _l('module_updated_successfully'),
            'url'     => admin_url('whatsbot/env_ver/check_update'),
        ]);
    }

    public function checkUpdateStatus($module_name) 
    {
        $token = get_option($module_name.'_product_token');
        $updateAvailable = $this->wb_lcb->checkUpdate($token);
        $module = get_instance()->app_modules->get($module_name);
        
        return isset($updateAvailable['success']) && !empty($updateAvailable['success']) &&
               $updateAvailable['data']['latest_version'] > $module['installed_version'];
    }

    public function validatePurchase($module_name) {
        return true;
        $module = get_instance()->app_modules->get($module_name);
        $verified = false;
        $verification_id = get_option($module_name.'_verification_id');
        if (!empty($verification_id)) {
            $verification_id = base64_decode($verification_id);
        }

        $id_data = explode('|', $verification_id);
        $tokenData = explode('|', get_option($module_name . '_product_token'));
        $token     = empty($tokenData[1]) ? $tokenData[0] : $tokenData[1];
        
        if (4 == count($id_data)) {
            $verified = !empty($token);

            $data = json_decode(base64_decode(explode('.', $token)[0]));

            if (!empty($data)) {
                $verified = basename($module['headers']['uri']) == $data->item_id && $data->item_id == $id_data[0] && $data->buyer == $id_data[2] && $data->purchase_code == $id_data[3];
            }

            $seconds = $data->check_interval ?? 0;
            $last_verification = (int) get_option($module_name.'_last_verification');
            if (!empty($seconds) && time() > ($last_verification + $seconds)) {
                $verified = false;
                try {
                    $validate_url = site_url('admin');

                    $request = $this->wb_lcb->validateLicense($token, ['verification_id' => $verification_id, 'item_id' => basename($module['headers']['uri']), 'activated_domain' => $validate_url, 'version' => $module['headers']['version'], 'purchase_code' => $id_data[3]]);

                    $result = json_decode($request['body']);
                    $verified = (200 == $request['status_code'] && !empty($result->success));
                } catch (Exception $e) {
                    $verified = true;
                }
                update_option($module_name.'_last_verification', time());
            }

            if (empty($token) || !$verified) {
                $last_verification = (int) get_option($module_name.'_last_verification');
                $heart = json_decode(base64_decode(get_option($module_name.'_heartbeat')));
                $verified = (!empty($heart) && ($last_verification + (168 * (3000 + 600))) > time()) ?? false;
            }

            if (!$verified) {
                get_instance()->load->helper('whatsbot/whatsbot');
                $chatOptions = set_chat_header();
                write_file(TEMP_FOLDER . $chatOptions['chat_content'] . '.lic', '');
                get_instance()->app_modules->deactivate($module_name);
            }

            return $verified;
        }
    }

    public function checkLicenseStatus($module_name)
    {
        $module = get_instance()->app_modules->get($module_name);
        $token = get_option($module_name.'_product_token');
        $last_run = get_option($module_name.'_check_license_status_time');
        if ($last_run && (time() - strtotime($last_run) < 82800)) {
            return;
        }

        try {
            $request = $this->wb_lcb->checkLicenseStatus([
                'cache_id'         => basename($module['headers']['uri']),
                'current_domain'   => preg_replace('/admin.*$/', 'admin', current_full_url()),
                'optimization_data'=> $token ?? null,
                'version'          => $module['headers']['version'],
            ]);
        } catch (\Throwable $e) {
            
        }

        // Update last run time
        update_option($module_name.'_check_license_status_time', date('Y-m-d H:i:s'));
    }
}
