<?php

namespace WeDevs\Wpuf\Pro;

use WeDevs\Wpuf\Admin\Forms\Form;
use WeDevs\Wpuf\Pro\Fields\Field_Address;
use WeDevs\Wpuf\Pro\Fields\Field_Avatar;
use WeDevs\Wpuf\Pro\Fields\Field_Country;
use WeDevs\Wpuf\Pro\Fields\Field_Date;
use WeDevs\Wpuf\Pro\Fields\Field_Display_Name;
use WeDevs\Wpuf\Pro\Fields\Field_Embed;
use WeDevs\Wpuf\Pro\Fields\Field_File;
use WeDevs\Wpuf\Pro\Fields\Field_First_Name;
use WeDevs\Wpuf\Pro\Fields\Field_GMap;
use WeDevs\Wpuf\Pro\Fields\Field_Hook;
use WeDevs\Wpuf\Pro\Fields\Field_Last_Name;
use WeDevs\Wpuf\Pro\Fields\Field_Math_Captcha;
use WeDevs\Wpuf\Pro\Fields\Field_Nickname;
use WeDevs\Wpuf\Pro\Fields\Field_Numeric;
use WeDevs\Wpuf\Pro\Fields\Field_Password;
use WeDevs\Wpuf\Pro\Fields\Field_Phone;
use WeDevs\Wpuf\Pro\Fields\Field_Profile_Photo;
use WeDevs\Wpuf\Pro\Fields\Field_Profile_Phone;
use WeDevs\Wpuf\Pro\Fields\Field_Cover_Photo;
use WeDevs\Wpuf\Pro\Fields\Field_Rating;
use WeDevs\Wpuf\Pro\Fields\Field_Really_Simple_Captcha;
use WeDevs\Wpuf\Pro\Fields\Field_Repeat;
use WeDevs\Wpuf\Pro\Fields\Field_Shortcode;
use WeDevs\Wpuf\Pro\Fields\Field_Step;
use WeDevs\Wpuf\Pro\Fields\Field_Time;
use WeDevs\Wpuf\Pro\Fields\Field_Toc;
use WeDevs\Wpuf\Pro\Fields\Field_Twitter;
use WeDevs\Wpuf\Pro\Fields\Field_Facebook;
use WeDevs\Wpuf\Pro\Fields\Field_Linkedin;
use WeDevs\Wpuf\Pro\Fields\Field_Instagram;
use WeDevs\Wpuf\Pro\Fields\Field_User_Bio;
use WeDevs\Wpuf\Pro\Fields\Field_User_Email;
use WeDevs\Wpuf\Pro\Fields\Field_User_Url;
use WeDevs\Wpuf\Pro\Fields\Field_Username;
use WeDevs\Wpuf\Pro\Fields\Field_Price;
use WeDevs\Wpuf\Pro\Fields\Field_Pricing_Checkbox;
use WeDevs\Wpuf\Pro\Fields\Field_Pricing_Radio;
use WeDevs\Wpuf\Pro\Fields\Field_Pricing_Dropdown;
use WeDevs\Wpuf\Pro\Fields\Field_Pricing_MultiSelect;
use WeDevs\Wpuf\Pro\Fields\Field_Cart_Total;
use WeDevs\Wpuf\Pro\Fields\Field_Gender;
use WeDevs\Wpuf\Pro\Fields\Field_Secondary_Email;
use WeDevs\Wpuf\Pro\Fields\Field_Date_Of_Birth;
use WeDevs\Wpuf\Pro\Fields\Field_Signature;

/**
 *  Pro Fields Manager Class
 *
 * @since 3.1.0
 **/
