<?php

namespace SGC\eGiftCard\Hooks\Handler;

defined('ABSPATH') || exit; // Prevent direct file access.

use SGC\eGiftCard\Foundation\Application;

class FilterHooksHandler
{
    /**
     * Display custom gift card data in the cart.
     *
     * @param array $item_data Cart item data.
     * @param array $cart_item Cart item.
     * @return array Modified cart item data.
     */
    public static function show_custom_gift_card_cart_data($item_data, $cart_item)
    {
        if (isset($cart_item['gift_card_data'])) {
            $gift_card_data = $cart_item['gift_card_data'];

            // Add custom gift card data to cart item display.
            $item_data[] = array(
                'name'  => __('Recipient Name', 'smart-gift-card'),
                'value' => esc_html($gift_card_data['recipient_name']),
            );
            $item_data[] = array(
                'name'  => __('Recipient Email', 'smart-gift-card'),
                'value' => esc_html($gift_card_data['recipient_email']),
            );
            $item_data[] = array(
                'name'  => __('Sender Name', 'smart-gift-card'),
                'value' => esc_html($gift_card_data['sender_name']),
            );
            $item_data[] = array(
                'name'  => __('Gift Message', 'smart-gift-card'),
                'value' => esc_html($gift_card_data['gift_message']),
            );
        }

        return $item_data;
    }

    /**
     * Display custom gift card design thumbnail in the cart.
     *
     * @param string $product_thumbnail Default product thumbnail.
     * @param array  $cart_item Cart item data.
     * @param string $cart_item_key Cart item key.
     * @return string Modified product thumbnail.
     */
    public static function custom_gift_card_cart_item_name($product_name, $cart_item, $cart_item_key)
    {
        if ( isset( $cart_item['gift_card_data'] ) ) {
            $gift_card = $cart_item['gift_card_data'];

            // Customize the title as you like
            $product_name = sprintf(
                'Gift Card — %s for %s',
                wc_price($gift_card['gift_amount'] ?? 0),
                esc_html($gift_card['recipient_name'] ?? '')
            );
        }

        return $product_name;
    }

    /**
     * Display custom gift card design thumbnail in the cart.
     *
     * @param string $product_thumbnail Default product thumbnail.
     * @param array  $cart_item Cart item data.
     * @param string $cart_item_key Cart item key.
     * @return string Modified product thumbnail.
     */
    public static function custom_gift_card_cart_thumbnail($product_thumbnail, $cart_item, $cart_item_key)
    {
        if (isset($cart_item['gift_card_data']['design_url'])) {
            $design_url = $cart_item['gift_card_data']['design_url'];

            // Check if the design URL contains '_temp_'
            if (strpos($design_url, '_temp_') !== false) {
                // Split the string by '_temp_' and reconstruct the URL
                $url_parts = explode('_temp_', $design_url);
                $design_url = '_temp' . '/' . end($url_parts);
            }

            $upload_dir = wp_upload_dir();
            $uploadUrl  = esc_url($upload_dir['baseurl']) . '/' . SMART_GIFT_CARD_PLUGIN_ASSET_ID . '/' . $design_url;

            // Determine the file extension
            $file_extension = pathinfo($uploadUrl, PATHINFO_EXTENSION);
            // If the file is a video
            if (in_array($file_extension, ['mp4', 'webm', 'ogg'])) {
                return '<video controls class="custom-gift-card-video" style="max-width: 200px; padding: 15px; width: 100%;">
                        <source src="' . $uploadUrl . '" type="video/' . $file_extension . '">
                        Your browser does not support the video tag.
                    </video>';
            }
            // If the file is an image
            else if (in_array($file_extension, ['jpg', 'jpeg', 'png', 'gif'])) {
                return sprintf(
                    '<img src="%s" alt="%s" class="%s" style="%s" />',// phpcs:ignorePluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
                    esc_url($uploadUrl),
                    esc_attr__('Gift Card Design', 'smart-gift-card'),
                    'custom-gift-card-image',
                    'max-width: 200px; padding: 15px; width: 100%;'
                );
            }
        }

        // Fallback to the default product thumbnail.
        return $product_thumbnail;
    }


