<?php

/**
 * Class Hooks
 * 
 * @package ArraySubs\Features\ProductEdit\Services
 * @since 1.0.0
 *
 * Handles the product edit page assets for the ArraySubs plugin.
 */

namespace ArraySubs\Features\ProductEdit\Services;

use ArraySubs\Supports\Config;
use WC_Product;
use WC_Product_Variation;

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

class Hooks
{
    public static $loadable = true;

    /**
     * Constructor.
     * 
     * Initializes the class by registering WordPress admin hooks.
     */
    public function __construct()
    {
        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets'], 100);
        add_action('woocommerce_product_options_pricing', [$this, 'renderSimpleProductHelperLinks'], 100);
        add_action('woocommerce_variation_options_pricing', [$this, 'renderVariationHelperLinks'], 100, 3);
    }

    /**
     * Enqueues the required CSS and JavaScript files.
     *
     * @param string $hook The current admin page hook.
     * @return void
     */
    public function enqueueAssets($hook): void
    {
        unset($hook);

        // Only load on WooCommerce product admin pages
        $screen = get_current_screen();
        if (!is_admin() || !$screen || $screen->post_type !== 'product') {
            return;
        }

        $is_product_edit_screen = 'post' === $screen->base;
        $is_products_list_screen = 'edit' === $screen->base;

        if (!$is_product_edit_screen && !$is_products_list_screen) {
            return;
        }

        // Load dependencies from webpack asset file
        $asset_file = Config::get('plugin.public_path') . 'build/admin/product-edit-page.asset.php';
        $asset = file_exists($asset_file) ? require $asset_file : ['dependencies' => ['wp-element'], 'version' => ARRAYSUBS_VERSION];

        // Enqueue product edit CSS
        wp_enqueue_style(
            'arraysubs-product-edit',
            Config::get('plugin.public_url') . 'build/admin/product-edit-page.css',
            [],
            $asset['version']
        );

        if (!$is_product_edit_screen) {
            return;
        }

        // Enqueue product edit JS
        wp_enqueue_script(
            'arraysubs-product-edit',
            Config::get('plugin.public_url') . 'build/admin/product-edit-page.js',
            $asset['dependencies'],
            $asset['version'],
            true
        );

        // Load translations for React components
        wp_set_script_translations(
            'arraysubs-product-edit',
            'arraysubs',
            Config::get('plugin.plugin_path') . 'languages'
        );

        $arraysubs_product_edit_data = [
            'currencySymbol' => get_woocommerce_currency_symbol(),
            'locale' => str_replace('_', '-', get_locale()),
            'i18n' => [
                'notSet' => __('Not set', 'arraysubs'),
                'from' => __('From', 'arraysubs'),
                'until' => __('Until', 'arraysubs'),
                'copyToClipboard' => __('Copy to clipboard', 'arraysubs'),
                'copied' => __('Copied!', 'arraysubs'),
                'copyFailed' => __('Copy failed', 'arraysubs'),
            ],
        ];

        $arraysubs_json_flags = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;

        wp_add_inline_script(
            'arraysubs-product-edit',
            'window.arraySubsductEdit = ' . wp_json_encode($arraysubs_product_edit_data, $arraysubs_json_flags) . ';',
            'before'
        );
    }

    /**
     * Render helper links for simple products in the pricing section.
     *
     * @return void
     */
    public function renderSimpleProductHelperLinks(): void
    {
        global $post;

        $product_id = isset($post->ID) ? absint($post->ID) : 0;
        if ($product_id <= 0) {
            return;
        }

        $product = wc_get_product($product_id);
        if (! $product instanceof WC_Product || ! $product->is_type('simple')) {
            return;
        }

        $this->renderHelperLinksBlock($product, false);
    }

