<?php

namespace WeDevs\Wpuf\Pro;

use Plugin_Upgrader;
use WP_Ajax_Upgrader_Skin;

/**
 * The installer class
 *
 * @since 4.0.0
 */
class Installer {

    /**
     * Install the WP User Frontend plugin via ajax
     *
     * @since 2.4.2
     *
     * @return void
     */
    public function install_wpuf_free() {
        check_ajax_referer( 'wpuf-pro-installer-nonce' );

        // The handler is only registered for administrators, but this installs
        // and activates a plugin, so verify the capability here too.
        if ( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) {
            wp_send_json_error( __( 'You do not have permission to install plugins.', 'wpuf-pro' ) );
        }

        include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
        include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';

        $plugin = 'wp-user-frontend';
        $api    = plugins_api(
            'plugin_information', [
                'slug'   => $plugin,
                'fields' => [ 'sections' => false ],
            ]
        );

        $upgrader = new Plugin_Upgrader( new WP_Ajax_Upgrader_Skin() );
        $result   = $upgrader->install( $api->download_link );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( $result );
        }

        $result = activate_plugin( 'wp-user-frontend/wpuf.php' );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( $result );
        }

        // check whether the version of wpuf free is prior to the code restructure
        if ( defined( 'WPUF_VERSION' ) && version_compare( WPUF_VERSION, '4.0.0', '<' ) ) {
            add_action( 'admin_notices', [ $this, 'upgrade_notice' ] );

            deactivate_plugins( WPUF_FILE );
        }

        wp_send_json_success();
    }

    /**
     * Show WordPress error notice if WP User Frontend not found
     *
     * @since 4.2.14
     */
    public function upgrade_notice() {
        ?>
        <div class="notice error" id="wpuf-pro-installer-notice" style="padding: 1em; position: relative;">
            <h2><?php esc_html_e( 'Your WP User Frontend Pro is almost ready!', 'wpuf-pro' ); ?></h2>
            <p>
                <?php
                /* translators: 1: opening anchor tag, 2: closing anchor tag. */
                printf( __( 'We\'ve pushed a major update on both <b>WP User Frontend Free</b> and <b>WP User Frontend Pro</b> that requires you to use latest version of both. Please update the WPUF pro to the latest version. <br><strong>Please make sure to take a complete backup of your site before updating.</strong>', 'wpuf-pro' ), '<a target="_blank" href="https://wordpress.org/plugins/wp-user-frontend/">', '</a>' );
                ?>
            </p>
        </div>
        <?php
    }

    /**
     * Create default forms
     *
     * @since 4.2.6
     *
     * @return void
     */
    public static function create_forms() {
        $wpuf_version = get_option( 'wpuf_pro_version' );

        // this is not a first time activation. return
        if ( $wpuf_version ) {
            return;
        }

        $forms = [
            'Registration Form' => [
                'fields' => [
                    [
                        'input_type'      => 'text',
                        'template'        => 'first_name',
                        'required'        => 'no',
                        'label'           => 'First Name',
                        'name'            => 'first_name',
                        'is_meta'         => 'no',
                        'help'            => '',
                        'css'             => '',
                        'placeholder'     => '',
                        'default'         => '',
                        'size'            => 40,
                        'id'              => 0,
                        'is_new'          => true,
                    ],
                    [
                        'input_type'      => 'text',
                        'template'        => 'last_name',
                        'required'        => 'no',
                        'label'           => 'Last Name',
                        'name'            => 'last_name',
                        'is_meta'         => 'no',
                        'help'            => '',
                        'css'             => '',
                        'placeholder'     => '',
                        'default'         => '',
                        'size'            => 40,
                        'id'              => 0,
                        'is_new'          => true,
                    ],
                    [
                        'input_type'      => 'text',
                        'template'        => 'user_login',
                        'required'        => 'no',
                        'label'           => 'Username',
                        'name'            => 'user_login',
                        'is_meta'         => 'no',
                        'help'            => '',
                        'css'             => '',
                        'placeholder'     => '',
                        'default'         => '',
                        'size'            => 40,
                        'id'              => 0,
                        'is_new'          => true,
                        'restriction_to'   => 'max',
                        'restriction_type' => 'character',
                    ],
                    [
                        'input_type'      => 'email',
                        'template'        => 'user_email',
                        'required'        => 'yes',
                        'label'           => 'Email Address',
                        'name'            => 'user_email',
                        'is_meta'         => 'no',
                        'help'            => '',
                        'css'             => '',
                        'placeholder'     => '',
                        'default'         => '',
                        'size'            => 40,
                        'id'              => 0,
                        'is_new'          => true,
                    ],
                    [
                        'input_type'      => 'password',
                        'template'        => 'password',
                        'required'        => 'yes',
                        'label'           => 'Password',
                        'name'            => 'password',
                        'is_meta'         => 'no',
                        'help'            => '',
                        'css'             => '',
                        'placeholder'     => '',
                        'default'         => '',
                        'size'            => 40,
                        'min_length'      => 5,
                        'repeat_pass'     => 'yes',
                        're_pass_label'   => 'Confirm Password',
                        'pass_strength'   => 'no',
                        'id'              => 0,
                        'is_new'          => true,
                    ],
                    [
                        'input_type'      => 'profile_photo',
                        'template'        => 'profile_photo',
                        'required'        => 'no',
                        'label'           => 'Profile Photo',
                        'button_label'    => 'Select Profile Photo',
                        'name'            => 'wpuf_profile_photo',
                        'is_meta'         => 'yes', // handled manually in class
                        'help'            => '',
                        'width'           => '',
                        'css'             => '',
                        'max_size'        => '1024',
                        'count'           => '1',
                        'id'              => 0,
                        'is_new'          => true,
                    ],
                ]
            ],
            'Profile Form' => [
                'fields' => [
                    [
                        'input_type'      => 'text',
                        'template'        => 'first_name',
                        'required'        => 'no',
                        'label'           => 'First Name',
                        'name'            => 'first_name',
                        'is_meta'         => 'no',
                        'help'            => '',
                        'css'             => '',
                        'placeholder'     => '',
                        'default'         => '',
                        'size'            => 40,
                        'id'              => 0,
                        'is_new'          => true,
                    ],
                    [
                        'input_type'      => 'text',
                        'template'        => 'last_name',
                        'required'        => 'no',
                        'label'           => 'Last Name',
                        'name'            => 'last_name',
                        'is_meta'         => 'no',
                        'help'            => '',
                        'css'             => '',
                        'placeholder'     => '',
                        'default'         => '',
                        'size'            => 40,
                        'id'              => 0,
                        'is_new'          => true,
                    ],
                    [
                        'input_type'      => 'text',
                        'template'        => 'user_login',
                        'required'        => 'no',
                        'label'           => 'Username',
                        'name'            => 'user_login',
                        'is_meta'         => 'no',
                        'help'            => '',
                        'css'             => '',
                        'placeholder'     => '',
                        'default'         => '',
                        'size'            => 40,
                        'id'              => 0,
                        'is_new'          => true,
                        'restriction_to'   => 'max',
                        'restriction_type' => 'character',
                    ],
                    [
                        'input_type'      => 'email',
                        'template'        => 'user_email',
                        'required'        => 'yes',
                        'label'           => 'Email Address',
                        'name'            => 'user_email',
                        'is_meta'         => 'no',
                        'help'            => '',
                        'css'             => '',
                        'placeholder'     => '',
                        'default'         => '',
                        'size'            => 40,
                        'id'              => 0,
                        'is_new'          => true,
                    ],
                    [
                        'input_type'      => 'profile_photo',
                        'template'        => 'profile_photo',
                        'required'        => 'no',
                        'label'           => 'Profile Photo',
                        'button_label'    => 'Select Profile Photo',
                        'name'            => 'wpuf_profile_photo',
                        'is_meta'         => 'yes', // handled manually in class
                        'help'            => '',
                        'width'           => '',
                        'css'             => '',
                        'max_size'        => '1024',
                        'count'           => '1',
                        'id'              => 0,
                        'is_new'          => true,
                    ],
                ]
            ]
        ];

        foreach ( $forms as $title => $data ) {
            $args = [
                'post_type'      => 'wpuf_profile',
                'title'          => $title,
                'post_status'    => 'all',
                'posts_per_page' => 1,
            ];

            $query = new \WP_Query( $args );

            // if the form already exists, skip it
            if ( ! empty( $query->posts ) ) {
                continue;
            }

            $form_id = wp_insert_post(
                [
                    'post_title'  => $title,
                    'post_type'   => 'wpuf_profile',
                    'post_status' => 'publish',
                ]
            );

            if ( ! is_wp_error( $form_id ) ) {
                $form_settings = [
                    'user_notification'  => 'on',
                    'admin_notification' => 'on',
                    'notification_type'  => 'welcome_email',
                    'role'               => 'subscriber',
                    'redirect_to'        => 'same',
                    'message'            => __( 'Registration successful', 'wpuf-pro' ),
                    'update_message'     => __( 'Profile updated successfully', 'wpuf-pro' ),
                    'submit_text'        => 'Register',
                    'update_text'        => 'Update Profile',
                ];

                update_post_meta( $form_id, 'wpuf_form_settings', $form_settings );

                foreach ( $data['fields'] as $order => $field ) {
                    wp_insert_post(
                        [
                            'post_type'    => 'wpuf_input',
                            'post_parent'  => $form_id,
                            'post_status'  => 'publish',
                            'post_content' => maybe_serialize( wp_unslash( $field ) ),
                            'menu_order'   => $order,
                        ]
                    );
                }

                if ( 'Profile Form' === $title ) {
                    $settings_data = get_option( 'wpuf_my_account' );

                    if ( empty( $settings_data['edit_profile_form'] ) ) {
                        $settings_data['edit_profile_form'] = $form_id;
                        update_option( 'wpuf_my_account', $settings_data );
                    }
                }
            }
        }

    }
}