    /**
     * Customize the quantity display for gift card items in the cart.
     *
     * @param string $product_quantity Default product quantity display.
     * @param string $cart_item_key Cart item key.
     * @param array  $cart_item Cart item data.
     * @return string Modified quantity display.
     */
    public static function custom_gift_card_quantity_display($product_quantity, $cart_item_key, $cart_item)
    {
        if (isset($cart_item['gift_card_data'])) {
            // Return the quantity as plain text for gift card items.
            return '<span class="gift-card-quantity">' . esc_html($cart_item['quantity']) . '</span>';
        }

        // Fallback to the default quantity input for non-gift card items.
        return $product_quantity;
    }

    /**
     * Update the cart item permalink for gift cards to link to a custom editing page.
     *
     * @param string $link Default cart item link.
     * @param array  $cart_item Cart item data.
     * @return string Modified permalink.
     */
    public static function update_cart_item_permalink($link, $cart_item)
    {
        if ( isset($cart_item['unique_key']) ) {
            $app = Application::instance();
            $settings = $app->getOption('sgc_smart_gift_general_settings', []);
            if (isset($settings['redeem_gift_page_id']) && !empty($settings['redeem_gift_page_id'])) {
                $gift_card_page = get_permalink($settings['gift_card_page_id']) . '#/';
            } else {
                $gift_card_page = home_url('/gift-card/#/');
            }
            // Use the unique key to link to a custom gift card editing page.
            $unique_key = urlencode($cart_item['unique_key']);
            $link = $gift_card_page . $unique_key;
        }

        return $link;
    }

    public static function sgc_smart_remove_gift_card_meta_from_order_view($formatted_meta, $item)
    {
        // Meta keys to remove
        $meta_keys_to_remove = array(
            'Gift Amount',
            'Gift Message',
            'Design Url'
        );

        // Loop through the formatted meta and remove unwanted keys
        foreach ($formatted_meta as $key => $meta) {
            if (in_array($meta->key, $meta_keys_to_remove)) {
                unset($formatted_meta[$key]);
            }
        }

        return $formatted_meta;
    }

    /**
     * Hide gift card product from shop/catalog views.
     *
     * @param bool $visible Whether the product is visible.
     * @param int $product_id Product ID.
     * @return bool Modified visibility status.
     */
    public static function hide_gift_card_product($visible, $product_id) 
    {
        $gift_product_id = self::get_smart_gift_card_product_id();
        // Check if the product is a gift card product
        if ( $gift_product_id && $product_id === $gift_product_id ) {
            return false;
        }
        
        return $visible;
    }

    /**
     * Exclude gift card product from product loops.
     *
     * @param WP_Query $query The product query.
     * @return WP_Query Modified query.
     */
    public static function exclude_gift_card_from_shop($query)
    {
        $gift_product_id = self::get_smart_gift_card_product_id();
        // Check if the query is for the main shop page or product category/tag
        if ( $gift_product_id && !is_admin() && $query->is_main_query() && (is_shop() || is_product_category() || is_product_tag()) ) {
            $query->set('post__not_in', array_merge((array)$query->get('post__not_in'), array($gift_product_id)));
        }

        return $query;
    }

    /**
     * Exclude gift card product from widget listings.
     *
     * @param array $args Query arguments.
     * @return array Modified query arguments.
     */
    public static function exclude_gift_card_from_widget($args) 
    {
        $gift_product_id = self::get_smart_gift_card_product_id();
        // Check if the widget is a product widget

        if ( $gift_product_id ) {
            $args['post__not_in'] = array( $gift_product_id );
        }
        
        return $args;
    }

    /**
     * Exclude gift card product from related products.
     *
     * @param array $related_posts Array of related product IDs.
     * @param int $product_id Current product ID.
     * @param array $args Related products arguments.
     * @return array Modified array of related product IDs.
     */
    public static function exclude_gift_card_from_related($related_posts, $product_id, $args) 
    {
        $gift_product_id = self::get_smart_gift_card_product_id();
        // Check if the gift card product ID is set and exists in the related posts
        if ( $gift_product_id && in_array($gift_product_id, $related_posts)) {
            $related_posts = array_diff($related_posts, array($gift_product_id));
        }
        
        return $related_posts;
    }

