<?php
/**
 * EMC Account Settings
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

if ( ! class_exists( 'emc_settings_account' ) ) :

/**
 * emc_settings_accounts
 */
class emc_settings_account extends emc_admin_settings {

   /**
    * Constructor.
    */
    public function __construct() {
        $this->id = 'account';
		$this->label = __( 'My Account', 'envoimoinscher' );
        add_filter( 'emc_settings_tabs_array', array( &$this, 'add_tab' ), 20 );
	}

	/**
	 * Get settings array
	 * @param $memory_limit limit ressources usage (for activation only)
	 * @return array
	 */
	public function get_settings($memory_limit = false) {

        $settings = array(
            0 => array(
                'section_id' => 'api_account_options',
                'section_title' => __( 'API account', 'envoimoinscher' ),
                'fields' => array(
                    0 => array(
                        'title' => __( 'Login *', 'envoimoinscher' ),
                        'desc' => __( 'Boxtal.com login', 'envoimoinscher' ),
                        'id' => 'EMC_LOGIN',
                        'type' => 'text',
                        'default' => '',
                        'placeholder' => __( 'login', 'envoimoinscher'),
                        'desc_tip' => true,
                        'required' => true,
                    ),
                    1 => array(
                        'title' => __( 'Password *', 'envoimoinscher' ),
                        'desc' => __( 'Boxtal.com password', 'envoimoinscher' ),
                        'id' => 'EMC_PASS',
                        'type' => 'password',
                        'default' => '',
                        'placeholder' => __( 'password', 'envoimoinscher'),
                        'desc_tip' => true,
                        'required' => true,
                    ),
                    2 => array(
                        'title' => __( 'API keys', 'envoimoinscher' ),
                        'desc' => __( 'Keys used to communicate with our API', 'envoimoinscher' ),
                        'id' => 'EMC_KEYS',
                        'type' => 'api_keys',
                        'desc_tip' => true,
                    ),
                    3 => array(
                        'title' => __( 'Environment *', 'envoimoinscher' ),
                        'id' => 'EMC_ENV',
                        'default' => 'test',
                        'type' => 'radio_inline',
                        'options' => array(
                            'test' => __( 'Test', 'envoimoinscher' ),
                            'prod' => __( 'Live', 'envoimoinscher' ),
                        ),
                        'desc_tip' => false,
                        'autoload' => true,
                        'inline' => true,
                        'required' => true,
                    ),
                ),
            ),
            1 => array(
                'section_id' => 'pickup_address_options',
                'section_title' => __( 'Pickup address', 'envoimoinscher' ),
                'fields' => array(
                    0 => array(
                        'title' => __( 'Pickup address(es) *', 'envoimoinscher' ),
                        'desc' => __( 'Input your shipping addresses here', 'envoimoinscher' ),
                        'id' => 'EMC_ADDRESSBOOK',
                        'default' => array(),
                        'type' => 'custom_address',
                        'desc_tip' =>  true,
                        'autoload' => false,
                    ),
                ),
            ),
            2 => array(
                'section_id' => 'emails_parameters',
                'section_title' => __( 'Mails to send / receive', 'envoimoinscher' ),
                'fields' => array(
                    0 => array(
                        'title' => __( 'Waybill mail', 'envoimoinscher' ),
                        'desc' => __( 'Sent to sender (you). This mail contain shipping instructions: waybill(s).', 'envoimoinscher' ),
                        'id' => 'EMC_mail_label',
                        'type' => 'checkbox',
                        'default' => 'yes',
                        'desc_tip' => true,
                    ),
                    1 => array(
                        'title' => __( 'Recipient notification mail', 'envoimoinscher' ),
                        'desc' => __( 'Sent to recipient (your customer). He will be notified that a parcel is sent by Boxtal and not the carrier.', 'envoimoinscher' ),
                        'id' => 'EMC_mail_notif',
                        'type' => 'checkbox',
                        'default' => 'no',
                        'desc_tip' => true,
                    ),
                    2 => array(
                        'title' => __( 'Billing mail', 'envoimoinscher' ),
                        'desc' => __( 'Sent to billing adress, as your Boxtal profile. Sends you your bill for sent orders.', 'envoimoinscher' ),
                        'id' => 'EMC_mail_bill',
                        'type' => 'checkbox',
                        'default' => 'yes',
                        'desc_tip' => true,
                    ),
                ),
            ),
        );

		return $settings;
	}

