<?php

namespace SGC\eGiftCard\Hooks\Handler;

defined('ABSPATH') || exit;

use SGC\eGiftCard\Foundation\AppHelper;
use SGC\eGiftCard\Http\Model\UserBalance;
use SGC\eGiftCard\Http\Model\GiftCode;

/**
 * Class ShortCodeHandler
 *
 * Handles the shortcodes for the eGift Card application.
 */
class ShortCodeHandler
{
    use AppHelper;

    /**
     * ShortCodeHandler constructor.
     *
     * Initializes the shortcodes for the eGift Card application.
     */
    public function __construct()
    {
        add_shortcode( 'sgc_smart_gift_customizer', [ $this, 'render_sgc_smart_gift_customizer' ] );
        add_shortcode( 'sgc_smart_gift_redeem_code',  [ $this, 'sgc_smart_gift_redeem_code_shortcode' ] );
    }

    /**
     * Render the eGift Card customizer.
     *
     * @return string The HTML content for the eGift Card customizer.
     */
    public function render_sgc_smart_gift_customizer()
    {
        $custom_css = "";
        $settings = self::getOption('sgc_smart_gift_general_settings', []);
        $colors = $settings['design_settings'] ?? [];
        if ( ! empty( $colors ) ) {
            $amount_color = $colors['gift_amount_btn_color'] ?? '#6A0DAD';
            $add_to_cart_btn_color = $colors['add_to_cart_btn_color'] ?? '#6A0DAD';
            $redeem_btn_color = $colors['redeem_btn_color'] ?? '#6A0DAD';
            $custom_css = "
                <style>
                    :root {
                        --sgc-gift-amount-btn-color: " . esc_attr($amount_color) . ";
                        --sgc-gift-amount-btn-hover-color: " . esc_attr($colors['gift_amount_btn_hover_color'] ?? '#6A0DAD') . ";
                        --sgc-add-to-cart-btn-color: " . esc_attr($add_to_cart_btn_color) . ";
                        --sgc-add-to-cart-btn-hover-color: " . esc_attr($colors['add_to_cart_btn_hover_color'] ?? '#6A0DAD') . ";
                        --sgc-redeem-btn-color: " . esc_attr($redeem_btn_color) . ";
                        --sgc-redeem-btn-hover-color: " . esc_attr($colors['redeem_btn_hover_color'] ?? '#6A0DAD') . ";
                    }
                </style>";
        }
        $this->load_smart_gift_card_customizer_assets();
        return $custom_css . '<div id="sgc_smart_gift_customizer_app"></div>';
    }

    /**
     * Load the assets for the eGift Card customizer.
     *
     * @return void
     */
    public function load_smart_gift_card_customizer_assets()
    {
        wp_enqueue_style(SMART_GIFT_CARD_PLUGIN_ASSET_ID . '-style', SMART_GIFT_CARD_PLUGIN_URL . 'assets/css/gift_card_customizer.css', [], SMART_GIFT_CARD_VERSION);
        wp_enqueue_script(SMART_GIFT_CARD_PLUGIN_ASSET_ID, SMART_GIFT_CARD_PLUGIN_URL . 'assets/js/customizer.js', ['jquery', 'moment'], SMART_GIFT_CARD_VERSION, true);
        wp_localize_script(SMART_GIFT_CARD_PLUGIN_ASSET_ID, SMART_GIFT_CARD_PLUGIN_ASSET_VARS . '_app_vars', $this->smart_gift_card_app_vars());
    }

    /**
     * Render the redeem gift code shortcode.
     *
     * @return string The HTML content for the redeem gift code form.
     */
    public function sgc_smart_gift_redeem_code_shortcode()
    {
        // Check if the user is logged in
        if (!is_user_logged_in()) {
            // Instead of redirection, display a friendly message with login link
            return $this->display_login_required_message();
        }

        $user_id = get_current_user_id();
        $msg = '';
        $settings_msg = '';

        // Process the form submission
        $msg = $this->process_gift_code_redeem($user_id);
        $settings_msg = $this->process_gift_balance_setting($user_id);

        $use_gift_balance = get_user_meta($user_id, 'use_gift_balance', true);
        $checked = ('no' === $use_gift_balance) ? '' : 'checked';

        $userBalanceModel = UserBalance::getInstance();
        $user_balance = $userBalanceModel->getBalanceByUserId($user_id);

        if (empty($user_balance)) {
            $user_balance = 0;
        }

        // Retrieve the current list of last 5 redeemed gift codes from user meta
        $redeem_list = get_user_meta($user_id, 'last_redeemed_gift_codes', true);

        if (!is_array($redeem_list)) {
            $redeem_list = array();
        }

        // Enqueue the necessary scripts and styles
        $this->enqueue_redeem_code_scripts();

        // If the user is logged in, display the input field
        ob_start(); // Start output buffering
        include_once(SMART_GIFT_CARD_PLUGIN_BASE_PATH . 'app/views/redeem-shortcode.php');
        return ob_get_clean(); // Return the buffered content
    }

    /**
     * Enqueue the necessary scripts and styles for the frontend.
     */
    public function enqueue_redeem_code_scripts()
    {
        wp_enqueue_style(SMART_GIFT_CARD_PLUGIN_ASSET_ID . '-style', SMART_GIFT_CARD_PLUGIN_URL . 'assets/css/redeem_code.css', [], SMART_GIFT_CARD_VERSION);
    }