    /**
     * Render helper links for each variation in the pricing section.
     *
     * @param int    $loop           Variation loop index.
     * @param array  $variation_data Variation data.
     * @param object $variation      Variation post object.
     * @return void
     */
    public function renderVariationHelperLinks(int $loop, array $variation_data, object $variation): void
    {
        unset($loop, $variation_data);

        $variation_id = isset($variation->ID) ? absint($variation->ID) : 0;
        if ($variation_id <= 0) {
            return;
        }

        $product = wc_get_product($variation_id);
        if (! $product instanceof WC_Product_Variation) {
            return;
        }

        $this->renderHelperLinksBlock($product, true);
    }

    /**
     * Render the helper links block.
     *
     * @param WC_Product $product                 Product object.
     * @param bool       $include_bottom_separator Whether to show a trailing separator.
     * @return void
     */
    private function renderHelperLinksBlock(WC_Product $product, bool $include_bottom_separator): void
    {
        $helper_links = $this->getHelperLinks($product);

        if (empty($helper_links['add_to_cart']) || empty($helper_links['checkout'])) {
            return;
        }

        $wrapper_class = $include_bottom_separator
            ? 'arraysubs-product-helper-links arraysubs-product-helper-links--variation'
            : 'arraysubs-product-helper-links arraysubs-product-helper-links--simple';

        echo '<hr class="arraysubs-product-helper-links__separator" />';
        echo '<div class="' . esc_attr($wrapper_class) . '">';
        echo '<div class="arraysubs-product-helper-links__header">' . esc_html__('Helper Links', 'arraysubs') . '</div>';

        $this->renderSingleHelperLinkRow(
            esc_html__('Direct add to cart', 'arraysubs'),
            $helper_links['add_to_cart']
        );

        $this->renderSingleHelperLinkRow(
            esc_html__('One-click checkout', 'arraysubs'),
            $helper_links['checkout']
        );

        echo '</div>';

        if ($include_bottom_separator) {
            echo '<hr class="arraysubs-product-helper-links__separator" />';
        }
    }

    /**
     * Render a single helper link row.
     *
     * @param string $label       Row label.
     * @param string $url         Generated URL.
     * @return void
     */
    private function renderSingleHelperLinkRow(string $label, string $url): void
    {
        echo '<div class="arraysubs-product-helper-links__row">';
        echo '<div class="arraysubs-product-helper-links__meta">';
        echo '<span class="arraysubs-product-helper-links__label">' . esc_html($label) . '</span>';
        echo '<a href="#" class="arraysubs-product-helper-links__copy-link" data-copy-text="' . esc_attr__('Copy to clipboard', 'arraysubs') . '" data-copied-text="' . esc_attr__('Copied!', 'arraysubs') . '" data-copy-failed-text="' . esc_attr__('Copy failed', 'arraysubs') . '">' . esc_html__('Copy to clipboard', 'arraysubs') . '</a>';
        echo '</div>';
        echo '<input type="text" readonly="readonly" class="arraysubs-product-helper-links__input" value="' . esc_attr($url) . '" />';
        echo '</div>';
    }

    /**
     * Build helper links for a product.
     *
     * @param WC_Product $product Product object.
     * @return array<string, string>
     */
    private function getHelperLinks(WC_Product $product): array
    {
        $query_args = $this->getProductRequestArgs($product);
        if (empty($query_args)) {
            return [];
        }

        return [
            'add_to_cart' => add_query_arg($query_args, wc_get_cart_url()),
            'checkout'    => add_query_arg($query_args, wc_get_checkout_url()),
        ];
    }

    /**
     * Get request arguments used to add the product to cart.
     *
     * @param WC_Product $product Product object.
     * @return array<string, int|string>
     */
    private function getProductRequestArgs(WC_Product $product): array
    {
        if ($product instanceof WC_Product_Variation) {
            $query_args = [
                'add-to-cart' => $product->get_parent_id(),
                'variation_id' => $product->get_id(),
            ];

            foreach ($product->get_variation_attributes() as $attribute_name => $attribute_value) {
                if ('' === (string) $attribute_value) {
                    continue;
                }

                $query_args[$attribute_name] = $attribute_value;
            }

            return $query_args;
        }

        return [
            'add-to-cart' => $product->get_id(),
        ];
    }
}