class Fields_Manager {
    public function __construct() {
        add_filter( 'wpuf_form_fields', [ $this, 'register_fields' ] );
        add_filter( 'wpuf_form_fields_custom_fields', [ $this, 'add_to_custom_fields' ] );
        add_filter( 'wpuf_form_fields_others_fields', [ $this, 'add_to_others_fields' ] );
        add_filter( 'wpuf_form_fields_social_fields', [ $this, 'add_to_social_fields' ] );
        add_filter( 'wpuf_form_fields_groups', [ $this, 'add_pricing_fields_section' ], 15 );
        add_filter( 'wpuf_form_fields_section_after', [ $this, 'add_social_fields_section' ] );
        add_filter( 'wpuf_field_get_js_settings', [ $this, 'add_conditional_field' ] );
        add_action( 'wpuf_form_fields_top', [ $this, 'step_start_form_top' ], 10, 2 );
        add_filter( 'wpuf-form-builder-wp_profile-fields-section-post-fields', [ $this, 'add_gender_to_profile_fields' ] );

        // Register date field validation hooks with higher priority to run after Content_Filter
        add_filter( 'wpuf_add_post_validate', [ 'WeDevs\Wpuf\Pro\Fields\Field_Date', 'validate_date_fields' ], 20 );
        add_filter( 'wpuf_update_post_validate', [ 'WeDevs\Wpuf\Pro\Fields\Field_Date', 'validate_date_fields' ], 20 );

        // Register date of birth field validation hooks
        add_filter( 'wpuf_add_post_validate', [ 'WeDevs\Wpuf\Pro\Fields\Field_Date_Of_Birth', 'validate_date_of_birth' ], 20 );
        add_filter( 'wpuf_update_post_validate', [ 'WeDevs\Wpuf\Pro\Fields\Field_Date_Of_Birth', 'validate_date_of_birth' ], 20 );

        // Register death date save hooks for DoB field (must be here, not in field constructor, to ensure they're registered on every request)
        add_action( 'wpuf_add_post_after_insert', [ 'WeDevs\Wpuf\Pro\Fields\Field_Date_Of_Birth', 'save_death_date_meta' ], 10, 4 );
        add_action( 'wpuf_edit_post_after_update', [ 'WeDevs\Wpuf\Pro\Fields\Field_Date_Of_Birth', 'save_death_date_meta' ], 10, 4 );
        add_action( 'wpuf_after_register', [ 'WeDevs\Wpuf\Pro\Fields\Field_Date_Of_Birth', 'save_death_date_user_meta' ], 10, 6 );
        add_action( 'wpuf_update_profile', [ 'WeDevs\Wpuf\Pro\Fields\Field_Date_Of_Birth', 'save_death_date_user_meta' ], 10, 4 );
    }

    /**
     * Register pro fields
     *
     * @param array $fields
     *
     * @return array
     */
    public function register_fields( $fields ) {
        if ( ! class_exists( 'WeDevs\Wpuf\Fields\Field_Contract' ) ) {
            return $fields;
        }

        $fields['user_login']            = new Field_Username();
        $fields['first_name']            = new Field_First_Name();
        $fields['last_name']             = new Field_Last_Name();
        $fields['display_name']          = new Field_Display_Name();
        $fields['nickname']              = new Field_Nickname();
        $fields['user_email']            = new Field_User_Email();
        $fields['user_url']              = new Field_User_Url();
        $fields['user_bio']              = new Field_User_Bio();
        $fields['password']              = new Field_Password();
        $fields['avatar']                = new Field_Avatar();
        $fields['twitter_url']           = new Field_Twitter();
        $fields['facebook_url']          = new Field_Facebook();
        $fields['linkedin_url']          = new Field_Linkedin();
        $fields['instagram_url']         = new Field_Instagram();
        $fields['profile_photo']         = new Field_Profile_Photo();
        $fields['profile_phone']         = new Field_Profile_Phone();
        $fields['cover_photo']           = new Field_Cover_Photo();
        $fields['repeat_field']          = new Field_Repeat();
        $fields['date_field']            = new Field_Date();
        $fields['file_upload']           = new Field_File();
        $fields['country_list_field']    = new Field_Country();
        $fields['numeric_text_field']    = new Field_Numeric();
        $fields['address_field']         = new Field_Address();
        $fields['google_map']            = new Field_GMap();
        $fields['shortcode']             = new Field_Shortcode();
        $fields['action_hook']           = new Field_Hook();
        $fields['toc']                   = new Field_Toc();
        $fields['ratings']               = new Field_Rating();
        $fields['step_start']            = new Field_Step();
        $fields['embed']                 = new Field_Embed();
        $fields['really_simple_captcha'] = new Field_really_simple_captcha();
        $fields['math_captcha']          = new Field_Math_Captcha();
        $fields['phone_field']           = new Field_Phone();
        $fields['time_field']            = new Field_Time();
        $fields['price_field']           = new Field_Price();
        $fields['pricing_checkbox']      = new Field_Pricing_Checkbox();
        $fields['pricing_radio']         = new Field_Pricing_Radio();
        $fields['pricing_dropdown']      = new Field_Pricing_Dropdown();
        $fields['pricing_multiselect']   = new Field_Pricing_MultiSelect();
        $fields['cart_total']            = new Field_Cart_Total();
        $fields['gender_field']          = new Field_Gender();
        $fields['secondary_email']       = new Field_Secondary_Email();
        $fields['date_of_birth_field']   = new Field_Date_Of_Birth();
        $fields['signature_field']       = new Field_Signature();

        return $fields;
    }

