<?php
/**
 * WooCommerce Store API Extension
 *
 * @package Jeremias\WcLicensedProduct\Checkout
 */

declare(strict_types=1);

namespace Jeremias\WcLicensedProduct\Checkout;

use Automattic\WooCommerce\StoreApi\Schemas\V1\CheckoutSchema;
use Automattic\WooCommerce\StoreApi\StoreApi;
use Automattic\WooCommerce\StoreApi\Schemas\ExtendSchema;
use Jeremias\WcLicensedProduct\License\LicenseManager;

/**
 * Extends the Store API to handle licensed product domain data
 */
final class StoreApiExtension
{
    private const IDENTIFIER = 'wc-licensed-product';

    private LicenseManager $licenseManager;

    public function __construct(LicenseManager $licenseManager)
    {
        $this->licenseManager = $licenseManager;
        $this->registerHooks();
    }

    /**
     * Register Store API hooks
     */
    private function registerHooks(): void
    {
        add_action('woocommerce_blocks_loaded', [$this, 'registerStoreApiExtension']);
    }

    /**
     * Register the Store API extension
     */
    public function registerStoreApiExtension(): void
    {
        if (!class_exists('Automattic\WooCommerce\StoreApi\StoreApi')) {
            return;
        }

        // Register endpoint data extension
        woocommerce_store_api_register_endpoint_data([
            'endpoint' => CheckoutSchema::IDENTIFIER,
            'namespace' => self::IDENTIFIER,
            'data_callback' => [$this, 'getExtensionData'],
            'schema_callback' => [$this, 'getExtensionSchema'],
            'schema_type' => ARRAY_A,
        ]);

        // Register update callback for the domain field
        woocommerce_store_api_register_update_callback([
            'namespace' => self::IDENTIFIER,
            'callback' => [$this, 'handleExtensionUpdate'],
        ]);

        // Hook into checkout order processing
        add_action('woocommerce_store_api_checkout_order_processed', [$this, 'processCheckoutOrder']);
    }

    /**
     * Get extension data for the checkout endpoint
     */
    public function getExtensionData(): array
    {
        return [
            'licensed_product_domain' => WC()->session ? WC()->session->get('licensed_product_domain', '') : '',
        ];
    }

    /**
     * Get extension schema
     */
    public function getExtensionSchema(): array
    {
        return [
            'licensed_product_domain' => [
                'description' => __('Domain for license activation', 'wc-licensed-product'),
                'type' => 'string',
                'context' => ['view', 'edit'],
                'readonly' => false,
            ],
        ];
    }

    /**
     * Handle extension data updates from the frontend
     */
    public function handleExtensionUpdate(array $data): void
    {
        if (isset($data['licensed_product_domain'])) {
            $domain = sanitize_text_field($data['licensed_product_domain']);
            $normalizedDomain = $this->licenseManager->normalizeDomain($domain);

            if (WC()->session) {
                WC()->session->set('licensed_product_domain', $normalizedDomain);
            }
        }
    }

    /**
     * Process the checkout order - save domain to order meta
     */
    public function processCheckoutOrder(\WC_Order $order): void
    {
        $domain = WC()->session ? WC()->session->get('licensed_product_domain', '') : '';

        // Also check in the request data for block checkout
        if (empty($domain)) {
            $requestData = json_decode(file_get_contents('php://input'), true);
            if (isset($requestData['extensions'][self::IDENTIFIER]['licensed_product_domain'])) {
                $domain = sanitize_text_field($requestData['extensions'][self::IDENTIFIER]['licensed_product_domain']);
                $domain = $this->licenseManager->normalizeDomain($domain);
            }
        }

        if (!empty($domain)) {
            $order->update_meta_data('_licensed_product_domain', $domain);
            $order->save();

            // Clear session data
            if (WC()->session) {
                WC()->session->set('licensed_product_domain', '');
            }
        }
    }
}
