<?php
/**
 * Setup Wizard Class
 *
 * Allows new users to create a Boxtal account or generate API keys.
 *
*/
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * emc_admin_setup_wizard class.
 */
class emc_admin_setup_wizard {

	/** @var string Currenct Step */
	private $step   = '';

	/** @var array Steps for the setup wizard */
	private $steps  = array();

	/**
	 * Hook in tabs.
	 */
	public function __construct() {
        add_action( 'admin_menu', array( $this, 'admin_menus' ) );
        add_action( 'admin_init', array( $this, 'setup_wizard' ) );
	}

	/**
	 * Add admin menus/screens.
	 */
	public function admin_menus() {
		add_dashboard_page( '', '', 'manage_options', 'emc-setup', '' );
	}

	/**
	 * Show the setup wizard.
	 */
	public function setup_wizard() {
		if ( empty( $_GET['page'] ) || 'emc-setup' !== $_GET['page'] ) {
			return;
		}
		$this->steps = array(
			'introduction' => array(
				'name'    =>  __( 'Introduction', 'envoimoinscher' ),
				'view'    => array( $this, 'emc_setup_introduction' ),
				'handler' => ''
			),
			'account' => array(
				'name'    =>  __( 'Create a Boxtal account', 'envoimoinscher' ),
				'view'    => array( $this, 'emc_setup_account' ),
				'handler' => array( $this, 'emc_setup_account_save' )
			),
			'keys' => array(
				'name'    =>  __( 'Generate API keys', 'envoimoinscher' ),
				'view'    => array( $this, 'emc_setup_keys' ),
				'handler' => array( $this, 'emc_setup_keys_save' )
			),
			'next_steps' => array(
				'name'    =>  __( 'Ready!', 'envoimoinscher' ),
				'view'    => array( $this, 'emc_setup_ready' ),
				'handler' => ''
			)
		);
		$this->step = isset( $_GET['step'] ) ? sanitize_key( $_GET['step'] ) : current( array_keys( $this->steps ) );

        wp_enqueue_style( 'multiple_select_css', plugins_url( '/assets/css/multiple-select.css', EMC_PLUGIN_FILE ), array(), '1.2.1' );
        wp_enqueue_script( 'multiple_select_js', plugins_url( '/assets/js/admin/multiple-select.js', EMC_PLUGIN_FILE ),  array( 'jquery' ), '1.2.1' );
        wp_enqueue_script( 'emc-setup', plugins_url( '/assets/js/admin/emc_setup_wizard.js', EMC_PLUGIN_FILE ), array( 'jquery', 'multiple_select_js' ), EMC_VERSION );

        // add translation
        $translations = array(
          'selectAll' => __('Select all', 'envoimoinscher'),
          'allSelected' => __('All selected', 'envoimoinscher'),
          'siretLabelFr' => __('SIRET', 'envoimoinscher'),
          'siretLabelEs' => __('CIF', 'envoimoinscher'),
          'siretLabelWorld' => __('Registration No. in the country', 'envoimoinscher'),
          'required' => __('This field is required', 'envoimoinscher'),
          'minlength' => __('Your password must be at least 6 characters', 'envoimoinscher'),
          'mismatchPassword' => __('Passwords must match', 'envoimoinscher'),
          'mismatchEmail' => __('Email addresses must match', 'envoimoinscher'),
          'formatAlpha' => __('Alphanumeric characters only', 'envoimoinscher'),
          'formatPhone' => __('Not a valid phone number', 'envoimoinscher'),
          'formatEmail' => __('Not a valid email', 'envoimoinscher'),
          'lengthSiret' => __('Siret must be 14 characters', 'envoimoinscher'),
          'lengthOther' => __("Field length doesn't appear to be correct", 'envoimoinscher'),
        );
        wp_localize_script( 'emc-setup', 'translations', $translations );

        // add list of UE countries
        $ue = WC()->countries->get_european_union_countries( 'eu_vat' );
        wp_localize_script( 'emc-setup', 'ue', $ue );

        // add ajax url
        wp_localize_script( 'emc-setup', 'ajax_url', admin_url( 'admin-ajax.php' ) );

        // add nonce for security
        $ajax_nonce = wp_create_nonce( 'boxtale_emc' );
        wp_localize_script( 'emc-setup', 'ajax_nonce', $ajax_nonce );

        // add admin css
        wp_enqueue_style( 'emc-setup', plugins_url( '/assets/css/admin.css', EMC_PLUGIN_FILE ), array(), EMC_VERSION );

		if ( isset( $_POST['save_step'] ) && isset( $this->steps[ $this->step ]['handler'] ) ) {
			call_user_func( $this->steps[ $this->step ]['handler'] );
		}

		ob_start();
		$this->setup_wizard_header();
		$this->setup_wizard_content();
		$this->setup_wizard_footer();
		exit;
	}