    /**
     * Exclude gift card product from search results.
     *
     * @param WP_Query $query The query object.
     * @return WP_Query Modified query object.
     */
    public static function exclude_gift_card_from_search($query) 
    {
        // Only modify search queries for the main query and product searches
        if ( ! is_admin() && $query->is_main_query() && ($query->is_search() || $query->is_archive()) ) {
            $gift_product_id = self::get_smart_gift_card_product_id();
            // Check if the gift card product ID is set
            if ( $gift_product_id ) {
                $excluded_ids = $query->get('post__not_in', array());
                if ( ! is_array( $excluded_ids ) ) {
                    $excluded_ids = array();
                }
                $excluded_ids[] = $gift_product_id;
                $query->set('post__not_in', $excluded_ids);
            }
        }
        
        return $query;
    }

    private static function get_smart_gift_card_product_id()
    {
        // Use the instance of Application class to call the getOption method
        $app = Application::instance();
        $settings = $app->getOption('sgc_smart_gift_general_settings', []);
        return isset($settings['gift_product_id']) ? (int)$settings['gift_product_id'] : 0;
    }

    /**
     * Block adding gift card to cart if other products exist and vice versa.
     *
     * @param bool $passed Whether the product can be added to the cart.
     * @param int  $product_id ID of the product being added.
     * @param int  $quantity Quantity of the product being added.
     * @return bool Modified $passed value.
     */
    public static function block_mixed_cart_giftcard( $passed, $product_id, $quantity ) {
        $app = Application::instance();
        $settings = $app->getOption('sgc_smart_gift_general_settings', []);
        if ( isset($settings['gift_product_id']) && ! empty($settings['gift_product_id']) ) {
            $gift_product_id = intval( $settings['gift_product_id'] );
        } else {
            $gift_product_id = 0;
        }

        if( $gift_product_id == 0 ) {
            return $passed;
        }

        $is_giftcard_being_added = ($product_id === $gift_product_id);
        $cart_has_giftcard = false;
        $cart_has_other = false;

        // Check what is already in cart
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( $cart_item['product_id'] === $gift_product_id ) {
                $cart_has_giftcard = true;
            } else {
                $cart_has_other = true;
            }
        }

        $allowed_with_others = isset($settings['sgc_allow_with_others']) ? $settings['sgc_allow_with_others'] : 'yes';

        if ( $allowed_with_others !== 'no' ) {
            return $passed; // No restrictions if allowed with others
        }

        // Rule 1: If cart has gift card → block other products
        if ( $cart_has_giftcard && ! $is_giftcard_being_added ) {
            wc_add_notice( 'You cannot add other items while a Gift Card is in the cart.', 'error' );
            return false;
        }

        // Rule 2: If cart has other products → empty cart and allow gift card
        if ( $cart_has_other && $is_giftcard_being_added ) {
            WC()->cart->empty_cart();
            wc_add_notice( 'Other items have been removed from your cart because Gift Cards must be purchased alone.', 'warning' );
        }

        return $passed;
    }

    /**
     * Disable coupons when gift cards are in the cart.
     *
     * @param bool $valid Whether the coupon is valid.
     * @param WC_Coupon $coupon Coupon object.
     * @return bool Modified validity status.
     * @throws Exception When gift cards are in the cart.
     */
    public static function disable_coupons_with_gift_cards( $valid, $coupon ) {
        if ( ! WC()->cart ) {
            return $valid;
        }

        $app = Application::instance();
        $settings = $app->getOption('sgc_smart_gift_general_settings', []);
        $gift_product_id = isset($settings['gift_product_id']) ? (int)$settings['gift_product_id'] : 0;
        $sgc_allow_coupons = isset($settings['sgc_allow_coupons']) ? $settings['sgc_allow_coupons'] : 'no';
        if ( $gift_product_id == 0 ) {
            return $valid;
        }

        if ( $sgc_allow_coupons === 'no' ) {
            return $valid;
        }

        // Check if cart contains gift cards
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( isset($cart_item['gift_card_data']) || $cart_item['product_id'] === $gift_product_id ) {
                throw new \Exception( __('Coupons cannot be applied when gift cards are in the cart.', 'smart-gift-card') );
            }
        }

        return $valid;
    }

}