    /**
     * Display a message when user is not logged in.
     *
     * @return string HTML content with login message
     */
    private function display_login_required_message() 
    {
        // Enqueue the necessary scripts and styles
        $this->enqueue_redeem_code_scripts();
        // Get login and registration URLs
        $login_url = wp_login_url(get_permalink());
        $register_url = wp_registration_url();
        
        ob_start(); 
        ?>
        <div class="sgc-login-required-message">
            <div class="sgc-message-container">
                <h2><?php esc_html_e('Login Required', 'smart-gift-card'); ?></h2>
                
                <div class="sgc-message-content">
                    <p><?php esc_html_e('You need to be logged in to redeem a gift card.', 'smart-gift-card'); ?></p>
                    
                    <div class="sgc-login-options">
                        <a href="<?php echo esc_url($login_url); ?>" class="sgc-login-button">
                            <?php esc_html_e('Login', 'smart-gift-card'); ?>
                        </a>
                        
                        <?php if (get_option('users_can_register')) : ?>
                            <span class="sgc-register-note">
                                <?php esc_html_e('Don\'t have an account?', 'smart-gift-card'); ?> 
                                <a href="<?php echo esc_url($register_url); ?>">
                                    <?php esc_html_e('Register', 'smart-gift-card'); ?>
                                </a>
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Redirect the user to the login page.
     *
     * @return void
     */
    private function redirect_to_login()
    {
        wp_safe_redirect(wp_login_url( get_permalink() ) );
        exit;
    }

    /**
     * Process the gift code redemption.
     *
     * @param int $user_id The ID of the user redeeming the gift code.
     * @return string The result message of the redemption process.
     */
    private function process_gift_code_redeem( $user_id )
    {
        if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset( $_POST['gift_code'] ) ) {
            //Verify nonce
            if ( ! isset( $_POST['sgc_smart_gift_redeem_code_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['sgc_smart_gift_redeem_code_nonce'] ) ), 'sgc_smart_gift_redeem_code_action' ) ) {
                return __( 'Invalid nonce.', 'smart-gift-card' );
            } else {
                $gift_code = sanitize_text_field( wp_unslash( $_POST['gift_code'] ) );
               return $this->sgc_smart_gift_redeem_code($gift_code, $user_id);
            }
        }
    }

    /**
     * Process the gift balance setting.
     *
     * @param int $user_id The ID of the user updating the gift balance setting.
     * @return string The result message of the setting update.
     */
    private function process_gift_balance_setting( $user_id )
    {
        if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset( $_POST['gift_balance_use_or_not'] ) ) {
            //Verify nonce
            if ( ! isset( $_POST['use_gift_balance_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['use_gift_balance_nonce'] ) ), 'use_gift_balance_action' ) ) {
                return __( 'Invalid nonce.', 'smart-gift-card' );
            } else {
                $use_gift_balance = isset($_POST['use_gift_balance']) ? 'yes' : 'no';
                update_user_meta($user_id, 'use_gift_balance', $use_gift_balance);
                return __( 'Use Gift Wallet Balance on checkout:', 'smart-gift-card' ) . ' ' . esc_html( $use_gift_balance );
            }
        }
    }

    /**
     * Redeem the gift code.
     *
     * @param string $gift_code The gift code to redeem.
     * @param int    $user_id   The ID of the user redeeming the gift code.
     * @return string The result message of the redemption process.
     */
    private function sgc_smart_gift_redeem_code( $gift_code, $user_id )
    {
        global $wpdb;
        $gift_code_data = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}gift_codes WHERE gift_code = %s AND is_redeemed = 0 AND order_id != 0", $gift_code ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery

        if (!$gift_code_data) {
            return __( 'Invalid or already redeemed gift code.', 'smart-gift-card' );
        }

        $gift_amount = $gift_code_data->gift_amount;

        $userBalanceModel = UserBalance::getInstance();
        $user_balance = $userBalanceModel->getBalanceByUserId( $user_id );

        $new_balance = $user_balance ? floatval( $user_balance ) + floatval( $gift_amount ) : $gift_amount;

        if ( $user_balance ) {
            $userBalanceModel->updateBalance( $user_id, $new_balance );
        } else {
            $userBalanceModel->store([
                'user_id' => $user_id,
                'balance' => $gift_amount,
                'gift_code' => $gift_code,
                'created_at' => current_time('mysql'),
            ]);
        }

        $giftCode = GiftCode::getInstance();
        $giftCode->update(['is_redeemed' => 1], $gift_code_data->id );

        $this->update_redeem_list($user_id, $gift_code, $gift_amount );

        $currency_symbol    = function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '&#36;';

        return __( 'Gift code redeemed successfully! Your new balance is:', 'smart-gift-card' ) .' '. $currency_symbol . $new_balance;
    }

    /**
     * Update the redeem list for the user.
     *
     * @param int    $user_id    The ID of the user.
     * @param string $gift_code  The redeemed gift code.
     * @param float  $gift_amount The amount of the redeemed gift code.
     * @return void
     */
    private function update_redeem_list( $user_id, $gift_code, $gift_amount )
    {
        $redeem_list = get_user_meta( $user_id, 'last_redeemed_gift_codes', true );
        if ( ! is_array($redeem_list ) ) {
            $redeem_list = [];
        }

        array_unshift( $redeem_list, [
            'date' => current_time('mysql'),
            'gift_code' => $gift_code,
            'amount' => $gift_amount,
        ] );

        // Ensure only the last 5 entries are stored
        $redeem_list = array_slice($redeem_list, 0, 5);

        update_user_meta( $user_id, 'last_redeemed_gift_codes', $redeem_list );
    }
}