<?php

namespace BuyMeCoffee\Classes;

use BuyMeCoffee\Classes\View;
use BuyMeCoffee\Classes\Vite;
use BuyMeCoffee\Helpers\ArrayHelper;
use BuyMeCoffee\Models\Buttons;
use BuyMeCoffee\Models\Supporters;

if (!defined('ABSPATH')) exit; // Exit if accessed directly

class DemoPage
{
    public function register()
    {
        $this->handleExteriorPages();
    }

    public function loadTemplateStyles()
    {
        Vite::enqueueStyle('buymecoffee_template_style', 'scss/public/BasicTemplate.scss', array(), BUYMECOFFEE_VERSION);
    }

    public function renderFormOnly($args = [])
    {
        $this->loadTemplateStyles();
        $btnController = new Buttons();
        $template = $btnController->getButton();
        $args = apply_filters('buymecoffee_form_render_args', $args);
        ob_start();
        include BUYMECOFFEE_DIR . 'includes/views/templates/FormShortCode.php';
        return ob_get_clean();
    }

    public function handleExteriorPages()
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Route detection only
        if (!isset($_GET['share_coffee'])) {
            return;
        }

        if (defined('CT_VERSION')) {
            // Oxygen page compatibility for the standalone Buy Me Coffee page only.
            remove_action('wp_head', 'oxy_print_cached_css', 999999);
        }

