<?php namespace Tussendoor\Reloadify\Controllers\WooCommerce;

use Tussendoor\Reloadify\Concerns\HasActions;
use Tussendoor\Reloadify\Concerns\HasSubscriptionCheckbox;
use Tussendoor\Reloadify\Controllers\Controller;
use Tussendoor\Reloadify\Plugin;

final class CheckoutController extends Controller
{
    use HasActions;
    use HasSubscriptionCheckbox;

    public function register()
    {
        $this->addActions();
        $this->addFilters();
    }

    public function addActions()
    {
        add_action('wp_enqueue_scripts', [$this, 'loadAssets']);
        add_action('woocommerce_checkout_before_terms_and_conditions', [$this, 'addSubscriptionCheckbox']);
        add_action('woocommerce_checkout_after_terms_and_conditions', [$this, 'addSubscriptionCheckbox']);
        add_action('woocommerce_checkout_update_order_meta', [$this, 'saveSubscriptionCheckboxSelection']);
        add_action('woocommerce_checkout_update_order', [$this, 'saveSubscriptionCheckboxSelection']);
    }

    public function addFilters()
    {
        add_filter('woocommerce_checkout_fields', [$this, 'reloadifyCheckoutFields']);
    }

    public function loadAssets()
    {
        if (! is_checkout()) return;

        wp_enqueue_script(
            Plugin::config('plugin.tag').'_checkout_script',
            Plugin::config('plugin.assets').'public/js/checkout.js',
            ['jquery'],
            Plugin::config('plugin.version')
        );

        wp_localize_script(
            Plugin::config('plugin.tag') . '_checkout_script',
            'Checkout',
            array(
                'ajaxurl'                => admin_url('admin-ajax.php'),
                'admin_page'             => Plugin::config('plugin.dashboard_url'),
                'save_update_action'     => self::$saveCheckoutUserMeta,
                'checkoutFormSelector'   => apply_filters('reloadify_checkout_form_class', Plugin::config('checkout.form_class')),
                'nonceSelector'          => apply_filters('reloadify_checkout_nonce_id', Plugin::config('checkout.nonce_id')),
                'firstNameSelector'      => apply_filters('reloadify_checkout_first_name_class', Plugin::config('checkout.first_name_class')),
                'lastNameSelector'       => apply_filters('reloadify_checkout_last_name_class', Plugin::config('checkout.last_name_class')),
                'emailSelector'          => apply_filters('reloadify_checkout_email_class', Plugin::config('checkout.email_class')),
                // Fields for billing address
                'billingStreetSelector'  => apply_filters('reloadify_checkout_billing_street_class', Plugin::config('checkout.billing_street_class')),
                'billingCitySelector'    => apply_filters('reloadify_checkout_billing_city_class', Plugin::config('checkout.billing_city_class')),
                'billingStateSelector'   => apply_filters('reloadify_checkout_billing_state_class', Plugin::config('checkout.billing_state_class')),
                'billingPostcodeSelector'=> apply_filters('reloadify_checkout_billing_postcode_class', Plugin::config('checkout.billing_postcode_class')),
                'billingCountrySelector' => apply_filters('reloadify_checkout_billing_country_class', Plugin::config('checkout.billing_country_class')),
                // Fields for shipping address
                'shippingStreetSelector' => apply_filters('reloadify_checkout_shipping_street_class', Plugin::config('checkout.shipping_street_class')),
                'shippingCitySelector'   => apply_filters('reloadify_checkout_shipping_city_class', Plugin::config('checkout.shipping_city_class')),
                'shippingStateSelector'  => apply_filters('reloadify_checkout_shipping_state_class', Plugin::config('checkout.shipping_state_class')),
                'shippingPostcodeSelector'=> apply_filters('reloadify_checkout_shipping_postcode_class', Plugin::config('checkout.shipping_postcode_class')),
                'shippingCountrySelector'=> apply_filters('reloadify_checkout_shipping_country_class', Plugin::config('checkout.shipping_country_class')),
            )
        );

    }

    public function reloadifyCheckoutFields($fields)
    {
        /**
         * Append original fields to a variable we can use in the filter
         */
        $originalFields = $fields;

        /**
         * Add custom classes to the billing and shipping fields
         */
        $customClasses = [
            'billing_first_name'  => Plugin::config('checkout.first_name_class'),
            'billing_last_name'   => Plugin::config('checkout.last_name_class'),
            'billing_email'       => Plugin::config('checkout.email_class'),
            'billing_address_1'   => Plugin::config('checkout.billing_street_class'),
            'billing_city'        => Plugin::config('checkout.billing_city_class'),
            'billing_state'       => Plugin::config('checkout.billing_state_class'),
            'billing_postcode'    => Plugin::config('checkout.billing_postcode_class'),
            'billing_country'     => Plugin::config('checkout.billing_country_class'),
            'shipping_address_1'  => Plugin::config('checkout.shipping_street_class'),
            'shipping_city'       => Plugin::config('checkout.shipping_city_class'),
            'shipping_state'      => Plugin::config('checkout.shipping_state_class'),
            'shipping_postcode'   => Plugin::config('checkout.shipping_postcode_class'),
            'shipping_country'    => Plugin::config('checkout.shipping_country_class'),
        ];

        foreach ($customClasses as $fieldKey => $class) {
            // Determine if it's a billing or shipping field based on the fieldKey prefix
            $fieldType = strpos($fieldKey, 'billing_') === 0 ? 'billing' : 'shipping';

            // Ensure the field exists before trying to add a class
            if (isset($fields[$fieldType][$fieldKey])) {
                $fields[$fieldType][$fieldKey]['class'][] = apply_filters('reloadify_checkout_' . $fieldKey . '_class', $class);
            }
        }

        /**
         * Apply filters to the changed fields
         *
         * @param $fields - changed fields containing reloadify selectors
         * @param $originalFields - the original unchanged fields
         */
        $fields = apply_filters('after_add_reloadify_checkout_fields_class', $fields, $originalFields);

        return $fields;
    }

}
