<?php

/**
 * Subscription Checkout Hooks
 *
 * @package ArraySubs\Features\SubscriptionCheckout\Services
 */

namespace ArraySubs\Features\SubscriptionCheckout\Services;

defined('ABSPATH') || exit;

use ArraySubs\Features\SubscriptionCheckout\Services\Traits\CartValidationTrait;
use ArraySubs\Features\SubscriptionCheckout\Services\Traits\CheckoutDisplayTrait;
use ArraySubs\Features\SubscriptionCheckout\Services\Traits\CheckoutHelpersTrait;
use ArraySubs\Features\SubscriptionCheckout\Services\Traits\CheckoutMigrationTrait;
use ArraySubs\Features\SubscriptionCheckout\Services\Traits\OneClickCheckoutTrait;
use ArraySubs\Features\SubscriptionCheckout\Services\Traits\SubscriptionCreationTrait;
use ArraySubs\Features\SubscriptionCheckout\Services\Traits\TrialCheckoutTrait;

/**
 * Main checkout integration hooks
 */
class Hooks
{
    use CartValidationTrait;
    use CheckoutDisplayTrait;
    use CheckoutHelpersTrait;
    use CheckoutMigrationTrait;
    use OneClickCheckoutTrait;
    use SubscriptionCreationTrait;
    use TrialCheckoutTrait;

    /**
     * Enable auto-loading
     *
     * @var bool
     */
    public static $loadable = true;

    /**
     * Constructor
     */
    public function __construct()
    {
        // Verify helper functions are available
        if (!function_exists('arraysubs_is_subscription_product')) {
            return;
        }
        if (!function_exists('arraysubs_create_subscription')) {
            return;
        }

        // Cart validation - enforce multiple subscription settings
        add_filter('woocommerce_add_to_cart_validation', [$this, 'validateAddToCart'], 10, 5);
        add_filter('woocommerce_update_cart_validation', [$this, 'validateCartQuantityUpdate'], 10, 4);

        // One-click checkout behavior
        add_action('woocommerce_add_to_cart', [$this, 'maybeKeepOnlyOneClickItemInCart'], 20, 6);
        add_filter('woocommerce_add_to_cart_redirect', [$this, 'redirectOneClickPurchasesToCheckout'], 20, 1);
        add_filter('wc_add_to_cart_message_html', [$this, 'maybeSuppressOneClickAddToCartMessage'], 20, 3);
        add_action('template_redirect', [$this, 'maybeRedirectCartPageToCheckout'], 20);
        add_filter('woocommerce_product_supports', [$this, 'disableAjaxAddToCartForOneClick'], 10, 3);

        // Checkout display - add after order totals (inside order review table, works with AJAX)
        add_action('woocommerce_review_order_after_order_total', [$this, 'displaySubscriptionSummaryInTable']);

        // Checkout migration pricing and metadata.
        add_action('woocommerce_before_calculate_totals', [$this, 'applyCheckoutMigrationPricing'], 30);
        add_filter('arraysubs_subscription_cart_item_data', [$this, 'appendCheckoutMigrationCartItemData'], 10, 4);
        add_action('woocommerce_checkout_create_order_line_item', [$this, 'addCheckoutMigrationOrderItemMeta'], 10, 4);
        add_action('woocommerce_after_checkout_validation', [$this, 'validateCheckoutCustomerRestrictions'], 20, 2);
        add_action('woocommerce_checkout_validate_order_before_payment', [$this, 'validateCheckoutCustomerRestrictionsStoreApi'], 20, 2);
        add_action('arraysubs_order_paid', [$this, 'maybeProcessCheckoutMigrationOrder'], 20, 2);

        // Create subscription on order - Classic Checkout
        add_action('woocommerce_checkout_order_processed', [$this, 'createSubscriptionsFromOrder'], 10, 3);

        // Create subscription on order - Block Checkout (Store API)
        // This hook fires for Block Checkout in WooCommerce 8.0+
        add_action('woocommerce_store_api_checkout_order_processed', [$this, 'createSubscriptionsFromOrderApi'], 10, 1);

        // Also hook into order creation directly as a fallback
        add_action('woocommerce_new_order', [$this, 'maybeCreateSubscriptionsFromNewOrder'], 20, 2);

        // Display subscription info in order details
        add_action('woocommerce_order_details_after_order_table', [$this, 'displayOrderSubscriptions'], 10, 1);

        // Force account creation for subscription purchases (if setting enabled)
        add_filter('woocommerce_checkout_registration_required', [$this, 'maybeRequireRegistration'], 10, 1);

        // Subscription checkout products cannot use cash on delivery.
        add_filter('woocommerce_available_payment_gateways', [$this, 'maybeHideCashOnDeliveryForSubscriptionCheckout'], 20, 1);

        // Trial checkout: skip payment when trial doesn't require a payment method
        add_filter('woocommerce_cart_needs_payment', [$this, 'maybeSkipPaymentForTrial'], 10, 1);
        add_filter('woocommerce_order_needs_payment', [$this, 'maybeSkipOrderPaymentForTrial'], 10, 2);
        add_filter('woocommerce_payment_complete_order_status', [$this, 'filterSubscriptionPaymentCompleteOrderStatus'], 20, 3);

        // Auto-complete zero-total trial orders when the customer lands on the order-received page.
        // Some gateways (e.g. ones that only capture a card-on-file for trials) do not call
        // payment_complete() themselves when the order total is $0, so the order stays in pending.
        add_action('woocommerce_thankyou', [$this, 'maybeAutoCompleteZeroTrialOrder'], 10, 1);

        // Note: Order status changes and subscription activation is now handled by
        // Subscriptions\Services\OrderIntegration which listens to woocommerce_order_status_changed
    }
}
