<?php

namespace Unlockafe_addons\Classes;

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

/**
 * Store_Credit_Frontend Class
 *
 * Handles the frontend display and logic for the store credit system.
 */
class Store_Credit_Frontend {

    private static $instance = null;

    public static function instance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __construct() {
        add_action('woocommerce_cart_coupon', [$this, 'display_gift_card_field']);
        add_action('woocommerce_checkout_coupon_form', [$this, 'display_gift_card_field']);
        add_action('wp_loaded', [$this, 'apply_gift_card']);
        add_action('woocommerce_cart_calculate_fees', [$this, 'apply_gift_card_discount_to_cart']);
        add_action('woocommerce_checkout_order_processed', [$this, 'update_balance_after_order'], 10, 2);
        add_action('woocommerce_account_dashboard', [$this, 'display_gift_card_balance_on_account_page']);
        add_filter('woocommerce_add_cart_item_data', [$this, 'add_gift_card_recipient_data_to_cart'], 10, 3);
        add_action('woocommerce_checkout_create_order_line_item', [$this, 'save_gift_card_recipient_data_to_order_item'], 10, 4);
    }

    /**
     * Display the gift card input field on the cart and checkout pages.
     */
    public function display_gift_card_field() {
        if (!wc_coupons_enabled()) {
            return;
        }
        ?>
        <div class="unlockafe-gift-card-form" style="margin-top: 20px;">
            <h2><?php esc_html_e('Gift Card', 'unlock-addons-for-elementor'); ?></h2>
            <p><?php esc_html_e('Have a gift card? Enter your code below.', 'unlock-addons-for-elementor'); ?></p>
            <p class="form-row form-row-first">
                <input type="text" name="unlockafe_gift_card_code" class="input-text" placeholder="<?php esc_attr_e('Gift card code', 'unlock-addons-for-elementor'); ?>" id="unlockafe_gift_card_code" value="" />
            </p>
            <p class="form-row form-row-last">
                <button type="submit" class="button" name="apply_gift_card" value="<?php esc_attr_e('Apply gift card', 'unlock-addons-for-elementor'); ?>"><?php esc_html_e('Apply gift card', 'unlock-addons-for-elementor'); ?></button>
            </p>
            <div class="clear"></div>
        </div>
        <?php
    }

    /**
     * Apply the gift card credit from the submitted form.
     */
    public function apply_gift_card() {
        if (!isset($_POST['apply_gift_card']) || !isset($_POST['unlockafe_gift_card_code'])) {
            return;
        }

        $code = sanitize_text_field(wp_unslash($_POST['unlockafe_gift_card_code']));

        if (empty($code)) {
            wc_add_notice(__('Please enter a gift card code.', 'unlock-addons-for-elementor'), 'error');
            return;
        }

        $gift_card = Store_Credit_Manager::instance()->get_gift_card_by_code($code);

        if ($gift_card && $gift_card->balance > 0) {
            WC()->session->set('unlockafe_gift_card_code', $code);
            WC()->session->set('unlockafe_gift_card_balance', $gift_card->balance);
            wc_add_notice(__('Gift card applied successfully.', 'unlock-addons-for-elementor'), 'success');
        } else {
            wc_add_notice(__('Invalid or expired gift card code.', 'unlock-addons-for-elementor'), 'error');
        }

        // Redirect to avoid form resubmission
        wp_safe_redirect(wc_get_cart_url());
        exit();
    }

    /**
     * Apply the gift card balance as a discount to the cart.
     *
     * @param \WC_Cart $cart The cart object.
     */
    public function apply_gift_card_discount_to_cart($cart) {
        if (is_admin() && !defined('DOING_AJAX')) {
            return;
        }

        $gift_card_code = WC()->session->get('unlockafe_gift_card_code');
        $gift_card_balance = WC()->session->get('unlockafe_gift_card_balance');

        if (empty($gift_card_code) || is_null($gift_card_balance)) {
            return;
        }

        $cart_total = $cart->get_subtotal() + $cart->get_fee_total() + $cart->get_shipping_total();

        $discount_amount = min($cart_total, $gift_card_balance);

        if ($discount_amount > 0) {
            $cart->add_fee(__('Gift Card', 'unlock-addons-for-elementor'), -$discount_amount);
        }
    }

