<?php

namespace EstatebudConnect\Controllers;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Plugin;
use EstatebudConnect\Configs\App;
use EstatebudConnect\Models\Settings;
use EstatebudConnect\Services\Estatebud;
use EstatebudConnect\Traits\Singleton;
use EstatebudConnect\Utilities\Helper;
use EstatebudConnect\Core\Log;
use EstatebudConnect\Core\Strings;
use EstatebudConnect\Core\Cache;

class CurrencySelector
{
    use Singleton;

    private $shortcode_tags = [
        'estatebud_currency' => 'render_currency_selector',
    ];

    public function __construct()
    {
        $this->register_shortcodes();

        add_action('wp_ajax_estatebud_change_currency', [$this, 'handle_change_currency']);
        add_action('wp_ajax_nopriv_estatebud_change_currency', [$this, 'handle_change_currency']);
    }

    private function register_shortcodes()
    {
        foreach ($this->shortcode_tags as $shortcode => $callback) {
            add_shortcode($shortcode, [$this, $callback]);
        }
    }

    private function enqueue_assets()
    {
        wp_enqueue_style(App::SLUG . '-frontend', Helper::get_url('dist/bundle-main.css'), [], App::VERSION);

        if (Plugin::has_build_tools()) {
            wp_enqueue_script(App::SLUG . '-frontend', Helper::get_url('app/Javascript/public/index.js'), [App::SLUG . '-choices'], uniqid());
        } else {
            wp_enqueue_script(App::SLUG . '-frontend', Helper::get_url('dist/bundle-main.js'), [App::SLUG . '-choices'], App::VERSION);
        }

        Strings::init_defaults('frontend');
    }

    public function render_currency_selector()
    {
        $this->enqueue_assets();

        $settings_data = Settings::instance()->get_data();

        $whois = Estatebud::instance()->cache(Cache::TTL_1H)->whois();
        $default_currency = strtoupper($whois['currency']);

        $user_session = Helper::get_user_session();
        $current_currency = strtoupper($user_session['currency'] ?? $default_currency);

        $default_option = [
            'value' => $default_currency,
            'disabled' => false,
            'selected' => $default_currency == $current_currency,
            'label' => $default_currency,
        ];

        $currencies = $settings_data['currencies'];
        $options = array_merge(
            $default_option ? [$default_option] : [],
            array_map(
                fn($currency) => [
                    'value' => strtoupper($currency),
                    'disabled' => false,
                    'selected' => strtoupper($currency) == $current_currency,
                    'label' => strtoupper($currency),
                ],
                $currencies,
            ),
        );

        ob_start();
        Helper::render_markup_from_views('Public/Form/components/currency-selector.php', [
            'variable_name' => 'currency',
            'options' => $options,
        ]);
        return ob_get_clean();
    }

    public function handle_change_currency()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $currency = strtoupper(sanitize_text_field(wp_unslash($_POST['targetCurrency'] ?? '')));

        Log::event("Currency: Setting display currency to {$currency}");

        Helper::set_user_session_data([
            'currency' => $currency,
        ]);

        $whois = Estatebud::instance()->cache(Cache::TTL_1H)->whois();

        $currency_data = Helper::get_currency_data($whois['currency'], $currency);

        if ($currency_data) {
            wp_send_json_success(
                [
                    'message' => 'Form saved',
                    'code' => 200,
                    'data' => $currency_data['exchange_rates'],
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Failed to save form',
                    'code' => 400,
                ],
                400,
            );
        }
    }
}
