<?php

namespace Unlockafe_Addons\Classes;

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

/**
 * Class Gift_Card_Product
 * @package Unlockafe_Addons\Classes
 */
class Gift_Card_Product
{
    /**
     * Gift_Card_Product constructor.
     */
    public function __construct()
    {
        add_filter('product_type_selector', [$this, 'add_gift_card_product_type']);
        add_filter('woocommerce_product_class', [$this, 'load_gift_card_product_class'], 10, 2);

        add_filter('woocommerce_product_data_tabs', [$this, 'add_gift_card_product_data_tab']);
        add_action('woocommerce_product_data_panels', [$this, 'add_gift_card_product_data_panel']);
        add_action('woocommerce_process_product_meta_unlockafe_gift_card', [$this, 'save_gift_card_product_data']);

        add_action('woocommerce_unlockafe_gift_card_add_to_cart', [$this, 'gift_card_add_to_cart']);
        add_filter('woocommerce_add_to_cart_validation', [$this, 'validate_gift_card_add_to_cart'], 10, 3);
        add_filter('woocommerce_add_cart_item_data', [$this, 'add_cart_item_data'], 10, 3);
        add_filter('woocommerce_get_price_html', [$this, 'gift_card_price_html'], 10, 2);
        add_action('woocommerce_before_calculate_totals', [$this, 'adjust_cart_item_price']);
        add_filter('wc_get_template', [$this, 'load_gift_card_template'], 10, 5);
        add_action('woocommerce_checkout_create_order_line_item', [$this, 'save_recipient_details_to_order_item'], 10, 4);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_gift_card_scripts']);
    }

    /**
     * Add 'Gift Card' to the product type dropdown.
     *
     * @param array $types
     * @return array
     */
    public function add_gift_card_product_type($types)
    {
        $types['unlockafe_gift_card'] = __('Unlockafe Gift Card', 'unlock-addons-for-elementor');
        return $types;
    }

    /**
     * Load the custom product class for gift cards.
     *
     * @param string $classname
     * @param string $product_type
     * @return string
     */
    public function load_gift_card_product_class($classname, $product_type)
    {
        if ($product_type == 'unlockafe_gift_card') {
            $classname = 'WC_Product_Unlockafe_Gift_Card';
        }
        return $classname;
    }

    /**
     * Add the 'Gift Card' tab to the product data section.
     *
     * @param array $tabs
     * @return array
     */
    public function add_gift_card_product_data_tab($tabs)
    {
        $tabs['unlockafe_gift_card'] = [
            'label'    => __('Gift Card', 'unlock-addons-for-elementor'),
            'target'   => 'unlockafe_gift_card_product_data',
            'class'    => ['show_if_unlockafe_gift_card'],
            'priority' => 21,
        ];
        return $tabs;
    }

    /**
     * Display the content of the 'Gift Card' tab.
     */
    public function add_gift_card_product_data_panel()
    {
        global $post;
        ?>
        <div id="unlockafe_gift_card_product_data" class="panel woocommerce_options_panel">
            <div class="options_group">
                <?php
                woocommerce_wp_text_input(
                    [
                        'id'          => '_unlockafe_gift_card_amount',
                        'label'       => __('Gift Card Amount', 'unlock-addons-for-elementor'),
                        'placeholder' => 'Enter the value of the gift card',
                        'desc_tip'    => 'true',
                        'description' => __('This is the value of the gift card. Leave blank to allow customers to set a custom amount.', 'unlock-addons-for-elementor'),
                        'type'        => 'number',
                        'custom_attributes' => [
                            'step' => 'any',
                            'min'  => '0',
                        ],
                    ]
                );
                ?>
            </div>
        </div>
        <?php
    }

    /**
     * Save the gift card product data.
     *
     * @param int $post_id
     */
    public function save_gift_card_product_data($post_id)
    {
        $gift_card_amount = isset($_POST['_unlockafe_gift_card_amount']) ? wc_clean($_POST['_unlockafe_gift_card_amount']) : '';
                update_post_meta($post_id, '_unlockafe_gift_card_amount', $gift_card_amount);

        // Also update the regular price
                if ($gift_card_amount) {
            update_post_meta($post_id, '_regular_price', $gift_card_amount);
            update_post_meta($post_id, '_price', $gift_card_amount);
        } else {
            // If the amount is cleared, also clear the price
            update_post_meta($post_id, '_regular_price', '');
            update_post_meta($post_id, '_price', '');
        }
    }

