<?php
class FormFmLogin extends CDController{

  public function __construct() {
    $this->view = 'fm/partials/forms/form-login.twig';

    CDAjaxHandler::localize_js_object(
      'creativedog_timber_theme-main',
      'login_controller_object',
      'form_fm_login',
      'login',
      array('post_login_action' => 'refresh')
    );


  }


  public static function ajax_login(){
    check_ajax_referer( 'login', '_nonce' );

    $password = $_POST['password'];
  	$email = $_POST['email'];

  	if($password != '' && $email != ''){
  		$credentials = array(
        'user_login'    => $email,
        'user_password' => $password,
        'remember'      => true
      );
  		$user = wp_signon( $credentials, false );

      if( !is_wp_error($user) ){

        $response = array( "success" => true );

        $user_data = get_field('user_data', 'user_'.$user->ID);

        if( $user_data['old_user'] == true ){
          $option_pages = get_field('option_pages', 'option');
          $redirect = $option_pages['user_pages']['confirm_user'];
          $response['redirect'] = $redirect;
        }else{
          $response['refresh'] = true;
        }

        echo json_encode( $response );
        exit();
  		}else{
  			echo json_encode(
  				array(
  					"error" => true,
  					"message" => 'Email y/o contraseña incorrectos.',
  				)
  			);
  			exit();
  		}
  	}else{
  		echo json_encode(
  			array(
  				"error" => true,
  				"message" => 'Por favor, ingrese su email y contraseña.'
  			)
  		);
  		exit();
  	}
  }

}
