<?php

namespace BuyMeCoffee\Builder;

use BuyMeCoffee\Classes\Vite;
use BuyMeCoffee\Controllers\PaymentHandler;
use BuyMeCoffee\Helpers\BuilderHelper;
use BuyMeCoffee\Models\Buttons;
use BuyMeCoffee\Helpers\ArrayHelper as Arr;
use BuyMeCoffee\Classes\DemoPage;
use BuyMeCoffee\Helpers\PaymentHelper;

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

class Render
{

    public function render($args = [])
    {
        $template = (new Buttons())->getButton();

        $buttonText = Arr::get($template, 'buttonText');
        $bgColor = esc_attr(Arr::get($template, 'advanced.bgColor', '#fad400'));
        $color = esc_attr(Arr::get($template, 'advanced.color', '#000000'));
        $minWidth = esc_attr(Arr::get($template, 'advanced.minWidth'));
        $fontSize = esc_attr(Arr::get($template, 'advanced.fontSize'));
        $radius = esc_attr(Arr::get($template, 'advanced.radius', '5'));

        $paymentPageUrl = site_url('?share_coffee');
        $openMode = Arr::get($template, 'openMode');

        $styling = "<style>.wpm-buymecoffee-container .wpm-buymecoffee-button{
            outline: none;
            box-shadow: none;
            padding: 10px 23px;
            line-height: 0px;
            background-color: $bgColor;
            color: $color;
            min-width: {$minWidth}px;
            font-size: {$fontSize}px;
            border-radius: {$radius}px;
            cursor: pointer;
            text-decoration: none;
        }
        button.wpm-buymecoffee-button {
            height: 50px;
        }
        .wpm-buymecoffee-button:hover {
            box-shadow: 4px 3px 6px 2px #ccc;
        }
        </style>";

