<?php

namespace WeDevs\Wpuf\Pro;

/**
 * Pricing Fields Assets Loader
 *
 * @since 4.2.2
 */
class Pricing_Fields_Loader {

    /**
     * Constructor
     *
     * @since 4.2.2
     */
    public function __construct() {
        add_action( 'wpuf_form_fields_top', [ $this, 'maybe_enqueue_pricing_assets' ], 5, 2 );
        add_action( 'wp_enqueue_scripts', [ $this, 'register_pricing_assets' ], 100 );
    }

    /**
     * Register pricing fields assets
     *
     * @since 4.2.2
     */
    public function register_pricing_assets() {
        // Don't load in admin
        if ( is_admin() ) {
            return;
        }

        // Register script - WordPress handles registration/enqueuing automatically
        wp_register_script(
            'pricing-fields',
            WPUF_PRO_ASSET_URI . '/js/pricing-fields.js',
            [ 'jquery' ],
            WPUF_PRO_VERSION,
            true
        );

        wp_register_style(
            'pricing-fields',
            WPUF_PRO_ASSET_URI . '/css/pricing-fields.css',
            [],
            WPUF_PRO_VERSION
        );

        // Localize script with pricing data (if needed in future)
        wp_localize_script( 'pricing-fields', 'wpufPricingData', [] );
    }

    /**
     * Enqueue pricing fields assets
     *
     * @since 4.2.2
     */
    public function enqueue_pricing_assets() {
        wp_enqueue_style( 'pricing-fields' );
        wp_enqueue_script( 'pricing-fields' );
    }

    /**
     * Maybe enqueue pricing assets if form has pricing fields
     *
     * @since 4.2.2
     *
     * @param object $form Form object.
     * @param array  $form_fields Form fields array.
     */
    public function maybe_enqueue_pricing_assets( $form, $form_fields ) {
        $has_pricing_fields = false;

        if ( ! empty( $form_fields ) && is_array( $form_fields ) ) {
            foreach ( $form_fields as $field ) {
                $field_type = isset( $field['template'] ) ? $field['template'] : ( isset( $field['input_type'] ) ? $field['input_type'] : '' );

                if ( in_array( $field_type, [
                    'price_field',
                    'pricing_checkbox',
                    'pricing_radio',
                    'pricing_dropdown',
                    'pricing_multiselect',
                    'cart_total',
                ] ) ) {
                    $has_pricing_fields = true;
                    break;
                }
            }
        }

        if ( $has_pricing_fields ) {
            $this->enqueue_pricing_assets();
        }
    }
}