	/**
	 * Setup Wizard Header.
	 */
	public function setup_wizard_header() {
        $language = get_locale();
        if (strtolower(substr($language, 0, 2)) == 'fr') {
            $hub_link = '//ecommerce.envoimoinscher.com/solutions/woocommerce/?utm_source=woocommerce&utm_campaign=20161201_onboarding_fr&utm_medium=referral';
            $img = '/assets/img/logo_fr.png';
        } elseif (strtolower(substr($language, 0, 2)) == 'es') {
            $hub_link = '//ecommerce.boxtal.es/soluciones/woocommerce/?utm_source=woocommerce&utm_campaign=20161201_onboarding_es&utm_medium=referral';
            $img = '/assets/img/logo_oth.png';
        } else {
            $hub_link = '//www.boxtal.com/colis/?utm_source=woocommerce&utm_campaign=20161201_onboarding_en&utm_medium=referral';
            $img = '/assets/img/logo_oth.png';
        }

		?>
		<!DOCTYPE html>
		<html <?php language_attributes(); ?>>
		<head>
			<meta name="viewport" content="width=device-width" />
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			<title><?php _e( 'Boxtal &rsaquo; Setup Wizard', 'envoimoinscher' ); ?></title>
            <?php wp_print_scripts( 'emc-setup' ); ?>
            <?php do_action( 'admin_print_styles' ); ?>
			<?php do_action( 'admin_head' ); ?>
		</head>
		<body class="emc-setup">
			<h1 id="emc-logo"><a href="<?php echo $hub_link; ?>" target="_blank"><img src="<?php echo plugins_url( $img , EMC_PLUGIN_FILE ); ?>" alt="<?php _e('Boxtal', 'envoimoinscher'); ?>" /></a></h1>
		<?php
	}

	/**
	 * Setup Wizard Footer.
	 */
	public function setup_wizard_footer() {
		?>
			<?php if ( 'next_steps' === $this->step ) : ?>
				<a class="emc-return-to-dashboard" href="<?php echo esc_url( admin_url() ); ?>"><?php _e( 'Return to the WordPress Dashboard', 'envoimoinscher' ); ?></a>
			<?php endif; ?>
			</body>
		</html>
		<?php
	}

	/**
	 * Output the content for the current step.
	 */
	public function setup_wizard_content() {
		echo '<div class="emc-setup-content '.$this->step.'">';
		call_user_func( $this->steps[ $this->step ]['view'] );
		echo '</div>';
	}

