<?php

namespace WeDevs\Wpuf\Pro\Fields;

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

/**
 * Pricing Checkbox Field Class
 *
 * Checkbox with price values for each option
 *
 * @since 4.2.2
 */
class Field_Pricing_Checkbox extends Form_Field_Checkbox {

    use Pricing_Field_Trait;

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

    /**
     * Render the Pricing Checkbox field
     */
    public function render( $field_settings, $form_id, $type = 'post', $post_id = null ) {
        $selected = [];

        if ( isset( $post_id ) && '0' !== $post_id ) {
            if ( $this->is_meta( $field_settings ) ) {
                if ( $value = $this->get_meta( $post_id, $field_settings['name'], $type, true ) ) {
                    $selected = $this->get_formatted_value( $value );
                } else {
                    $selected = [];
                }
            }
        } else {
            $selected = ! empty( $field_settings['selected'] ) ? $field_settings['selected'] : [];
        }

        // Ensure $selected is always an array
        if ( ! is_array( $selected ) ) {
            $selected = [];
        }

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

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

        <div class="wpuf-fields">
            <?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;
                    ?>
                    <div class="wpuf-pricing-checkbox-item <?php echo 'yes' === esc_attr( $field_settings['inline'] ) ? 'wpuf-checkbox-inline' : 'wpuf-checkbox-block'; ?>">
                        <label>
                            <input
                                type="checkbox"
                                class="<?php echo esc_attr( sprintf( 'wpuf_%s_%d', $field_settings['name'], $form_id ) ); ?>"
                                id="<?php echo esc_attr( $field_settings['name'] ); ?>"
                                name="<?php echo esc_attr( $field_settings['name'] ); ?>[]"
                                value="<?php echo esc_attr( $value ); ?>"
                                <?php echo in_array( $value, $selected ) ? ' checked="checked"' : ''; ?>
                                data-required="<?php echo esc_attr( $field_settings['required'] ); ?>"
                                data-type="pricing-checkbox"
                                data-price="<?php echo esc_attr( $price ); ?>"
                            />
                            <?php echo esc_html( $option ); ?>
                            <?php if ( $show_price ) : ?>
                                <span class="wpuf-price-label"> - <?php echo esc_html( number_format( $price, 2 ) ); ?></span>
                            <?php endif; ?>
                        </label>
                        <?php if ( $enable_quantity ) : ?>
                            <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; margin-left: 10px;"
                            />
                        <?php endif; ?>
                    </div>
                    <?php
                }
            } ?>

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

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

    /**
     * Get field options setting
     *
     * @since 4.2.2
     */
    public function get_options_settings() {
        // Get default common options (label, help, required, etc.)
        $default_options = $this->get_default_option_settings();

        // Get pricing-specific options (includes our custom options field with prices)
        $pricing_options = $this->get_pricing_field_options( true, true, true );

        // Return merged options - note: we don't include parent's get_default_option_dropdown_settings()
        // because pricing fields have their own option management with prices
        return array_merge( $default_options, $pricing_options );
    }

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

        $props = [
            'input_type'        => 'pricing_checkbox',
            'label'             => __( 'Pricing Checkbox', 'wpuf-pro' ),
            'name'              => 'wpuf_pricing_checkbox',
            'is_meta'           => 'yes',
            'selected'          => [],
            'inline'            => 'no',
            'show_price_label'  => 'yes',
            'enable_quantity'   => 'no',
            '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] ) ? $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;
    }
}
