<?php

namespace EstatebudConnect\Controllers;

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

use EstatebudConnect\Configs\App;
use EstatebudConnect\Models\Forms;
use EstatebudConnect\Models\Settings;
use EstatebudConnect\Traits\Singleton;
use EstatebudConnect\Utilities\Color;
use EstatebudConnect\Utilities\Helper;

class Frontend
{
    use Singleton;

    private $shortcode_tags = [
        'estatebud' => 'render_shortcode',
    ];

    public function __construct()
    {
        $this->register_shortcodes();
        add_action('wp_enqueue_scripts', [$this, 'enqueue_assets']);
    }

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

    public function enqueue_assets()
    {
        $settings_data = Settings::instance()->get_data();

        $branding_color = $settings_data['branding_color'];
        $edge_style = $settings_data['edge_style'] ?? '';
        $field_style = $settings_data['field_style'] ?? '';
        $button_style = $settings_data['button_style'] ?? '';
        $custom_css = str_replace(["\r", "\n"], ' ', $settings_data['custom_css']);
        $map_provider = $settings_data['map_provider'] ?? '';

        $edge_style_conversion = App::EDGE_STYLE_CONVERSION;
        $button_style_conversion = App::BUTTON_STYLE_CONVERSION;

        $color = new Color($branding_color);

        $frontend_css = sprintf(
            ':root { --estatebud-branding-color: %s; --estatebud-branding-color-hover: %s; --estatebud-edge-radius: %spx; --estatebud-field-radius: %spx; --estatebud-button-radius: %spx; --estatebud-button-padding-x: %spx; --estatebud-button-padding-y: %spx; }',
            $branding_color,
            '#' . $color->darken(),
            $edge_style_conversion['edge_style'][$edge_style] ?? '0',
            $edge_style_conversion['field_style'][$field_style] ?? '0',
            $edge_style_conversion['button_style'][$button_style] ?? '0',
            $button_style_conversion[$button_style]['padding']['x'] ?? '0',
            $button_style_conversion[$button_style]['padding']['y'] ?? '0',
        );

        wp_enqueue_style(App::SLUG . '-choices-base', Helper::get_url('assets/third-party/choices/choices.css'), [], App::VERSION);
        wp_enqueue_style(App::SLUG . '-intltel', Helper::get_url('assets/third-party/intltelinput/intltelinput.css'), [], App::VERSION);
        wp_enqueue_style(App::SLUG . '-frontend', Helper::get_url('dist/bundle-main.css'), [App::SLUG . '-choices-base'], App::VERSION);
        wp_add_inline_style(App::SLUG . '-frontend', wp_kses($frontend_css . $custom_css, []));

        if (\EstatebudConnect\Plugin::has_build_tools()) {
            wp_enqueue_script(
                App::SLUG . '-choices',
                Helper::get_url('app/Javascript/third-party/choices/choices.js'),
                [],
                uniqid(),
            );
        } else {
            wp_enqueue_script(
                App::SLUG . '-choices',
                Helper::get_url('dist/bundle-choices.js'),
                [],
                App::VERSION,
            );
        }

        wp_enqueue_script(
            App::SLUG . '-intltel',
            Helper::get_url('assets/third-party/intltelinput/intltelinput.js'),
            [],
            App::VERSION,
        );
    }

    public function render_shortcode($raw_atts)
    {
        $atts = shortcode_atts(
            [
                'form' => '',
                'search' => '',
                'map' => 'false',
                'map_position' => 'top',
                'map_visibility' => 'false',
                'map_clustering' => 'true',
                'map_zoom_limit' => '',
                'map_default_state' => 'off',
                'sorting' => 'published',
                'results_per_page' => '12',
                'widget_mode' => 'false',
                'slider' => 'false',
                'slider_duration' => '',
                'slider_infinite' => 'true',
                'slider_nav_arrows' => 'true',
                'slider_nav_dots' => 'true',
                'slider_effect' => '',
                'slider_speed' => '',
                'favorites' => '',
            ],
            $raw_atts,
            'estatebud',
        );

        $form_id = !empty($atts['form']) ? esc_html($atts['form']) : '';
        $search_id = !empty($atts['search']) ? esc_html($atts['search']) : '';
        $has_form = !empty($form_id);
        $has_search = !empty($search_id);

        $shortcode_id = uniqid();
        $output = '';

        if ($has_form) {
            $output .= Form::instance()->render_form($form_id, [
                'shortcode_id' => $shortcode_id,
                'search_id' => $search_id,
            ]);
        }

        if ($has_search) {
            $output .= Listings::instance()->render_search(
                array_merge($atts, [
                    'shortcode_id' => $shortcode_id,
                    'form_id' => $form_id,
                ])
            );
        }

        if (!$has_form && !$has_search) {
            return '<!-- estatebud: form or search attribute required -->';
        }

        $output = '<div class="estatebud-shortcode-wrapper" data-shortcode-id="' . esc_attr($shortcode_id) . '">' . $output . '</div>';
        return $output;
    }
}