    /**
     * Customize the price HTML for gift cards.
     *
     * @param string $price_html
     * @param \WC_Product $product
     * @return string
     */
    public function gift_card_price_html($price_html, $product) {
        if ($product->get_type() === 'unlockafe_gift_card') {
            if ($product->get_price() > 0) {
                return $price_html;
            } else {
                return __('Enter an amount', 'unlock-addons-for-elementor');
            }
        }
        return $price_html;
    }

    /**
     * Display the gift card amount input on the single product page.
     */
    public function gift_card_add_to_cart()
    {
        global $product;

        if (!$product || $product->get_type() !== 'unlockafe_gift_card') {
            return;
        }

        ?>
        <div class="unlockafe-gift-card-recipient-details">
            <h4><?php _e('Recipient Details', 'unlock-addons-for-elementor'); ?></h4>
            <?php
            woocommerce_form_field('unlockafe_recipient_name', [
                'type'        => 'text',
                'class'       => ['form-row-wide'],
                'label'       => __('Recipient\'s Name', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter recipient\'s name', 'unlock-addons-for-elementor'),
                'required'    => true,
            ]);

            woocommerce_form_field('unlockafe_recipient_email', [
                'type'        => 'email',
                'class'       => ['form-row-wide'],
                'label'       => __('Recipient\'s Email', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter recipient\'s email', 'unlock-addons-for-elementor'),
                'required'    => true,
            ]);

            woocommerce_form_field('unlockafe_recipient_message', [
                'type'        => 'textarea',
                'class'       => ['form-row-wide'],
                'label'       => __('Personal Message', 'unlock-addons-for-elementor'),
                'placeholder' => __('Add a personal message (optional)', 'unlock-addons-for-elementor'),
                'required'    => false,
            ]);

            woocommerce_form_field('unlockafe_delivery_date', [
                'type'        => 'text',
                'class'       => ['form-row-wide', 'unlockafe-delivery-date-picker'],
                'label'       => __('Delivery Date', 'unlock-addons-for-elementor'),
                'placeholder' => __('Leave blank to send immediately', 'unlock-addons-for-elementor'),
                'required'    => false,
            ]);

            $fixed_amount = get_post_meta($product->get_id(), '_unlockafe_gift_card_amount', true);

            if (empty($fixed_amount)) {
                // Allow custom amount
                woocommerce_form_field('unlockafe_gift_card_amount', [
                    'type'        => 'number',
                    'label'       => __('Gift Card Amount', 'unlock-addons-for-elementor'),
                    'placeholder' => __('Enter amount', 'unlock-addons-for-elementor'),
                    'required'    => true,
                    'custom_attributes' => [
                        'step' => 'any',
                        'min'  => '1',
                    ],
                ]);
            } else {
                // Use fixed amount
                echo '<input type="hidden" name="unlockafe_gift_card_amount" value="' . esc_attr($fixed_amount) . '">';
            }
            ?>
        </div>
        <?php
    }

    /**
     * Validate the custom gift card amount before adding to cart.
     *
     * @param bool $passed
     * @param int $product_id
     * @param int $quantity
     * @return bool
     */
    public function validate_gift_card_add_to_cart($passed, $product_id, $quantity)
    {
        $product = wc_get_product($product_id);

        // If it's not a gift card, don't do any custom validation.
        if (!$product || $product->get_type() !== 'unlockafe_gift_card') {
            return $passed;
        }

        // From here, we know it's a gift card.

        // Validate custom amount
        if (isset($_POST['unlockafe_gift_card_amount']) && !is_numeric($_POST['unlockafe_gift_card_amount'])) {
            wc_add_notice(__('Please enter a valid gift card amount.', 'unlock-addons-for-elementor'), 'error');
            $passed = false;
        }

        // Validate recipient email
        if (empty($_POST['unlockafe_recipient_email']) || !is_email($_POST['unlockafe_recipient_email'])) {
            wc_add_notice(__('Please enter a valid email address for the recipient.', 'unlock-addons-for-elementor'), 'error');
            $passed = false;
        }

        // Validate recipient name
        if (empty($_POST['unlockafe_recipient_name'])) {
            wc_add_notice(__('Please enter a name for the recipient.', 'unlock-addons-for-elementor'), 'error');
            $passed = false;
        }

        // Validate delivery date if provided
        if (!empty($_POST['unlockafe_delivery_date'])) {
            $date = sanitize_text_field($_POST['unlockafe_delivery_date']);
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                wc_add_notice(__('Please enter a valid delivery date in YYYY-MM-DD format.', 'unlock-addons-for-elementor'), 'error');
                $passed = false;
            }
        }

