
<?php
class PageFmSubscription extends CDController{

  private static $user_data_key = 'field_5cd1ded13b283';

  public function __construct() {

    CDAjaxHandler::localize_js_object(
      'creativedog_timber_theme-main',
      'handle_subscription_controller_object',
      'page_fm_subscription',
      'handle_subscription'
    );

    $this->view = 'fm/page/subscription.twig';
  }

  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;

    $employees_quantity_field = get_field_object('field_5cd1e5d727408');
    $employees_quantity_choices = $employees_quantity_field['choices'];

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

  }

  public static function ajax_nopriv_handle_subscription(){
    check_ajax_referer( 'handle_subscription', '_nonce' );

    $subscribe_creation = self::create_subscriber($_POST['user_data']);

    if(  !is_wp_error( $subscribe_creation )  ){
      $is_sent = self::send_welcome_notification($_POST['user_data']);
      $option_pages = get_field('option_pages', 'option');
      $redirect = $option_pages['thank_you_pages']['subscription'];
      $response = array( 'success' => true, 'redirect' => $redirect  );
    }else{
      $response = array( 'error' => true, 'message' => $subscribe_creation->get_error_message());
    }

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

  private static function create_subscriber($data){

    if ( !email_exists( $data['email'] ) ) {

      $insert_user_data = array(
        'user_login'  => $data['email'],
        'user_email'  => $data['email'],
        'user_pass'   => $data['password'],
        'role' => 'subscriber'
      );

      $user_id = wp_insert_user( $insert_user_data );


      if( !is_wp_error( $user_id ) ){

        unset($data['password']);

        unset($data['repeat_password']);

        $data['old_user'] = false;

        update_field(self::$user_data_key, $data, 'user_'.$user_id);

        $response = true;

      }else{
        $response = new WP_Error( 'validation', 'Ha habido un error al crear el usuario, revise los datos e inténtelo de nuevo.'  );
      }
    }else{
      $response = new WP_Error( 'validation', 'Este email ya se encuentra registrado.'  );
    }

    return $response;
  }


  private static function send_welcome_notification($user_data){

    $notification = new Notification();

    $is_sent = $notification->newSubscriber($user_data);

    return $is_sent;
  }


}