        $this->renderBasicTemplate([], 'page');
    }

    public function loadModalContent()
    {
        wp_enqueue_style('dashicons');
        $this->loadTemplateStyles();
        $btnController = new Buttons();
        $template = $btnController->getButton();

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo View::make('templates.FormShortCode', ['template' => $template, 'type' => '',]);
    }

    public function renderBasicTemplate($args = [], $type = '')
    {
        if (is_page() || $type === 'page') {
            wp_enqueue_style('dashicons');
            $this->loadDefaultPageTemplate();
            $this->loadTemplateStyles();
            $this->loadCustomizer();

            $btnController = new Buttons();
            $template = $btnController->getButton();

            $quote = ArrayHelper::get($template, 'advanced.quote', false);
            $profileImage = ArrayHelper::get($template, 'advanced.image');
            if ($profileImage == '') {
                $profileImage = Vite::staticPath() . 'images/profile.png';
            }

            $bannerImage = ArrayHelper::get($template, 'advanced.banner_image', '');
            if ($bannerImage === '' || $bannerImage === null) {
                $bannerImage = Vite::staticPath() . 'images/banner-default.jpg';
            } elseif ($bannerImage === 'none') {
                $bannerImage = '';
            }

            //escaped in template, ignoring phpcs here now
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo View::make('templates.BasicTemplate', [
                'template' => $this->sanitizeTemplate($template), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                'type' => 'button',
                'quote' => esc_html($quote),
                'show_title' => esc_html(ArrayHelper::get($template, 'formTitle') == 'yes'),
                'profile_image' => esc_url($profileImage),
                'banner_image' => esc_url($bannerImage),
                'name' => esc_html(ArrayHelper::get($template, 'yourName')),
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                'args' => apply_filters('buymecoffee_form_render_args', static::getSanitizedArguments($args)),
            ]);
            exit();
        }
    }

    public function loadCustomizer()
    {
        if (!current_user_can('manage_options')) return;
        wp_enqueue_media();
        Vite::enqueueScript('buymecoffee_customizer', 'js/customizer.js', array('jquery'), BUYMECOFFEE_VERSION, true);
        Vite::enqueueStyle('buymecoffee_customizer_style', 'scss/admin/customizer.scss', array(), BUYMECOFFEE_VERSION);
        wp_localize_script('buymecoffee_customizer', 'buymecoffee_customizer_data', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'buymecoffee_nonce' => wp_create_nonce('buymecoffee_nonce'),
            'is_admin' => true,
        ));
    }

    public function loadDefaultPageTemplate()
    {
        add_filter('template_include', function ($original) {
            return locate_template(array('page.php', 'single.php', 'index.php'));
        }, 999);
    }

    private function sanitizeTemplate($template)
    {
        if (!is_array($template)) {
            return [];
        }

        // Define sanitization rules for root level fields
        $rootFields = [
            'yourName' => ['type' => 'text', 'default' => ''],
            'buttonText' => ['type' => 'text', 'default' => ''],
            'enableMessage' => ['type' => 'text', 'default' => 'no'],
            'formTitle' => ['type' => 'text', 'default' => 'no'],
            'enableName' => ['type' => 'text', 'default' => 'no'],
            'enableEmail' => ['type' => 'text', 'default' => 'no'],
            'defaultAmount' => ['type' => 'int', 'default' => 5],
            'custom_coffee' => ['type' => 'int', 'default' => 5],
            'openMode' => ['type' => 'text', 'default' => 'page'],
            'currency' => ['type' => 'text', 'default' => 'USD'],
        ];

        // Define sanitization rules for advanced fields
        $advancedFields = [
            'image' => ['type' => 'url', 'default' => ''],
            'banner_image' => ['type' => 'text', 'default' => ''],
            'banner_position_x' => ['type' => 'float', 'default' => 50],
            'banner_position_y' => ['type' => 'float', 'default' => 50],
            'banner_zoom' => ['type' => 'float', 'default' => 1],
            'enable' => ['type' => 'text', 'default' => 'yes'],
            'bgColor' => ['type' => 'text', 'default' => ''],
            'color' => ['type' => 'text', 'default' => ''],
            'formShadow' => ['type' => 'text', 'default' => 'no'],
            'minWidth' => ['type' => 'int', 'default' => 180],
            'textAlign' => ['type' => 'text', 'default' => 'center'],
            'minHeight' => ['type' => 'int', 'default' => 43],
            'fontSize' => ['type' => 'int', 'default' => 21],
            'radius' => ['type' => 'int', 'default' => 4],
            'button_style' => ['type' => 'text', 'default' => ''],
            'bg_style' => ['type' => 'text', 'default' => ''],
            'border_style' => ['type' => 'text', 'default' => ''],
            'quote' => ['type' => 'text', 'default' => ''],
        ];

        $sanitized = [];

        // Sanitize root level fields
        foreach ($rootFields as $field => $config) {
            $sanitized[$field] = $this->sanitizeField($template, $field, $config['type'], $config['default']);
        }

        // Sanitize advanced fields
        if (isset($template['advanced']) && is_array($template['advanced'])) {
            $sanitized['advanced'] = [];
            foreach ($advancedFields as $field => $config) {
                $sanitized['advanced'][$field] = $this->sanitizeField($template['advanced'], $field, $config['type'], $config['default']);
            }
        } else {
            $sanitized['advanced'] = [];
        }

        // Preserve any other fields that might exist
        foreach ($template as $key => $value) {
            if (!isset($sanitized[$key])) {
                if (is_array($value)) {
                    $sanitized[$key] = array_map('sanitize_text_field', $value);
                } else {
                    $sanitized[$key] = sanitize_text_field($value);
                }
            }
        }

        return $sanitized;
    }

    private function sanitizeField($data, $field, $type, $default)
    {
        if (!isset($data[$field])) {
            return $default;
        }

        switch ($type) {
            case 'int':
                return absint($data[$field]);
            case 'float':
                return (float) $data[$field];
            case 'url':
                return esc_url_raw($data[$field]);
            case 'text':
            default:
                return sanitize_text_field($data[$field]);
        }
    }

    public function renderSupportersWall($atts = [])
    {
        $atts = shortcode_atts([
            'limit'       => '',
            'show_amount' => '',
        ], $atts, 'buymecoffee_supporters');

        $savedSettings = get_option('buymecoffee_supporters_display_settings', []);
        $settings = wp_parse_args($savedSettings, [
            'show_name'      => 'yes',
            'show_avatar'    => 'yes',
            'show_amount'    => 'no',
            'show_message'   => 'yes',
            'max_supporters' => 20,
        ]);

        // Shortcode attributes override saved settings
        if ($atts['limit'] !== '') {
            $settings['max_supporters'] = max(1, min(100, absint($atts['limit'])));
        }
        if ($atts['show_amount'] !== '') {
            $settings['show_amount'] = $atts['show_amount'] === 'yes' ? 'yes' : 'no';
        }

        Vite::enqueueStyle('buymecoffee_public_style', 'scss/public/public-style.scss', [], BUYMECOFFEE_VERSION);

        $supporters = (new Supporters())->getPublicSupporters($settings);

        ob_start();
        include BUYMECOFFEE_DIR . 'includes/views/templates/SupportersWall.php';
        return ob_get_clean();
    }

    public static function getSanitizedArguments($args): array
    {
        if (!is_array($args)) {
            $args = [];
        }

        foreach ($args as $key => $value) {
            $args[$key] = esc_html($value);
        }
        return $args;
    }
}