        ob_start();
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo wp_kses($styling, ['style' => []]);
        ?>
        <div class="wpm-buymecoffee-container">
            <!--  The Modal button -->
            <?php
            if (sanitize_text_field($openMode) === 'modal') {
                ?>
                <button class="wpm-buymecoffee-button" id="bmc_open_modal_btn"><?php echo esc_html($buttonText); ?></button>
                <div id="bmc_modal_wrapper" class="modal">
                    <div class="bmc_modal_content">
                        <span class="close">&times;</span>
                        <?php (new DemoPage())->loadModalContent(); ?>
                    </div>
                </div>
                <?php
            } else {
                ?>
                <a class="wpm-buymecoffee-button" target="_blank"
                   href="<?php echo esc_url($paymentPageUrl); ?>"><?php echo esc_html($buttonText); ?></a>
                <?php
            } ?>
        </div>
        <?php
        $content = ob_get_clean();
        return $content;
    }

    public static function renderInputElements($template = [], $args = [])
    {
        static::addAssets();

        $nameAttributes = array(
            'data-required' => 'no',
            'data-type' => 'text',
            'name' => 'wpm-supporter-name',
            'placeholder' => 'John Doe',
            'class' => 'wpm-supporter-name',
            'id' => 'wpm-supporter-name',
        );

        $emailAttributes = array(
            'data-required' => 'no',
            'data-type' => 'email',
            'name' => 'wpm-supporter-email',
            'placeholder' => 'example@domain.com (optional)',
            'class' => 'wpm-supporter-email',
            'id' => 'wpm-supporter-email',
        );

        $msgAttributes = array(
            'data-required' => 'yes',
            'data-type' => 'textarea',
            'name' => 'wpm-supporter-message',
            'placeholder' => 'Love to hear from you! (optional)',
            'class' => 'wpm-supporter-message',
            'id' => 'wpm-supporter-message',
        );

        $btnAttributes = array(
            'data-required' => 'no',
            'data-type' => 'submit',
            'name' => 'wpm_submit_button',
            'placeholder' => 'Submit',
            'class' => 'wpm_submit_button',
            'id' => 'wpm_submit_button',
        );
        if (empty($template)) {
            $template = (new Buttons())->getButton();
        }
        $enableName = Arr::get($template, 'enableName') == 'yes';
        $enableEmail = Arr::get($template, 'enableEmail') == 'yes';
        $enableMsg = Arr::get($template, 'enableMessage') == 'yes';
        $allowRecurring = Arr::get($template, 'allow_recurring', 'no') === 'yes';
        $recurringInterval = Arr::get($template, 'recurring_interval', 'month');
        $defaultAmount = intval(Arr::get($template, 'defaultAmount', '5'));
        $customCoffeeDefault = intval(Arr::get($template, 'custom_coffee', '5'));

        $currency = Arr::get($template, 'currency', 'USD');
        $symbool = PaymentHelper::currencySymbol($currency);
        $formattedDefaultAmount = PaymentHelper::getFormattedAmount($defaultAmount * 100, $currency);
        $formDynamicClass = BuilderHelper::getFormDynamicClass();

        $isCustomPay = false;
        $customAmount = $defaultAmount;

        if (isset($args['custom'])) {
            $isCustomPay = true;
            $customAmount = intval(Arr::get($args, 'custom', $defaultAmount));
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public form parameter
        if (isset($_GET['custom'])) {
            $isCustomPay = true;
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public form parameter
            $customAmount = intval($_GET['custom']);
        }

        // Pre-populate form from membership level when arriving via paywall CTA
        $bmcLevelId = 0;
        $bmcLevelName = '';
        $bmcLevelPrice = 0;
        $bmcLevelFormattedAmount = '';
        $bmcLevelPaymentType = 'subscription';
        if (!empty($args['bmc_level'])) {
            $bmcLevel   = $args['bmc_level'];
            $bmcLevelId = absint($bmcLevel->id);
            $bmcLevelName = sanitize_text_field($bmcLevel->name);
            $bmcLevelPrice = (int) $bmcLevel->price;
            $bmcLevelPaymentType = !empty($bmcLevel->payment_type) && $bmcLevel->payment_type === 'one_time' ? 'one_time' : 'subscription';
            $bmcLevelFormattedAmount = PaymentHelper::getFormattedAmount($bmcLevelPrice, $currency);
            $defaultAmount = $bmcLevelPrice / 100;
            $customCoffeeDefault = $defaultAmount;
            $allowRecurring   = $bmcLevelPaymentType === 'subscription';
            $recurringInterval = sanitize_text_field($bmcLevel->interval_type ?: 'month');
            $emailAttributes['data-required'] = 'yes';
            $emailAttributes['placeholder'] = __('Email address', 'buy-me-coffee');
        }

        $submitButtonLabel = $bmcLevelId
            ? ($bmcLevelPaymentType === 'one_time' ? __('Join', 'buy-me-coffee') : __('Subscribe', 'buy-me-coffee'))
            : __('Support', 'buy-me-coffee');

        ob_start();
        ?>
        <form id="<?php echo esc_attr($formDynamicClass . '_main_wrapper');  ?>" class="buymecoffee_form<?php echo $bmcLevelId ? ' bmc-level-locked' : ''; ?>" data-wpm_currency="<?php echo esc_html($currency); ?>"<?php echo $bmcLevelId ? ' data-bmc-level-id="' . absint($bmcLevelId) . '" data-bmc-payment-type="' . esc_attr($bmcLevelPaymentType) . '"' : ''; ?>>
            <input type="hidden" name="__buymecoffee_ref" value="<?php echo esc_html($template['yourName']); ?>"/>
            <input type="hidden" name="buymecoffee_quantity" value="1"/>
            <?php if ($bmcLevelId): ?>
            <input type="hidden" name="bmc_level_id" value="<?php echo absint($bmcLevelId); ?>"/>
            <?php
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only URL param
            $bmcReturnUrl = isset($_GET['bmc_return_url']) ? esc_url_raw(wp_unslash($_GET['bmc_return_url'])) : '';
            if ($bmcReturnUrl): ?>
            <input type="hidden" name="bmc_return_url" value="<?php echo esc_url($bmcReturnUrl); ?>"/>
            <?php endif; ?>
            <?php endif; ?>
            <div class="buymecoffee_payment_processor"></div>
            <?php if ($bmcLevelId): ?>
            <!-- Level-locked: show level name + fixed amount, hide coffee selector -->
            <div class="buymecoffee_input_content">
                <input type="hidden" style="display: none!important;" name="buymecoffee_amount" class="buymecoffee_payment" value="<?php echo esc_attr(number_format($defaultAmount, 2, '.', '')); ?>"
                       data-price="<?php echo esc_attr($bmcLevelPrice); ?>"/>
            </div>
            <div class="bmc-level-locked-info" data-bmc-level-info>
                <span class="bmc-level-locked-name"><?php echo esc_html($bmcLevelName); ?></span>
                <div class="bmc-level-locked-pricing">
                    <span class="bmc-level-locked-amount"><?php echo esc_html($bmcLevelFormattedAmount); ?></span>
                    <?php if ($bmcLevelPaymentType === 'subscription') : ?>
                    <span class="bmc-level-locked-interval">/<?php echo esc_html($recurringInterval === 'year' ? __('year', 'buy-me-coffee') : __('month', 'buy-me-coffee')); ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <?php elseif (!$isCustomPay): ?>
            <div class="buymecoffee_input_content">
                <input type="hidden" style="display: none!important;" name="buymecoffee_amount" class="buymecoffee_payment" value="<?php echo esc_attr($defaultAmount); ?>"
                       data-price="<?php echo esc_attr($defaultAmount * 100); ?>"/>
            </div>
            <div class="buymecoffee_payment_item">
                <div class="buymecoffee_payment_input_content">
                    <div class="buymecoffee_coffee_selector">
                        <img width="36" src="<?php echo esc_url(Vite::staticPath() . 'images/coffee-cup.png'); ?>">
                        <span>x</span>

                        <div class="bmc_coffee">
                            <input id="one_coffee_select_radio_<?php echo esc_attr($formDynamicClass); ?>" value="1" class="coffee-select"
                                   name="radio-group" type="radio" checked>
                            <label for="one_coffee_select_radio_<?php echo esc_attr($formDynamicClass); ?>">1</label>

                            <input id="two_coffee_select_radio_<?php echo esc_attr($formDynamicClass); ?>" value="2" class="coffee-select"
                                   name="radio-group" type="radio">
                            <label for="two_coffee_select_radio_<?php echo esc_attr($formDynamicClass); ?>">2</label>

                            <input id="three_coffee_select_radio_<?php echo esc_attr($formDynamicClass); ?>" value="3" class="coffee-select"
                                   name="radio-group" type="radio">
                            <label for="three_coffee_select_radio_<?php echo esc_attr($formDynamicClass); ?>">3</label>
                        </div>
                        <input class="buymecoffee_custom_quantity" type="number" min="1" name="buymecoffee_quantity" value="5" data-quantity="5">

                    </div>
                </div>
            </div>

            <?php endif; ?>
            <?php if ($isCustomPay): ?>
            <!--   This custom quantity will update in any future feature       /-->
            <div class="buymecoffee_payment_item" style="align-items: center;">
                <div class="buymecoffee_input_content">
                    <div class="buymecoffee_input_content_custom_pay">
                        <span class="buymecoffee_currency_prefix"><?php echo esc_html($symbool); ?></span>
                        <input type="number" class="buymecoffee_payment"
                               name="buymecoffee_amount"
                               value="<?php echo esc_attr($customAmount); ?>"
                               data-price="<?php echo esc_attr($customAmount * 100); ?>">
                    </div>
                </div>
            </div>
            <?php endif; ?>
            <?php if ($enableName): ?>
                <div data-element_type="input" class="buymecoffee_form_item">
                    <div class="buymecoffee_input_content">
                        <input <?php
                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        echo static::builtAttributes($nameAttributes); ?>></input>
                    </div>
                </div>
            <?php endif; ?>

            <?php
            // Show email field normally, or hidden-but-present when an account is required.
            $requiresAccountEmail = $allowRecurring || (bool) $bmcLevelId;
            $emailHiddenForAccount = !$enableEmail && $requiresAccountEmail;
            if ($enableEmail || $requiresAccountEmail) : ?>
                <div data-element_type="email" class="buymecoffee_form_item<?php echo $emailHiddenForAccount ? ' bmc_email_recurring_only' : ''; ?>"<?php echo $emailHiddenForAccount ? ' style="display:none;"' : ''; ?>>
                    <div class="buymecoffee_input_content">
                        <input <?php
                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        echo static::builtAttributes($emailAttributes); ?>></input>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($enableMsg): ?>
                <div data-element_type="textarea" class="buymecoffee_form_item">
                    <div class="buymecoffee_input_content">
                        <textarea rows="2" <?php
                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        echo static::builtAttributes($msgAttributes); ?>></textarea>
                    </div>
                </div>
            <?php endif; ?>

            <div class="buymecoffee_form_item buymecoffee_pay_methods" id="buymecoffee_pay_methods">
                <div class="buymecoffee_pay_method" data-payment_selected="none">
                    <?php echo esc_html(static::payMethod($template, $bmcLevelId)); ?>
                </div>
            </div>

            <?php
            $intervalLabel = $recurringInterval === 'year' ? __('yearly', 'buy-me-coffee') : __('monthly', 'buy-me-coffee');
            if ($allowRecurring) : ?>
            <?php if ($bmcLevelId) : ?>
            <div class="buymecoffee_recurring_section" style="display:none;" data-interval="<?php echo esc_attr($recurringInterval); ?>">
                <input type="hidden" class="buymecoffee_is_recurring" name="buymecoffee_is_recurring" value="yes">
            </div>
            <?php else : ?>
            <div class="buymecoffee_recurring_section" style="display:none;" data-interval="<?php echo esc_attr($recurringInterval); ?>">
                <label class="buymecoffee_recurring_label">
                    <input type="checkbox" class="buymecoffee_is_recurring" name="buymecoffee_is_recurring" value="yes">
                    <?php esc_html_e('Make it recurring', 'buy-me-coffee'); ?>
                    <span class="buymecoffee_recurring_hint">(<?php echo esc_html(sprintf(/* translators: %s: billing interval, e.g. "monthly" */ __('billed %s', 'buy-me-coffee'), $intervalLabel)); ?>)</span>
                </label>
            </div>
            <?php endif; ?>
            <?php endif; ?>

            <div data-element_type="submit" class="buymecoffee_form_item buymecoffee_form_submit_wrapper">
                <div class="buymecoffee_input_content">
                    <button <?php
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    echo static::builtAttributes($btnAttributes); ?>
                            data-default-label="<?php esc_attr_e('Support', 'buy-me-coffee'); ?>"
                            data-recurring-label="<?php esc_attr_e('Subscribe', 'buy-me-coffee'); ?>"
                            data-membership-label="<?php echo esc_attr($bmcLevelPaymentType === 'one_time' ? __('Join', 'buy-me-coffee') : __('Subscribe', 'buy-me-coffee')); ?>">
                        <span class="wpm_submit_button_label"><?php echo esc_html($submitButtonLabel); ?></span>
                        <div class="wpm_loading_svg">
                            <svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg"
                                 xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="30px" height="30px"
                                 viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve">
                                <path opacity="0.2" fill="#000"
                                      d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946 s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634 c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/>
                                <path fill="#000"
                                      d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0 C22.32,8.481,24.301,9.057,26.013,10.047z">
                                    <animateTransform attributeType="xml" attributeName="transform" type="rotate"
                                                      from="0 20 20"
                                                      to="360 20 20" dur="0.5s" repeatCount="indefinite"/>
                                </path></svg>
                        </div>
                            <span class="wpm_payment_total_amount_prefix" style="display:none;"></span>
                            <span class="wpm_payment_total_amount"><?php echo esc_html($formattedDefaultAmount); ?></span>
                    </button>
                </div>
            </div>
            <p class="buymecoffee_no_signup" data-default="<?php esc_attr_e('No signup required', 'buy-me-coffee'); ?>" data-recurring="<?php esc_attr_e('An account will be created to manage your subscription', 'buy-me-coffee'); ?>" data-membership="<?php esc_attr_e('An account will be created to manage your membership', 'buy-me-coffee'); ?>"><?php esc_html_e('No signup required', 'buy-me-coffee'); ?></p>
        </form>
        <?php
        return ob_get_clean();
    }

    public static function payMethod($template, $bmcLevelId = 0)
    {
        $methods = PaymentHandler::getAllMethods();
        $requiresSubscription = (bool) $bmcLevelId;
        $hasActiveMethod = false;

        foreach ($methods as $method) {
            if (!PaymentHandler::isMethodEnabled($method)) {
                continue;
            }

            // For subscription checkouts, only show gateways that support subscriptions
            if ($requiresSubscription) {
                $supports = isset($method['supports']) ? $method['supports'] : ['one_time'];
                if (!in_array('subscription', $supports, true)) {
                    continue;
                }
            }

            $hasActiveMethod = true;
            do_action('buymecoffee_render_component_' . $method['route'], $template);
        }

        if (!$hasActiveMethod) {
            return __("Please activate at least one payment method!", 'buy-me-coffee');
        }
    }

    public static function addAssets()
    {
        Vite::enqueueStyle('buymecoffee_css', 'scss/public/public-style.scss', array(), BUYMECOFFEE_VERSION);
        Vite::enqueueScript('buymecoffee_public_js',  'js/BmcPublic.js', array('jquery'), BUYMECOFFEE_VERSION, true);
        $bmcSettings      = get_option('buymecoffee_payment_setting', []);
        $accountEnabled   = !empty($bmcSettings['enable_account']) && $bmcSettings['enable_account'] === 'yes';
        $accountPageId    = $accountEnabled && !empty($bmcSettings['account_page_id']) ? (int) $bmcSettings['account_page_id'] : 0;
        $accountPageUrl   = $accountPageId ? (string) get_permalink($accountPageId) : '';

        wp_localize_script('buymecoffee_public_js', 'buymecoffee_general', array_merge(array(
            'ajax_url'         => admin_url('admin-ajax.php'),
            'buymecoffee_nonce' => wp_create_nonce('buymecoffee_nonce'),
            'account_page_url' => $accountPageUrl,
        ), PaymentHelper::getFrontendFormattingConfig()));
    }

    public static function builtAttributes($attributes)
    {
        $atts = "";
        foreach ($attributes as $attributeKey => $attribute) {
            if (is_array($attribute)) {
                $attribute = wp_json_encode($attribute);
            }
            $atts .= esc_attr($attributeKey) . "='" . esc_attr(htmlspecialchars($attribute, ENT_QUOTES)) . "' ";

        }
        return $atts;
    }

    public function confirmation($hash)
    {
        echo 'Thanks for your contribution!';
    }
}