    /**
     * Update the gift card balance after an order is processed and clear session.
     *
     * @param int      $order_id The order ID.
     * @param array    $posted_data The posted data from checkout.
     */
    public function update_balance_after_order($order_id, $posted_data) {
        $gift_card_code = WC()->session->get('unlockafe_gift_card_code');

        if (empty($gift_card_code)) {
            return;
        }

        $order = wc_get_order($order_id);
        $discount_total = 0;

        foreach ($order->get_fees() as $fee) {
            if ($fee->name === __('Gift Card', 'unlock-addons-for-elementor')) {
                $discount_total += abs($fee->get_total());
            }
        }

        if ($discount_total > 0) {
            Store_Credit_Manager::instance()->update_gift_card_balance($gift_card_code, $discount_total);
            $order->add_order_note(sprintf(__('Used Gift Card %s for a discount of %s.', 'unlock-addons-for-elementor'), $gift_card_code, wc_price($discount_total)));
        }

        // Clear session data
        WC()->session->set('unlockafe_gift_card_code', null);
        WC()->session->set('unlockafe_gift_card_balance', null);
    }

    /**
     * Display user's gift card balances on the My Account page.
     */
    public function display_gift_card_balance_on_account_page() {
        $user = wp_get_current_user();
        if (!$user || !$user->ID) {
            return;
        }

        $gift_cards = Store_Credit_Manager::instance()->get_gift_cards_by_email($user->user_email);

        if (empty($gift_cards)) {
            return;
        }

        echo '<h2>' . __('Your Gift Cards', 'unlock-addons-for-elementor') . '</h2>';
        echo '<table class="woocommerce-table woocommerce-table--gift-cards shop_table shop_table_responsive">';
        echo '<thead><tr>';
        echo '<th class="woocommerce-gift-card-code">' . __('Code', 'unlock-addons-for-elementor') . '</th>';
        echo '<th class="woocommerce-gift-card-balance">' . __('Balance', 'unlock-addons-for-elementor') . '</th>';
        echo '<th class="woocommerce-gift-card-expiry">' . __('Expires', 'unlock-addons-for-elementor') . '</th>';
        echo '</tr></thead>';
        echo '<tbody>';

        foreach ($gift_cards as $card) {
            echo '<tr>';
            echo '<td>' . esc_html($card->code) . '</td>';
            echo '<td>' . wc_price($card->balance) . '</td>';
            echo '<td>' . ($card->expiry_date ? date_i18n(get_option('date_format'), strtotime($card->expiry_date)) : __('Never', 'unlock-addons-for-elementor')) . '</td>';
            echo '</tr>';
        }

        echo '</tbody></table>';
    }

    /**
     * Add gift card recipient data to the cart item.
     */
    public function add_gift_card_recipient_data_to_cart($cart_item_data, $product_id, $variation_id) {
        $product = wc_get_product($product_id);
        if ($product && $product->get_type() === 'unlockafe_gift_card') {
            if (isset($_POST['unlockafe_gc_recipient_email'])) {
                $cart_item_data['unlockafe_gc_recipient_email'] = sanitize_email($_POST['unlockafe_gc_recipient_email']);
            }
            if (isset($_POST['unlockafe_gc_recipient_name'])) {
                $cart_item_data['unlockafe_gc_recipient_name'] = sanitize_text_field($_POST['unlockafe_gc_recipient_name']);
            }
            if (isset($_POST['unlockafe_gc_recipient_message'])) {
                $cart_item_data['unlockafe_gc_recipient_message'] = sanitize_textarea_field($_POST['unlockafe_gc_recipient_message']);
            }
        }
        return $cart_item_data;
    }

    /**
     * Save gift card recipient data to the order item meta.
     */
    public function save_gift_card_recipient_data_to_order_item($item, $cart_item_key, $values, $order) {
        if (isset($values['unlockafe_gc_recipient_email'])) {
            $item->add_meta_data(
                __('Recipient Email', 'unlock-addons-for-elementor'),
                $values['unlockafe_gc_recipient_email'],
                true
            );
        }
        if (isset($values['unlockafe_gc_recipient_name'])) {
            $item->add_meta_data(
                __('Recipient Name', 'unlock-addons-for-elementor'),
                $values['unlockafe_gc_recipient_name'],
                true
            );
        }
        if (isset($values['unlockafe_gc_recipient_message'])) {
            $item->add_meta_data(
                __('Message', 'unlock-addons-for-elementor'),
                $values['unlockafe_gc_recipient_message'],
                true
            );
        }
    }
}
