<?php

namespace WeDevs\Wpuf\Pro\Fields;

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

/**
 * Price Field Class
 *
 * Allows users to input custom amounts or select predefined pricing options
 *
 * @since 4.2.2
 */
class Field_Price extends Pro_Field_Contract {

    use Pricing_Field_Trait;

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

    /**
     * Render the Price field
     *
     * @param array  $field_settings
     * @param int    $form_id
     * @param string $type
     * @param int    $post_id
     *
     * @return void
     */
    public function render( $field_settings, $form_id, $type = 'post', $post_id = null ) {
        $input_mode = isset( $field_settings['price_input_mode'] ) ? $field_settings['price_input_mode'] : 'user_input';
        $is_hidden = isset( $field_settings['price_hidden'] ) && $field_settings['price_hidden'] === 'yes';

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

        $placeholder = ! empty( $field_settings['placeholder'] ) ? $field_settings['placeholder'] : '';

        // If hidden mode, show builder message
        if ( $is_hidden && is_admin() ) {
            echo '<div class="wpuf-price-hidden-notice" style="padding: 10px; background: #fff3cd; border: 1px solid #ffc107; margin: 10px 0;">';
            echo '<strong>' . esc_html__( 'Note:', 'wpuf-pro' ) . '</strong> ';
            echo esc_html__( 'This price field will be hidden on the frontend.', 'wpuf-pro' );
            echo '</div>';
        }

        $field_classes = 'wpuf-fields';
        if ( $is_hidden && ! is_admin() ) {
            $field_classes .= ' wpuf-hidden-field';
            $field_settings['css'] = isset( $field_settings['css'] ) ? $field_settings['css'] . ' wpuf_hidden_field' : 'wpuf_hidden_field';
        }

        // Start the field wrapper
        if ( is_admin() ) { ?>
            <tr <?php $this->print_list_attributes( $field_settings ); ?>> <th><strong> <?php echo wp_kses_post( $field_settings['label'] ); ?><?php echo $this->required_mark( $field_settings ); ?> </strong></th> <td>
        <?php } else { ?>
            <li <?php $this->print_list_attributes( $field_settings ); ?>>
            <div class="wpuf-label">
                <label for="<?php echo esc_attr( $field_settings['name'] . '_' . $form_id ); ?>">
                    <?php echo wp_kses_post( $field_settings['label'] ); ?><?php echo $this->required_mark( $field_settings ); ?>
                </label>
            </div>
            <div class="<?php echo esc_attr( $field_classes ); ?>">
                <input
                    class="textfield <?php echo esc_attr( 'wpuf_' . $field_settings['name'] . '_' . $form_id ); ?>"
                    id="<?php echo esc_attr( $field_settings['name'] . '_' . $form_id ); ?>"
                    type="number"
                    step="0.01"
                    min="<?php echo isset( $field_settings['price_min'] ) ? esc_attr( $field_settings['price_min'] ) : '0'; ?>"
                    <?php if ( isset( $field_settings['price_max'] ) && $field_settings['price_max'] !== '' ) : ?>
                    max="<?php echo esc_attr( $field_settings['price_max'] ); ?>"
                    <?php endif; ?>
                    data-required="<?php echo esc_attr( $field_settings['required'] ); ?>"
                    data-type="price"
                    data-price-field="true"
                    name="<?php echo esc_attr( $field_settings['name'] ); ?>"
                    placeholder="<?php echo esc_attr( $placeholder ); ?>"
                    value="<?php echo esc_attr( $value ); ?>"
                    <?php echo $input_mode === 'fixed' ? 'readonly' : ''; ?>
                />

                <?php $this->help_text( $field_settings ); ?>
            </div>
        <?php } // end if is_admin ?>

        <?php
        if ( is_admin() ) {
            ?>
                </td></tr>
            <?php
        } else {
            ?>
        </li>
        <?php
        }
    }