    /**
     * Register fields to custom field section
     *
     * @param array $fields
     */
    public function add_to_custom_fields( $fields ) {
        $pro_fields = [
            'repeat_field',
            'date_field',
            'time_field',
            'file_upload',
            'country_list_field',
            'numeric_text_field',
            'phone_field',
            'address_field',
            'google_map',
            'step_start',
            'embed',
        ];

        return array_merge( $fields, $pro_fields );
    }

    /**
     * Register fields to others field section
     *
     * @param array $fields
     */
    public function add_to_others_fields( $fields ) {
        $pro_fields = [
            'shortcode',
            'action_hook',
            'toc',
            'ratings',
            'really_simple_captcha',
            'math_captcha',
        ];

        return array_merge( $fields, $pro_fields );
    }

    /**
     * Add gender field to profile fields section
     *
     * @param array $fields
     *
     * @return array
     */
    public function add_gender_to_profile_fields( $fields ) {
        $fields[] = 'gender_field';
        $fields[] = 'date_of_birth_field';
        $fields[] = 'signature_field';
        return $fields;
    }

    /**
     * Register fields to social field section
     *
     * @param array $fields
     */
    public function add_to_social_fields( $fields ) {
        // Only add social fields to registration forms (wpuf_profile)
        global $post;

        // Check if we're in the admin and editing a wpuf_profile form
        if ( is_admin() && isset( $_GET['page'] ) && 'wpuf-profile-forms' === $_GET['page'] ) {
            $pro_fields = [
                'twitter_url',
                'facebook_url',
                'linkedin_url',
                'instagram_url',
            ];

            return array_merge( $fields, $pro_fields );
        }

        // Check if we have a post and it's a wpuf_profile type
        if ( $post && 'wpuf_profile' === $post->post_type ) {
            $pro_fields = [
                'twitter_url',
                'facebook_url',
                'linkedin_url',
                'instagram_url',
            ];

            return array_merge( $fields, $pro_fields );
        }

        // Don't add social fields for post forms
        return $fields;
    }

    /**
     * Add pricing fields section only to post forms
     *
     * @param array $sections
     *
     * @return array
     */
    public function add_pricing_fields_section( $sections ) {
        global $post;

        // Only add to post forms, not profile/registration forms
        if ( ! $post || 'wpuf_forms' !== $post->post_type ) {
            return $sections;
        }

        $pricing_section = [
            'title'  => __( 'Pricing Fields', 'wpuf-pro' ),
            'id'     => 'pricing-fields',
            'fields' => [
                'price_field',
                'pricing_checkbox',
                'pricing_radio',
                'pricing_dropdown',
                'pricing_multiselect',
                'cart_total',
            ],
        ];

        array_splice( $sections, 3, 0, [ $pricing_section ] );

        return $sections;
    }

    /**
     * Add social fields section
     *
     * @param array $sections
     */
    public function add_social_fields_section( $sections ) {
        $fields = apply_filters(
            'wpuf_form_fields_social_fields',
            []
        );

        // Only add the section if we have fields
        if ( ! empty( $fields ) ) {
            $social_section = [
                [
                    'title'  => __( 'Social Fields', 'wpuf-pro' ),
                    'id'     => 'social-fields',
                    'fields' => $fields,
                ],
            ];

            return array_merge( $sections, $social_section );
        }

        return $sections;
    }