	/**
	 * Introduction step.
	 */
	public function emc_setup_introduction() {
		?>
		<h1><?php _e( 'Your all-in-one shipping provider', 'envoimoinscher' ); ?></h1>
		<p><?php echo sprintf(__( '<strong>Up to 75%s</strong> immediate discount on your shipments', 'envoimoinscher' ), '%'); ?></p>
		<p><?php _e( 'No minimum volume, no contract', 'envoimoinscher' ); ?></p>
		<p><?php _e( '<strong>Easy and transparent</strong> package monitoring', 'envoimoinscher' ); ?></p>
		<p><?php _e( "<strong>1 dedicated customer service team</strong> answering your customers' needs and <strong>one single billing</strong> whichever carriers you choose, <strong>let Boxtal handle everything!</strong>", 'envoimoinscher' ); ?></p>
		<hr>
        <div id="img-operators">
            <table>
              <tr>
                <td><img src="<?php echo plugins_url( '/assets//img/carriers/logo-pofr.png' , EMC_PLUGIN_FILE ); ?>" class="laposte" /></td>
                <td><img src="<?php echo plugins_url( '/assets//img/carriers/logo-monr.png' , EMC_PLUGIN_FILE ); ?>" class="mondialrelay" /></td>
                <td><img src="<?php echo plugins_url( '/assets//img/carriers/logo-sogp.png' , EMC_PLUGIN_FILE ); ?>" class="relaiscolis" /></td>
                <td><img src="<?php echo plugins_url( '/assets//img/carriers/logo-chrp.png' , EMC_PLUGIN_FILE ); ?>" class="chronopost" /></td>
                <td><img src="<?php echo plugins_url( '/assets//img/carriers/logo-tnte.png' , EMC_PLUGIN_FILE ); ?>" class="tnt" /></td>
              </tr>
              <tr>
                <td><img src="<?php echo plugins_url( '/assets//img/carriers/logo-upse.png' , EMC_PLUGIN_FILE ); ?>" class="ups" /></td>
                <td><img src="<?php echo plugins_url( '/assets//img/carriers/logo-dhle.png' , EMC_PLUGIN_FILE ); ?>" class="dhl" /></td>
                <td><img src="<?php echo plugins_url( '/assets//img/carriers/logo-fedx.png' , EMC_PLUGIN_FILE ); ?>" class="fedex" /></td>
                <td><img src="<?php echo plugins_url( '/assets//img/carriers/logo-imxe.png' , EMC_PLUGIN_FILE ); ?>" class="happypost" /></td>
                <td><img src="<?php echo plugins_url( '/assets//img/carriers/logo-seur.png' , EMC_PLUGIN_FILE ); ?>" class="seur" /></td>
              </tr>
            </table>
        </div>
        <div class="emc-setup-actions step">
          <table>
            <tr>
              <td><a href="<?php echo esc_url( add_query_arg( 'step', 'account') ); ?>" class="button-primary button button-large button-next"><?php _e( 'Create a free account', 'envoimoinscher' ); ?></a></td>
              <td><a href="<?php echo esc_url( add_query_arg( 'step', 'keys') ); ?>" class="button-primary button button-large"><?php _e( 'I already have an account', 'envoimoinscher' ); ?></a></td>
            </tr>
          </table>
        </div>
		<?php
	}