    /**
     * Get field options setting
     *
     * @return array
     */
    public function get_options_settings() {
        $default_options = $this->get_default_option_settings( true, [ 'width' ] );

        $price_options = [
            [
                'name'      => 'price_input_mode',
                'title'     => __( 'Input Type', 'wpuf-pro' ),
                'type'      => 'radio',
                'options'   => [
                    'user_input' => __( 'User Input - Allow users to enter any amount', 'wpuf-pro' ),
                    'fixed'      => __( 'Fixed - Use default value only', 'wpuf-pro' ),
                ],
                'default'   => 'user_input',
                'section'   => 'basic',
                'priority'  => 12,
                'help_text' => __( 'Choose whether users can enter custom amounts or use a fixed price', 'wpuf-pro' ),
            ],
            [
                'name'      => 'default',
                'title'     => __( 'Default Value', 'wpuf-pro' ),
                'type'      => 'text',
                'section'   => 'advanced',
                'priority'  => 10,
                'help_text' => __( 'The default price value (numeric only)', 'wpuf-pro' ),
            ],
            [
                'name'      => 'placeholder',
                'title'     => __( 'Placeholder Text', 'wpuf-pro' ),
                'type'      => 'text',
                'section'   => 'advanced',
                'priority'  => 11,
                'help_text' => __( 'Placeholder text for the input field (e.g., "Enter amount")', 'wpuf-pro' ),
            ],
            [
                'name'      => 'price_hidden',
                'title'     => __( 'Hidden Field', 'wpuf-pro' ),
                'type'      => 'radio',
                'options'   => [
                    'yes' => __( 'Yes - Hide this field on frontend', 'wpuf-pro' ),
                    'no'  => __( 'No - Show this field', 'wpuf-pro' ),
                ],
                'default'   => 'no',
                'inline'    => true,
                'section'   => 'advanced',
                'priority'  => 12,
                'help_text' => __( 'Hide this field from frontend form (value will still be used in calculations)', 'wpuf-pro' ),
            ],
            [
                'name'      => 'price_min',
                'title'     => __( 'Minimum Value', 'wpuf-pro' ),
                'type'      => 'text',
                'section'   => 'advanced',
                'priority'  => 13,
                'help_text' => __( 'Minimum allowed price value', 'wpuf-pro' ),
                'dependencies' => [
                    'price_input_mode' => 'user_input',
                ],
            ],
            [
                'name'      => 'price_max',
                'title'     => __( 'Maximum Value', 'wpuf-pro' ),
                'type'      => 'text',
                'section'   => 'advanced',
                'priority'  => 14,
                'help_text' => __( 'Maximum allowed price value (leave empty for no limit)', 'wpuf-pro' ),
                'dependencies' => [
                    'price_input_mode' => 'user_input',
                ],
            ],
        ];

        return array_merge( $default_options, $price_options );
    }

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

        $props = [
            'input_type'       => 'price_field',
            'label'            => __( 'Price', 'wpuf-pro' ),
            'is_meta'          => 'yes',
            'price_input_mode' => 'user_input',
            'price_hidden'     => 'no',
            'price_min'        => '0',
            'price_max'        => '',
            'default'          => '',
            'placeholder'      => __( 'Enter amount', 'wpuf-pro' ),
            'id'               => 0,
            'is_new'           => true,
            'show_in_post'     => 'yes',
            'hide_field_label' => 'no',
        ];

        return array_merge( $defaults, $props );
    }

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

        $value = isset( $_POST[ $field['name'] ] ) ? floatval( wp_unslash( $_POST[ $field['name'] ] ) ) : 0;

        // Validate min/max
        if ( isset( $field['price_min'] ) && $value < floatval( $field['price_min'] ) ) {
            $value = floatval( $field['price_min'] );
        }

        if ( isset( $field['price_max'] ) && $field['price_max'] !== '' && $value > floatval( $field['price_max'] ) ) {
            $value = floatval( $field['price_max'] );
        }

        return number_format( $value, 2, '.', '' );
    }

    /**
     * Render price field data
     *
     * @since 4.2.2
     *
     * @param mixed $data
     * @param array $field
     *
     * @return string
     */
    public function render_field_data( $data, $field ) {
        $data = is_array( $data ) ? array_pop( $data ) : $data;
        $hide_label = isset( $field['hide_field_label'] )
            ? wpuf_validate_boolean( $field['hide_field_label'] )
            : false;

        if ( empty( $data ) ) {
            return '';
        }

        $formatted_price = number_format( floatval( $data ), 2 );

        $container_classnames = [ 'wpuf-field-data', 'wpuf-field-data-' . $this->input_type ];

        ob_start();
        ?>
            <li class="<?php echo esc_attr( implode( ' ', $container_classnames ) ); ?>">
                <?php if ( ! $hide_label ) : ?>
                    <label><?php echo esc_html( $field['label'] ); ?>:</label>
                <?php endif; ?>
                <strong><?php echo esc_html( $formatted_price ); ?></strong>
            </li>
        <?php
        return ob_get_clean();
    }
}
