<?php
/**
 * WooCommerce Checkout Blocks Integration
 *
 * @package Jeremias\WcLicensedProduct\Checkout
 */

declare(strict_types=1);

namespace Jeremias\WcLicensedProduct\Checkout;

use Automattic\WooCommerce\Blocks\Integrations\IntegrationInterface;
use Jeremias\WcLicensedProduct\Admin\SettingsController;
use Jeremias\WcLicensedProduct\Product\LicensedProductVariation;

/**
 * Integration with WooCommerce Checkout Blocks
 */
final class CheckoutBlocksIntegration implements IntegrationInterface
{
    /**
     * The name of the integration
     */
    public function get_name(): string
    {
        return 'wc-licensed-product';
    }

    /**
     * Initialize the integration
     */
    public function initialize(): void
    {
        $this->registerScripts();
        $this->registerAdditionalCheckoutFields();
    }

    /**
     * Register scripts for the checkout block
     */
    private function registerScripts(): void
    {
        $scriptPath = WC_LICENSED_PRODUCT_PLUGIN_DIR . 'assets/js/checkout-blocks.js';
        $scriptUrl = WC_LICENSED_PRODUCT_PLUGIN_URL . 'assets/js/checkout-blocks.js';

        if (file_exists($scriptPath)) {
            wp_register_script(
                'wc-licensed-product-checkout-blocks',
                $scriptUrl,
                ['wc-blocks-checkout', 'wp-element', 'wp-components', 'wp-i18n', 'wp-plugins', 'wp-data'],
                WC_LICENSED_PRODUCT_VERSION,
                true
            );

            wp_set_script_translations(
                'wc-licensed-product-checkout-blocks',
                'wc-licensed-product',
                WC_LICENSED_PRODUCT_PLUGIN_DIR . 'languages'
            );
        }
    }

    /**
     * Register additional checkout fields using WooCommerce Blocks API
     */
    private function registerAdditionalCheckoutFields(): void
    {
        add_action('woocommerce_blocks_loaded', function (): void {
            // Check if the function exists (WooCommerce 8.9+)
            if (!function_exists('woocommerce_register_additional_checkout_field')) {
                return;
            }

            // Register the domain field using WooCommerce's checkout fields API
            // For single domain mode only (multi-domain uses custom JS component)
            if (!SettingsController::isMultiDomainEnabled()) {
                woocommerce_register_additional_checkout_field([
                    'id' => 'wc-licensed-product/domain',
                    'label' => __('License Domain', 'wc-licensed-product'),
                    'location' => 'order',
                    'type' => 'text',
                    'required' => false,
                    'attributes' => [
                        'placeholder' => __('example.com', 'wc-licensed-product'),
                        'pattern' => '^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$',
                        'title' => __('Enter a valid domain (without http:// or www)', 'wc-licensed-product'),
                    ],
                ]);
            }
        });
    }

    /**
     * Returns an array of script handles to enqueue in the frontend context
     */
    public function get_script_handles(): array
    {
        return ['wc-licensed-product-checkout-blocks'];
    }

    /**
     * Returns an array of script handles to enqueue in the editor context
     */
    public function get_editor_script_handles(): array
    {
        return [];
    }

    /**
     * Returns script data to pass to the frontend scripts
     */
    public function get_script_data(): array
    {
        $isMultiDomain = SettingsController::isMultiDomainEnabled();

        return [
            'hasLicensedProducts' => $this->cartHasLicensedProducts(),
            'licensedProducts' => $this->getLicensedProductsFromCart(),
            'isMultiDomainEnabled' => $isMultiDomain,
            'fieldPlaceholder' => __('example.com', 'wc-licensed-product'),
            'fieldDescription' => $isMultiDomain
                ? __('Enter a unique domain for each license (without http:// or www).', 'wc-licensed-product')
                : __('Enter the domain where you will use the license (without http:// or www).', 'wc-licensed-product'),
            'sectionTitle' => $isMultiDomain
                ? __('License Domains', 'wc-licensed-product')
                : __('License Domain', 'wc-licensed-product'),
            'validationError' => __('Please enter a valid domain.', 'wc-licensed-product'),
            'duplicateError' => __('Each license requires a unique domain.', 'wc-licensed-product'),
            'licenseLabel' => __('License %d:', 'wc-licensed-product'),
            'singleDomainLabel' => __('Domain', 'wc-licensed-product'),
        ];
    }

    /**
     * Check if cart contains licensed products
     */
    private function cartHasLicensedProducts(): bool
    {
        return !empty($this->getLicensedProductsFromCart());
    }

    /**
     * Get licensed products from cart with quantities
     *
     * @return array<string, array{product_id: int, variation_id: int, name: string, quantity: int, duration_label: string}>
     */
    private function getLicensedProductsFromCart(): array
    {
        if (!WC()->cart) {
            return [];
        }

        $licensedProducts = [];
        foreach (WC()->cart->get_cart() as $cartItem) {
            $product = $cartItem['data'];
            if (!$product) {
                continue;
            }

            // Check for simple licensed products
            if ($product->is_type('licensed')) {
                $productId = $product->get_id();
                $licensedProducts[] = [
                    'product_id' => $productId,
                    'variation_id' => 0,
                    'name' => $product->get_name(),
                    'quantity' => (int) $cartItem['quantity'],
                    'duration_label' => '',
                ];
                continue;
            }

            // Check for variations of licensed-variable products
            if ($product->is_type('variation')) {
                $parentId = $product->get_parent_id();
                $parent = wc_get_product($parentId);

                if ($parent && $parent->is_type('licensed-variable')) {
                    $variationId = $product->get_id();

                    // Get duration label if it's a LicensedProductVariation
                    $durationLabel = '';
                    if ($product instanceof LicensedProductVariation) {
                        $durationLabel = $product->get_license_duration_label();
                    } else {
                        // Try to instantiate as LicensedProductVariation
                        $variation = new LicensedProductVariation($variationId);
                        $durationLabel = $variation->get_license_duration_label();
                    }

                    $licensedProducts[] = [
                        'product_id' => $parentId,
                        'variation_id' => $variationId,
                        'name' => $product->get_name(),
                        'quantity' => (int) $cartItem['quantity'],
                        'duration_label' => $durationLabel,
                    ];
                }
            }
        }

        return $licensedProducts;
    }
}
