<?php
class PageFmConfirmMigratedUser extends CDController{

  private static $user_data_key = 'field_5cd1ded13b283';

  public function __construct() {

    CDAjaxHandler::localize_js_object(
      'creativedog_timber_theme-main',
      'handle_confirm_migrated_user_controller_object',
      'page_fm_confirm_migrated_user',
      'handle_confirmation'
    );

    $this->view = 'fm/page/confirm-migrated-user.twig';

    $this->access();
  }

  private function access(){
    if(!is_user_logged_in()){
      wp_redirect( home_url() );
      exit;
    }else{
      $user_data = get_field('user_data', 'user_'.get_current_user_id());
      if($user_data['old_user'] == true){
        return true;
      }else{
        wp_redirect( home_url() );
        exit;
      }
    }
  }


  public function get_context(){

    $this->data = CDTimber::get_context();

    $country_field = get_field_object('field_5cd1e112c2eb9');
    $country_choices = $country_field['choices'];

    $this->data['form']['country_choices'] = $country_choices;

    $company_area_field = get_field_object('field_5cd1e450ac3dc');
    $company_area_choices = $company_area_field['choices'];

    $this->data['form']['company_area_choices'] = $company_area_choices;

  }

  public static function ajax_priv_handle_confirmation(){
    check_ajax_referer( 'handle_confirmation', '_nonce' );

    $user = wp_get_current_user();

    $user_data = $_POST['user_data'];

    $user_id = $user->ID;

    if($user_id && isset($user_data['password']) && $user_data['password'] != '' ){

      wp_set_password( $user_data['password'], $user_id );

      $creds = array(
          'user_login'    => $user->data->user_email,
          'user_password' => $user_data['password'],
          'remember'      => true
      );

      $logged = wp_signon( $creds, false );

      unset( $user_data['password'] );
      unset( $user_data['repeat_password'] );
      $user_data['old_user'] =  false;

      update_field(self::$user_data_key, $user_data, 'user_'.$user_id);
      $response = array( 'success' => true, 'redirect' => get_home_url() );
    }else{
      $response = array( 'error' => true, 'message' => 'Ha habido un error en los datos proporcionados.');
    }

    echo json_encode($response);
    exit();
  }

}