        return $passed;
    }

    /**
     * Add the custom gift card amount to the cart item data.
     *
     * @param array $cart_item_data
     * @param int $product_id
     * @param int $variation_id
     * @return array
     */
    public function add_cart_item_data($cart_item_data, $product_id, $variation_id) {
        $product = wc_get_product($product_id);
        if (!$product || $product->get_type() !== 'unlockafe_gift_card') {
            return $cart_item_data;
        }

        // Save custom amount
        if (isset($_POST['unlockafe_gift_card_amount'])) {
            $cart_item_data['unlockafe_gift_card_amount'] = (float) wc_clean($_POST['unlockafe_gift_card_amount']);
            $cart_item_data['data']->set_price($cart_item_data['unlockafe_gift_card_amount']);
        }

        // Save recipient details
        if (isset($_POST['unlockafe_recipient_name'])) {
            $cart_item_data['unlockafe_recipient_name'] = sanitize_text_field($_POST['unlockafe_recipient_name']);
        }
        if (isset($_POST['unlockafe_recipient_email'])) {
            $cart_item_data['unlockafe_recipient_email'] = sanitize_email($_POST['unlockafe_recipient_email']);
        }
        if (isset($_POST['unlockafe_recipient_message'])) {
            $cart_item_data['unlockafe_recipient_message'] = sanitize_textarea_field($_POST['unlockafe_recipient_message']);
        }

        if (!empty($_POST['unlockafe_delivery_date'])) {
            $cart_item_data['unlockafe_delivery_date'] = sanitize_text_field($_POST['unlockafe_delivery_date']);
        }

        return $cart_item_data;
    }

    /**
     * Adjust the price of the gift card in the cart.
     *
     * @param object $cart
     */
    public function adjust_cart_item_price($cart) {
        if (is_admin() && !defined('DOING_AJAX')) {
            return;
        }

        foreach ($cart->get_cart() as $cart_item) {
            if (isset($cart_item['unlockafe_gift_card_amount'])) {
                $cart_item['data']->set_price($cart_item['unlockafe_gift_card_amount']);
            }
        }
    }

    /**
     * Load the custom template for the gift card product.
     *
     * @param string $template
     * @param string $template_name
     * @param array $args
     * @param string $template_path
     * @param string $default_path
     * @return string
     */
    public function load_gift_card_template($template, $template_name, $args, $template_path, $default_path) {
        global $product;

        if ($template_name === 'single-product/add-to-cart/simple.php' && is_a($product, 'WC_Product') && $product->get_type() === 'unlockafe_gift_card') {
            $plugin_template_path = plugin_dir_path(__DIR__) . '../templates/single-product/add-to-cart/unlockafe-gift-card.php';
            if (file_exists($plugin_template_path)) {
                return $plugin_template_path;
            }
        }

        return $template;
    }

    /**
     * Save recipient details to the order item meta.
     *
     * @param \WC_Order_Item_Product $item
     * @param string $cart_item_key
     * @param array $values
     * @param \WC_Order $order
     */
    public function save_recipient_details_to_order_item($item, $cart_item_key, $values, $order) {
        if (!empty($values['unlockafe_recipient_name'])) {
            $item->add_meta_data('Recipient Name', $values['unlockafe_recipient_name']);
        }
        if (!empty($values['unlockafe_recipient_email'])) {
            $item->add_meta_data('Recipient Email', $values['unlockafe_recipient_email']);
        }
        if (!empty($values['unlockafe_recipient_message'])) {
            $item->add_meta_data('Message', $values['unlockafe_recipient_message']);
        }
        if (!empty($values['unlockafe_delivery_date'])) {
            $item->add_meta_data('Delivery Date', $values['unlockafe_delivery_date']);
        }
    }

    /**
     * Enqueue scripts for the gift card product page.
     */
    public function enqueue_gift_card_scripts() {
        if (is_product()) {
            global $product;
            if (is_a($product, 'WC_Product') && $product->get_type() === 'unlockafe_gift_card') {
                wp_enqueue_script('jquery-ui-datepicker');
                wp_enqueue_style('jquery-ui-css', '//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css');
                wp_add_inline_script('jquery-ui-datepicker', "
                    jQuery(document).ready(function($) {
                        $('.unlockafe-delivery-date-picker input').datepicker({
                            dateFormat: 'yy-mm-dd',
                            minDate: 0
                        });
                    });
                ");
            }
        }
    }
}
    
if (!class_exists('WC_Product_Unlockafe_Gift_Card')) {
    class WC_Product_Unlockafe_Gift_Card extends \WC_Product_Simple
    {
        public function __construct($product = 0)
        {
            parent::__construct($product);
            $this->set_virtual(true);
        }

        public function get_type() {
            return 'unlockafe_gift_card';
        }
    }
}