    /**
	* Output popups
	*/
	public function output() {
        parent::output();
		?>
            <!-- payment method warning popup -->
            <div style="display:none">
                <div id="payment-method-popup">
                    <div class="center">
                        <span class="s14">
                            <?php
                                if (get_option('EMC_COUNTRY') == "ES") {
                                    $site = 'Boxtale.es';
                                    $link = "http://www.boxtal.es/cuentas/mis_preferencias.html#paiement";
                                } else {
                                    $language = get_locale();
                                    if (strtolower(substr($language, 0, 2)) == 'fr') {
                                        $site = 'EnvoiMoinsCher.com';
                                        $link = "http://www.envoimoinscher.com/comptes/mes_preferences.html#paiement";
                                    } else {
                                        $site = 'Boxtal.com';
                                        $link = "http://www.boxtal.com/comptes/mes_preferences.html#paiement";
                                    }
                                }
                                echo sprintf(__( 'In order to use the plugin in production mode, you need to activate differed payment by direct debit in your %1$s account, "My Preferences" tab.', 'envoimoinscher' ), $site);
                            ?>
                        </span>
                        <br/><br/>

                        <a class="button-primary mr5" href="<?php echo $link; ?>" target="_blank"><?php _e( 'Activate differed payment', 'envoimoinscher' ); ?></a>
                        <button class="button-secondary mr5"><?php _e( 'Skip', 'envoimoinscher' ); ?></button>
                    </div>
                </div>
            </div>
        <?php
	}

    /**
	 * Output api_keys field.
	 *
	 * @param $field
	 */
	public function output_api_keys_field($field) {
        if (!get_option('EMC_KEY_TEST') && !get_option('EMC_KEY_PROD')) {
            return;
        }
        ?>
        <tr valign="top">
            <th scope="row" class="titledesc">
                <label for="<?php echo esc_attr( $field['id'] ); ?>"><?php echo esc_html( $field['title'] ); ?></label>
                <?php echo $field['tooltip_html']; ?>
            </th>
            <td class="forminp forminp-<?php echo sanitize_title( $field['type'] ) ?>">
                <?php echo $field['description']; ?>
                <?php
                    if (get_option('EMC_KEY_TEST') !== false) {
                        echo '<p>'.get_option('EMC_KEY_TEST').' '.__('(test)', 'envoimoinscher').'</p>';
                    }
                    if (get_option('EMC_KEY_PROD') !== false) {
                        echo '<p>'.get_option('EMC_KEY_PROD').' '.__('(live)', 'envoimoinscher').'</p>';
                    }
                ?>
            </td>
        </tr>
        <?php
    }

    /**
	 * Output custom_address field.
	 *
	 * @param $field
	 */
	public function output_custom_address_field($field) {
        require_once(WP_PLUGIN_DIR.'/envoimoinscher/includes/admin/views/html-admin-address-table.php');
    }

	/**
	 * Save account options.
     * For e-mail configuration for logged user, accepted keys are : label, notification, bill.
     * If you want to remove the e-mail sending for one of these keys, you must put into it an empty string like "".
     * @access public
     * @return Void
	 */
	public function save(){

        parent::save();

        if( isset( $_POST ) && ! empty( $_POST ) ) {
            $new_emails_params = array(
                'label' => ! empty( $_POST['EMC_mail_label'] ) ? '1' : '',
                'notification' => ! empty( $_POST['EMC_mail_notif'] ) ? '1' : '',
                'bill' => ! empty( $_POST['EMC_mail_bill'] ) ? '1' : ''
            );

            $user_class = new Emc\User();
            $user_class->setPlatformParams(EMC_PLATFORM, WC_VERSION, EMC_VERSION);
            $user_class->setEnv('prod');
            $user_class->setKey(get_option('EMC_KEY_PROD'));
            $language = get_locale();
            $user_class->setLocale(str_replace('_', '-', $language));
            $upload_dir = wp_upload_dir();
            $user_class->setUploadDir($upload_dir['basedir']);
            $user_class->postEmailConfiguration($new_emails_params);

            $new_emails_params['label'] == '1' ? $label = 'yes' : $label = 'no';
            $new_emails_params['notification'] == '1' ? $notification = 'yes' : $notification = 'no';
            $new_emails_params['bill'] == '1' ? $bill = 'yes' : $bill = 'no';

            update_option( 'EMC_mail_label', $label );
            update_option( 'EMC_mail_notif', $notification );
            update_option( 'EMC_mail_bill', $bill );
        }
	}

    /**
	 * Saves custom address field (saves only parcel points, since address info is saved through AJAX).
	 *
	 * @param $field
	 */
	public function save_custom_address_field ($field) {
        if( isset( $_POST ) && ! empty( $_POST ) ) {
            $addressbook = envoimoinscher_model::get_addresses("all", true);
            if (!empty($addressbook)) {
                global $wpdb;
                foreach ($addressbook as $address) {
                    $dropoff_points = array();
                    foreach ($_POST as $key => $value) {
                        if (strpos($key, 'PP-'.$address['id'].'-') === 0) {
                            $dropoff_points[str_replace('PP-'.$address['id'].'-', '', $key)] = $value;
                        }
                    }
                    $wpdb->update(
                        $wpdb->prefix.'emc_addresses',
                        array(
                            'dropoff_points' => serialize($dropoff_points),
                        ),
                        array(
                            'id' => $address['id'],
                        ),
                        array(
                            '%s'
                        ),
                        array(
                            '%d'
                        )
                    );
                }
            }
        }
	}

}

endif;