	/**
	 * Account creation.
	 */
	public function emc_setup_account() {
        $language = get_locale();
        $iso = strtoupper(substr($language, 0, 2));
		?>
		<h1><?php _e( 'Account creation', 'envoimoinscher' ); ?></h1>
        <form method="post" id="EMC-account-creation">
            <h4><?php _e( 'Shipping country', 'envoimoinscher' ); ?></h4>
                <table class="form-table">
                    <tr>
                        <th scope="row"><label for="user-default_shipping_country"><?php _e( 'Country you will be shipping from', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
                        <td>
                            <select name="user-default_shipping_country">
                                <option value="FR" <?php if ($iso == 'FR') echo "selected"; ?>><?php _e('France', 'envoimoinscher'); ?></option>
                                <option value="ES" <?php if ($iso == 'ES') echo "selected"; ?>><?php _e('Spain', 'envoimoinscher'); ?></option>
                            </select>
                        </td>
                    </tr>
                </table>
            <h4><?php _e( 'Person to contact', 'envoimoinscher' ); ?></h4>
            <table>
				<tr>
					<th scope="row"><label for="facturation-contact_civ"></label></th>
					<td>
                        <input type="radio" name="facturation-contact_civ" checked="checked" value="M.">
                        <label for="facturation.contact_civ"><?php _e( 'Mr', 'envoimoinscher' ); ?></label>
                        <input type="radio" name="facturation-contact_civ" value="Mme">
                        <label for="facturation.contact_civ"><?php _e( 'Mrs', 'envoimoinscher' ); ?></label>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="facturation-contact_nom"><?php _e( 'Surname', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="facturation-contact_nom" value="">
                        <p class="facturation-contact_nom-error" style="display:none"></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="facturation-contact_prenom"><?php _e( 'First name', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="facturation-contact_prenom" value="">
                        <p class="facturation-contact_prenom-error" style="display:none"></p>
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="user-site-online"><?php _e( 'Is your website online?', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
                        <select name="user-site-online">
							<option value="0"><?php _e('No', 'envoimoinscher'); ?></option>
							<option value="1"><?php _e('Yes', 'envoimoinscher'); ?></option>
						</select>
					</td>
				</tr>
                <tr id="volumetrie" style="display:none">
					<th scope="row"><label for="user-volumetrie"><?php _e( 'What is your average shipping quantity?', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
                        <select name="user-volumetrie">
							<option value="1"><?php _e('less than 10', 'envoimoinscher'); ?></option>
							<option value="2"><?php _e('10 to 100', 'envoimoinscher'); ?></option>
							<option value="3"><?php _e('100 to 250', 'envoimoinscher'); ?></option>
							<option value="4"><?php _e('250 to 500', 'envoimoinscher'); ?></option>
							<option value="5"><?php _e('500 to 1000', 'envoimoinscher'); ?></option>
							<option value="6"><?php _e('1000 to 2000', 'envoimoinscher'); ?></option>
							<option value="7"><?php _e('2000 to 5000', 'envoimoinscher'); ?></option>
							<option value="8"><?php _e('5000 to 10000', 'envoimoinscher'); ?></option>
							<option value="9"><?php _e('more than 10000', 'envoimoinscher'); ?></option>
						</select>
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="user-partner_code"><?php _e( 'Partner code, if you have one', 'envoimoinscher' ); ?></label> <div class="emc-not-required"></div></th>
					<td>
						<input type="text" name="user-partner_code" value="">
                        <p class="user-partner_code-error" style="display:none"></p>
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="facturation-url"><?php _e( 'Your site URL', 'envoimoinscher' ); ?></label> <div class="emc-not-required"></div></th>
					<td>
						<input type="text" name="facturation-url" value="">
                        <p class="facturation-url-error" style="display:none"></p>
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="facturation-contact_email"><?php _e( 'Your email address', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="facturation-contact_email" value="">
                        <p class="facturation-contact_email-error" style="display:none"></p>
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="facturation-contact_email2"><?php _e( 'Confirm your email address', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="facturation-contact_email2" value="">
                        <p class="facturation-contact_email2-error" style="display:none"></p>
					</td>
				</tr>
			</table>
            <h4><?php _e( 'Your login', 'envoimoinscher' ); ?></h4>
            <table>
				<tr>
					<th scope="row"><label for="user-login"><?php _e( 'Login', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="user-login" value="">
                        <p class="user-login-error" style="display:none"></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="user-password"><?php _e( 'Password', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="password" name="user-password" value="">
                        <p class="user-password-error" style="display:none"></p>
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="user-confirm_password"><?php _e( 'Confirm your password', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="password" name="user-confirm_password" value="">
                        <p class="user-confirm_password-error" style="display:none"></p>
					</td>
				</tr>
			</table>
            <h4><?php _e( 'Your invoice address', 'envoimoinscher' ); ?></h4>
            <table>
				<tr>
					<th scope="row"><label for="facturation-contact_ste"><?php _e( 'Company/Organisation', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="facturation-contact_ste" value="">
                        <p class="facturation-contact_ste-error" style="display:none"></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="facturation-adresse1"><?php _e( 'Address line 1', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="facturation-adresse1" value="">
                        <p class="facturation-adresse1-error" style="display:none"></p>
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="facturation-adresse2"><?php _e( 'Address line 2', 'envoimoinscher' ); ?></label> <div class="emc-not-required"></div></th>
					<td>
						<input type="text" name="facturation-adresse2" value="">
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="facturation-adresse3"><?php _e( 'Address line 3', 'envoimoinscher' ); ?></label> <div class="emc-not-required"></div></th>
					<td>
						<input type="text" name="facturation-adresse3" value="">
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="facturation-pays_iso"><?php _e( 'Country', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
                        <?php
                            if(method_exists(WC()->countries, 'get_countries')) {
                                $display_countries =  WC()->countries->get_countries();
                            } else {
                                $display_countries =  WC()->countries->countries;
                            }
                        ?>
                        <select id="pays_iso" name="facturation-pays_iso">
                            <?php
                                foreach ($display_countries as $c => $country) {
                                    echo '<option value="'.$c.'" ';
                                    if ($c == $iso || ($iso == 'EN' && $c == "GB")) {
                                        echo 'selected="selected"';
                                    }
                                    echo '>'.$country.'</option>';
                                }
                            ?>
						</select>
					</td>
				</tr>
                <tr style="display:none" id="contact_etat">
					<th scope="row"><label for="facturation-contact_etat"><?php _e( 'State', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
                        <select name="facturation-contact_etat"></select>
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="facturation-codepostal"><?php _e( 'ZIP code', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="facturation-codepostal" value="">
                        <p class="facturation-codepostal-error" style="display:none"></p>
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="facturation-ville"><?php _e( 'City', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="facturation-ville" value="">
                        <p class="facturation-ville-error" style="display:none"></p>
					</td>
				</tr>
                <tr>
					<th scope="row"><label for="facturation-contact_tel"><?php _e( 'Phone', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="facturation-contact_tel" value="">
                        <p class="facturation-contact_tel-error" style="display:none"></p>
					</td>
				</tr>
                <tr>
                    <th scope="row"><label for="facturation-contact_locale"><?php _e( 'Preferred language of correspondance?', 'envoimoinscher' ); ?></label> <div class="emc-not-required"></div></th>
                    <td>
                        <select name="facturation-contact_locale">
                            <option value="fr_FR" <?php if ($language == 'fr_FR') echo "selected"; ?>><?php _e('French', 'envoimoinscher'); ?></option>
                            <option value="en_US" <?php if ($language == 'en_US') echo "selected"; ?>><?php _e('English', 'envoimoinscher'); ?></option>
                            <option value="es_ES" <?php if ($language == 'es_ES') echo "selected"; ?>><?php _e('Spanish', 'envoimoinscher'); ?></option>
                        </select>
                    </td>
                </tr>
                <tr id="defaut_enl">
                    <td><input type="checkbox" name="facturation-defaut_enl" checked> <div class="emc-not-required"></div></td>
					<td>
                        <label for="facturation-defaut_enl"><?php _e( 'Make this address my default pickup address', 'envoimoinscher' ); ?></label>
					</td>
                </tr>
            </table>
            <h4><?php _e( 'Professional account', 'envoimoinscher' ); ?></h4>
            <table>
				<tr>
					<th scope="row"><label for="facturation-contact_stesiret"><?php _e( 'SIRET', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="facturation-contact_stesiret" value="">
                        <p class="facturation-contact_stesiret-error" style="display:none"></p>
					</td>
				</tr>
				<tr id="tva">
					<th scope="row"><label for="facturation-contact_tvaintra"><?php _e( 'Intra-community VAT No.', 'envoimoinscher' ); ?></label> <div class="emc-not-required"></div></th>
					<td>
						<input type="text" name="facturation-contact_tvaintra" value="">
					</td>
				</tr>
			</table>
            <h4><?php _e( 'Legal notes', 'envoimoinscher' ); ?></h4>
            <table>
				<tr>
					<td>
                        <?php
                            if ($iso == 'FR') {
                                $site_cgv = "http://www.boxtal.com/cgv.html";
                                $api_cgv = "//www.envoimoinscher.com/additional_documents/cgvu_api.pdf";
                            } elseif ($iso == 'ES') {
                                $site_cgv = "http://www.boxtal.es/cgv.html";
                                $api_cgv = "//www.boxtal.es/additional_documents/cgvu_api.pdf";
                            } else {
                                $site_cgv = "http://ecommerce.envoimoinscher.com/cgvu/";
                                $api_cgv = "//www.envoimoinscher.com/additional_documents/cgvu_api.pdf";
                            }
                        ?>
                        <input type="checkbox" name="cgv">
                        <label for="cgv"><?php echo sprintf(__( 'I acknowledge having read the <a href="%1$s" target="_blank">General Terms and Conditions of Sale and of Use of the Boxtal.com website</a> and the <a href="%2$s" target="_blank">General Terms and Conditions of Use of the Boxtal.com API</a> in full and agree to the terms thereof', 'envoimoinscher' ), $site_cgv, $api_cgv); ?></label>
                        <p class="cgv-error" style="display:none"></p>
                    </td>
                </tr>
                <tr>
					<td>
                        <input type="checkbox" name="newsletterEmc">
                        <label for="newsletterEmc"><?php _e( 'I wish to receive information regarding Boxtal.com news', 'envoimoinscher' ); ?></label>
					</td>
                </tr>
            </table>
            <div class="emc-setup-actions step">
                <a href="<?php echo esc_url( add_query_arg( 'step', 'introduction') ); ?>" class="button-secondary button button-large button-next"><?php _e( 'Back to previous step', 'envoimoinscher' ); ?></a>
                <a href="<?php echo esc_url( add_query_arg( 'step', 'next_steps') ); ?>" class="button-secondary button button-large"><?php _e( 'Skip this step', 'envoimoinscher' ); ?></a>
                <input type="submit" id="emc-submit-account" class="button-primary button button-large" value="<?php esc_attr_e( 'Create an account', 'envoimoinscher' ); ?>" name="save_step" />
                <div id="loading-animation" style="display:none"><img src="<?php echo plugins_url('/assets/img/loading.gif', EMC_PLUGIN_FILE); ?>" /><?php _e( 'Please wait', 'envoimoinscher' ); ?></div>
                <?php wp_nonce_field( 'emc-setup' ); ?>
            </div>
		</form>
		<?php
	}

	/**
	 * Account creation process.
	 */
	public function emc_setup_account_save() {
		check_admin_referer( 'emc-setup' );

        $login = sanitize_text_field( $_POST['user-login'] );
		update_option( 'EMC_LOGIN', $login );

        $pwd = sanitize_text_field( $_POST['user-password'] );
		update_option( 'EMC_PASS', $pwd );

        // add default address if checkbox is checked
        if ($_POST['facturation-defaut_enl'] == 'on') {
            global $wpdb;
            // if there is no default address, insert, else update
            if (envoimoinscher_model::has_default_address() === false) {
                $result = $wpdb->insert(
                    $wpdb->prefix.'emc_addresses',
                    array(
                        'type' => 'default',
                        'active' => 1,
                        'label' => sanitize_text_field( $_POST['facturation-contact_ste'] ),
                        'gender' => (isset($_POST['facturation-contact_civ']) && $_POST['facturation-contact_civ'] == "Mme") ? "Mme" : "M",
                        'first_name' => sanitize_text_field( $_POST['facturation-contact_prenom'] ),
                        'last_name' => sanitize_text_field( $_POST['facturation-contact_nom'] ),
                        'company' => sanitize_text_field( $_POST['facturation-contact_ste'] ),
                        'address' => sanitize_text_field( $_POST['facturation-adresse1'] ).' '.sanitize_text_field( $_POST['facturation-adresse2'] ).' '.sanitize_text_field( $_POST['facturation-adresse3'] ),
                        'zipcode' => sanitize_text_field( $_POST['facturation-codepostal'] ),
                        'city' => sanitize_text_field( $_POST['facturation-ville'] ),
                        'phone' => sanitize_text_field( $_POST['facturation-contact_tel'] ),
                        'email' => sanitize_text_field( $_POST['facturation-contact_email'] ),
                        'add_info' => '',
                        'dispo_hde' => '12:00',
                        'dispo_hle' => '17:00',
                        'pickup_day_1' => '2',
                        'pickup_day_2' => '3',
                        'pickup_split' => '17',
                        'shipping_classes' => "",
                        'dropoff_points' => 'a:0:{}',
                    ),
                    array(
                        '%s',
                        '%d',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%d',
                        '%d',
                        '%d',
                        '%s',
                        '%s',
                    )
                );
                if (false == $result) {
                    $notice = array(
                        'type' => "simple-notice",
                        'status' => 'failure',
                        'message' => 'There was a problem creating your default address.',
                        'autodestruct' => 1
                    );
                    emc_admin_notices::add_custom_notice('address_create_fail', $notice);
                }
            } else {
                // get default address id
                $default_address = self::get_addresses("default", true);
                $default_address = current($default_address);
                $default_address_id = $default_address['id'];

                $result = $wpdb->update(
                    $wpdb->prefix.'emc_addresses',
                    array(
                        'type' => 'default',
                        'active' => 1,
                        'label' => sanitize_text_field( $_POST['facturation-contact_ste'] ),
                        'gender' => (isset($_POST['facturation-contact_civ']) && $_POST['facturation-contact_civ'] == "Mme") ? "Mme" : "M",
                        'first_name' => sanitize_text_field( $_POST['facturation-contact_prenom'] ),
                        'last_name' => sanitize_text_field( $_POST['facturation-contact_nom'] ),
                        'company' => sanitize_text_field( $_POST['facturation-contact_ste'] ),
                        'address' => sanitize_text_field( $_POST['facturation-adresse1'] ).' '.sanitize_text_field( $_POST['facturation-adresse2'] ).' '.sanitize_text_field( $_POST['facturation-adresse3'] ),
                        'zipcode' => sanitize_text_field( $_POST['facturation-codepostal'] ),
                        'city' => sanitize_text_field( $_POST['facturation-ville'] ),
                        'phone' => sanitize_text_field( $_POST['facturation-contact_tel'] ),
                        'email' => sanitize_text_field( $_POST['facturation-contact_email'] ),
                        'add_info' => '',
                        'dispo_hde' => '12:00',
                        'dispo_hle' => '17:00',
                        'pickup_day_1' => '2',
                        'pickup_day_2' => '3',
                        'pickup_split' => '17',
                    ),
                    array(
                        'id' => $default_address_id,
                    ),
                    array(
                        '%s',
                        '%d',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%d',
                        '%d',
                        '%d',
                    ),
                    array(
                        '%d'
                    )
                );
                if ($result === false) {
                    $notice = array(
                        'type' => "simple-notice",
                        'status' => 'failure',
                        'message' => 'There was a problem updating your default address.',
                        'autodestruct' => 1
                    );
                    emc_admin_notices::add_custom_notice('address_update_fail', $notice);
                }
            }
        }

        wp_redirect( esc_url_raw( add_query_arg( 'step', 'next_steps') ) );
		exit;
	}

	/**
	 * API keys generation.
	 */
	public function emc_setup_keys() {
        $language = get_locale();
        $iso = strtoupper(substr($language, 0, 2));
		?>
		<h1><?php _e( 'API keys generation', 'envoimoinscher' ); ?></h1>
        <form method="post" id="EMC-api-keys">
            <h4><?php _e( 'General information', 'envoimoinscher' ); ?></h4>
            <table>
                <tr>
					<th scope="row"><label for="user-site-online"><?php _e( 'Is your website online?', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
                        <select name="user-site-online">
							<option value="0"><?php _e('No', 'envoimoinscher'); ?></option>
							<option value="1"><?php _e('Yes', 'envoimoinscher'); ?></option>
						</select>
					</td>
				</tr>
                <tr id="volumetrie" style="display:none">
					<th scope="row"><label for="user-volumetrie"><?php _e( 'What is your average shipping quantity?', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
                        <select name="user-volumetrie">
							<option value="1"><?php _e('less than 10', 'envoimoinscher'); ?></option>
							<option value="2"><?php _e('10 to 100', 'envoimoinscher'); ?></option>
							<option value="3"><?php _e('100 to 250', 'envoimoinscher'); ?></option>
							<option value="4"><?php _e('250 to 500', 'envoimoinscher'); ?></option>
							<option value="5"><?php _e('500 to 1000', 'envoimoinscher'); ?></option>
							<option value="6"><?php _e('1000 to 2000', 'envoimoinscher'); ?></option>
							<option value="7"><?php _e('2000 to 5000', 'envoimoinscher'); ?></option>
							<option value="8"><?php _e('5000 to 10000', 'envoimoinscher'); ?></option>
							<option value="9"><?php _e('more than 10000', 'envoimoinscher'); ?></option>
						</select>
					</td>
				</tr>
            </table>
            <h4><?php _e( 'Boxtal credentials', 'envoimoinscher' ); ?></h4>
            <table>
				<tr>
					<th scope="row"><label for="user-login"><?php _e( 'Login', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="text" name="user-login" value="">
                        <p class="user-login-error" style="display:none"></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="user-password"><?php _e( 'Password', 'envoimoinscher' ); ?></label> <sup class="emc-required">*</sup></th>
					<td>
						<input type="password" name="user-password" value="">
                        <p class="user-password-error" style="display:none"></p>
					</td>
				</tr>
			</table>
            <h4><?php _e( 'Legal notes', 'envoimoinscher' ); ?></h4>
            <table>
				<tr>
					<td>
                        <?php
                            if ($iso == 'FR') {
                                $api_cgv = "//www.envoimoinscher.com/additional_documents/cgvu_api.pdf";
                            } elseif ($iso == 'ES') {
                                $api_cgv = "//www.boxtal.es/additional_documents/cgvu_api.pdf";
                            } else {
                                $api_cgv = "//www.envoimoinscher.com/additional_documents/cgvu_api.pdf";
                            }
                        ?>
                        <input type="checkbox" name="cgv">
                        <label for="cgv"><?php echo sprintf(__( 'I acknowledge having read the <a href="%1$s" target="_blank">General Terms and Conditions of Use of the Boxtal.com API</a> in full and agree to the terms thereof', 'envoimoinscher' ), $api_cgv); ?></label>
                        <p class="cgv-error" style="display:none"></p>
                    </td>
                </tr>
            </table>
            <div class="emc-setup-actions step">
                <a href="<?php echo esc_url( add_query_arg( 'step', 'introduction') ); ?>" class="button-secondary button button-large"><?php _e( 'Back to previous step', 'envoimoinscher' ); ?></a>
                <a href="<?php echo esc_url( add_query_arg( 'step', 'next_steps') ); ?>" class="button-secondary button button-large"><?php _e( 'Skip this step', 'envoimoinscher' ); ?></a>
                <input type="submit" id="emc-generate-keys" class="button-primary button button-large" value="<?php esc_attr_e( 'Get API keys', 'envoimoinscher' ); ?>" name="save_step" />
                <div id="loading-animation" style="display:none"><img src="<?php echo plugins_url('/assets/img/loading.gif', EMC_PLUGIN_FILE); ?>" /><?php _e( 'Please wait', 'envoimoinscher' ); ?></div>
                <?php wp_nonce_field( 'emc-setup' ); ?>
            </div>
		</form>
		<?php
	}

	/**
	 * API keys generation process.
	 */
	public function emc_setup_keys_save() {
		check_admin_referer( 'emc-setup' );

		$login = sanitize_text_field( $_POST['user-login'] );
		update_option( 'EMC_LOGIN', $login );

        $pwd = sanitize_text_field( $_POST['user-password'] );
		update_option( 'EMC_PASS', $pwd );

        wp_redirect( esc_url_raw( add_query_arg( 'step', 'next_steps') ) );
		exit;
	}

	/**
	 * Final step.
	 */
	public function emc_setup_ready() {
		emc_admin_notices::remove_notice( 'install' );
		?>
		<h1><?php _e( 'Congratulations!', 'envoimoinscher' ); ?></h1>
        <p><?php _e( 'You can now start configuring your delivery options.', 'envoimoinscher' ); ?></p>

        <h4><?php _e( 'Next Steps', 'envoimoinscher' ); ?></h4>
		<div class="emc-setup-next-steps">
            <ul>
                <?php if (!envoimoinscher_model::has_default_address()) : ?>
                    <li><a href="<?php echo esc_url( admin_url( '/admin.php?page=envoimoinscher-settings&tab=account' ) ); ?>"><?php _e( 'Add a default shipping address', 'envoimoinscher' ); ?></a></li>
                <?php endIf; ?>
                <li><a href="<?php echo esc_url( admin_url( '/admin.php?page=envoimoinscher-settings&tab=shipping-description' ) ); ?>"><?php _e( 'Detail your content type', 'envoimoinscher' ); ?></a></li>
                <li><a href="<?php echo esc_url( admin_url( '/admin.php?page=envoimoinscher-settings&tab=carriers' ) ); ?>"><?php _e( 'Update your carrier list and choose your carriers', 'envoimoinscher' ); ?></a></li>
            </ul>
		</div>
		<?php
	}
}

new emc_admin_setup_wizard();