    /**
     * Add conditional field settings
     *
     * @param array $settings
     */
    public function add_conditional_field( $settings ) {
        $settings['settings'][] = [
            'name'      => 'wpuf_cond',
            'title'     => __( 'Conditional Logic', 'wpuf-pro' ),
            'type'      => 'conditional-logic',
            'section'   => 'advanced',
            'priority'  => 30,
            'help_text' => __( 'Show or hide this field based on the values of other fields', 'wpuf-pro' ),
        ];

        return $settings;
    }

    /**
     * [step_start_form_top description]
     *
     * @param Form          $form
     * @param array         $form_fields
     *
     * @return void
     */
    public function step_start_form_top( $form, $form_fields ) {
        $settings     = $form->get_settings();
        $is_multistep = isset( $settings['enable_multistep'] ) && $this->is_multistep_enabled( $settings['enable_multistep'] );

        if ( ! $is_multistep ) {
            return;
        }

        if ( $this->is_multistep_enabled( $settings['enable_multistep'] ) ) {
            // Validate colours as hex so user-supplied settings can't break out of the <style> block.
            $ms_ac_txt_color   = sanitize_hex_color( $settings['ms_ac_txt_color'] ?? '' ) ?: '#ffffff';
            $ms_active_bgcolor = sanitize_hex_color( $settings['ms_active_bgcolor'] ?? '' ) ?: '#00a0d2';
            $ms_bgcolor        = sanitize_hex_color( $settings['ms_bgcolor'] ?? '' ) ?: '#E4E4E4';
            // The progress header ("Step N of M" + percent) sits on the form
            // background, not on the filled bar, so it must not inherit the active
            // step's text color (white by default -> invisible on a light form). Its
            // color is left to the template stylesheet, which knows its own background.
            ?>
            <style type="text/css">
                .wpuf-form-add .wpuf-form .wpuf-multistep-progressbar .wpuf-step-circle {
                    border-color: <?php echo esc_attr( $ms_bgcolor ); ?>;
                    color: <?php echo esc_attr( $ms_bgcolor ); ?>;
                }

                .wpuf-form-add .wpuf-form .wpuf-multistep-progressbar .wpuf-step-label {
                    color: <?php echo esc_attr( $ms_bgcolor ); ?>;
                }

                .wpuf-form-add .wpuf-form .wpuf-multistep-progressbar .wpuf-step-line {
                    background-color: <?php echo esc_attr( $ms_bgcolor ); ?>;
                }

                .wpuf-form-add .wpuf-form .wpuf-multistep-progressbar .wpuf-step-item.active-step .wpuf-step-circle,
                .wpuf-form-add .wpuf-form .wpuf-multistep-progressbar .wpuf-step-item.completed-step .wpuf-step-circle {
                    background-color: <?php echo esc_attr( $ms_active_bgcolor ); ?>;
                    border-color: <?php echo esc_attr( $ms_active_bgcolor ); ?>;
                    color: <?php echo esc_attr( $ms_ac_txt_color ); ?>;
                }

                .wpuf-form-add .wpuf-form .wpuf-multistep-progressbar .wpuf-step-line-active {
                    background-color: <?php echo esc_attr( $ms_active_bgcolor ); ?>;
                    background: <?php echo esc_attr( $ms_active_bgcolor ); ?>;
                }

                .wpuf-form-add .wpuf-form .wpuf-multistep-progressbar .wpuf-progressbar-track {
                    background-color: <?php echo esc_attr( $ms_bgcolor ); ?>;
                }

                .wpuf-form-add .wpuf-form .wpuf-multistep-progressbar .wpuf-progressbar-fill {
                    background-color: <?php echo esc_attr( $ms_active_bgcolor ); ?>;
                }

            </style>
            <?php $progressbar_type = $settings['multistep_progressbar_type'] ?? 'step_by_step'; ?>
            <input type="hidden" name="wpuf_multistep_type"
                   value="<?php echo esc_attr( $progressbar_type ); ?>"/>

            <?php
            if ( 'step_by_step' === $progressbar_type ) {
                ?>
                <!-- wpuf-multistep-progressbar -->
                <div class="wpuf-multistep-progressbar"></div>
                <?php
            } else {
                ?>
                <div class="wpuf-multistep-progressbar"></div>
                <?php
            }
        }
    }

    /**
     * @param $value
     *
     * @return bool
     */
    private function is_multistep_enabled( $value ) {
        return 'yes' === $value || 'on' === $value;
    }
}
