<?php

namespace WeDevs\Wpuf\Pro\Fields;

use WeDevs\Wpuf\Fields\Form_Field_MultiDropdown;
use WeDevs\Wpuf\Pro\Fields\Traits\Pricing_Field_Trait;

/**
 * Pricing Multi-Select Field Class
 *
 * Multi-select dropdown with price values for each option
 *
 * @since 4.2.2
 */
class Field_Pricing_MultiSelect extends Form_Field_MultiDropdown {

    use Pricing_Field_Trait;

    public function __construct() {
        $this->name       = __( 'Pricing Multi-Select', 'wpuf-pro' );
        $this->input_type = 'pricing_multiselect';
        $this->icon       = 'currency';
    }

    /**
     * Render the Pricing Multi-Select field
     */
    public function render( $field_settings, $form_id, $type = 'post', $post_id = null ) {
        if ( isset( $post_id ) && '0' !== $post_id ) {
            $selected = $this->get_meta( $post_id, $field_settings['name'], $type, false );
            $selected = is_array( $selected ) ? $selected : [];
        } else {
            $selected = isset( $field_settings['selected'] ) ? $field_settings['selected'] : [];
        }

        $enable_quantity = isset( $field_settings['enable_quantity'] ) && 'yes' === $field_settings['enable_quantity'];
        $name            = $field_settings['name'];

        wp_enqueue_script( 'wpuf-custom-multiselect' );
        wp_enqueue_style( 'wpuf-custom-multiselect' );

        $this->field_print_label( $field_settings, $form_id ); ?>

        <div class="wpuf-fields">
            <select
                class="multiselect wpuf-multiselect-field <?php echo 'wpuf_' . esc_attr( $field_settings['name'] ) . '_' . esc_attr( $form_id ); ?>"
                id="<?php echo esc_attr( $field_settings['name'] ) . '_' . esc_attr( $form_id ); ?>"
                name="<?php echo esc_attr( $name ); ?>[]"
                data-required="<?php echo esc_attr( $field_settings['required'] ); ?>"
                data-type="pricing-multiselect"
                multiple="multiple"
                style="height: 150px;">

                <?php
                if ( $field_settings['options'] && count( $field_settings['options'] ) > 0 ) {
                    foreach ( $field_settings['options'] as $value => $option ) {
                        $price = isset( $field_settings['prices'][$value] ) ? floatval( $field_settings['prices'][$value] ) : 0;
                        $is_selected = in_array( $value, $selected, true );
                        ?>
                        <option
                            value="<?php echo esc_attr( $value ); ?>"
                            data-price="<?php echo esc_attr( $price ); ?>"
                            <?php selected( $is_selected, true ); ?>>
                            <?php echo esc_html( $option . ' - ' . number_format( $price, 2 ) ); ?>
                        </option>
                        <?php
                    }
                } ?>
            </select>

            <?php if ( $enable_quantity ) : ?>
                <div class="wpuf-multiselect-quantities" style="margin-top: 10px;">
                    <?php foreach ( $field_settings['options'] as $value => $option ) : ?>
                        <div class="wpuf-qty-row" data-value="<?php echo esc_attr( $value ); ?>" style="margin-bottom: 5px; display: none;">
                            <label style="display: inline-block; width: 150px;"><?php echo esc_html( $option ); ?>:</label>
                            <input
                                type="number"
                                class="wpuf-pricing-quantity"
                                name="<?php echo esc_attr( $field_settings['name'] ); ?>_qty[<?php echo esc_attr( $value ); ?>]"
                                min="1"
                                value="1"
                                style="width: 60px;"
                            />
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php $this->help_text( $field_settings ); ?>
        </div>

        <?php $this->after_field_print_label();
    }

    /**
     * Get field options setting
     */
    public function get_options_settings() {
        $default_options = $this->get_default_option_settings();
        $pricing_options = $this->get_pricing_field_options( false, false, true );

        return array_merge( $default_options, $pricing_options );
    }

    /**
     * Get the field props
     */
    public function get_field_props() {
        $defaults = $this->default_attributes();

        $props = [
            'input_type'        => 'pricing_multiselect',
            'label'             => __( 'Pricing Multi-Select', 'wpuf-pro' ),
            'name'              => 'wpuf_pricing_multiselect',
            'is_meta'           => 'yes',
            'enable_quantity'   => 'no',
            'selected'          => [],
            'options'           => [
                'first_item'  => __( 'First Item', 'wpuf-pro' ),
                'second_item' => __( 'Second Item', 'wpuf-pro' ),
                'third_item'  => __( 'Third Item', 'wpuf-pro' ),
            ],
            'prices'            => [
                'first_item'  => '10',
                'second_item' => '25',
                'third_item'  => '50',
            ],
            'id'                => 0,
            'is_new'            => true,
            'show_in_post'      => 'yes',
            'hide_field_label'  => 'no',
        ];

        return array_merge( $defaults, $props );
    }

    /**
     * Prepare entry
     */
    public function prepare_entry( $field ) {
        check_ajax_referer( 'wpuf_form_add' );

        $field_name = isset( $_POST[$field['name']] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST[$field['name']] ) ) : [];
        $entry_value = [];

        if ( $field_name ) {
            foreach ( $field_name as $option_key ) {
                $label = isset( $field['options'][$option_key] ) ? $field['options'][$option_key] : '';
                $price = isset( $field['prices'][$option_key] ) ? floatval( $field['prices'][$option_key] ) : 0;

                $qty = 1;
                if ( isset( $_POST[$field['name'] . '_qty'][$option_key] ) ) {
                    $qty = intval( $_POST[$field['name'] . '_qty'][$option_key] );
                }

                $entry_value[] = $label . ' (' . ( $price * $qty ) . ')';
            }

            return implode( '|', $entry_value );
        }

        return '';
    }

    public function is_pro() {
        return true;
    }
}
