<?php

class multiloca_menu_helper{

    public function __construct()
    {
        add_action('init', array($this, 'init_multiloca_menu'));
    }

    public function init_multiloca_menu()
    {
		    add_action('admin_footer', array($this, 'multiloca_users_ajax_sync_script'));
        add_action('wp_ajax_save_multiloca_menu_options', array($this, 'multiloca_menu_options_save'));
        add_action('wp_ajax_remove_multiloca_menu_options', array($this, 'multiloca_menu_options_remove'));
        add_action('wp_ajax_save_wcmlim_distance_unit', array($this, 'save_wcmlim_distance_unit'));

    }

    public function save_wcmlim_distance_unit() {

      if (!current_user_can('manage_options')) {
          wp_send_json_error(__('Unauthorized.', 'wcmlim'));
          wp_die();
      }
      

      if (isset($_POST['distance_unit'])) {
        $distance_unit = sanitize_text_field($_POST['distance_unit']);
        $allowed_units = array('km', 'miles'); // adjust as per allowed units
    
        if (!in_array($distance_unit, $allowed_units, true)) {
            wp_send_json_error(__('Invalid distance unit.', 'wcmlim'));
            wp_die();
        }
    
        update_option('wcmlim_location_distance_unit', $distance_unit);
        wp_send_json_success(__('Distance unit saved successfully.', 'wcmlim'));
      } else {
        wp_send_json_error(__('Invalid request.', 'wcmlim'));
      }
      wp_die();
    }

	public function multiloca_users_ajax_sync_script()
	{

		$js_file_url = plugins_url('', __FILE__) . '/js/multiloca.js';


		wp_enqueue_script('multiloca-js', $js_file_url, array('jquery'), '1.0', true);

		wp_localize_script('multiloca-js', 'multilocaMenuNonce', array(
			'userurl' => admin_url('admin-ajax.php'),
			'usernonce' => wp_create_nonce('multiloca_users_ajax_nonce'),
		));


	}


    public function multiloca_menu_options_save()
    {

      check_ajax_referer('multiloca_users_ajax_nonce', 'nonce');

      if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error([
            'message' => 'Unauthorized access',
        ], 403);
        return;
      }

        $wcmlim_email = isset($_POST['wcmlim_email']) ? sanitize_email($_POST['wcmlim_email']) : '';
        $purchase_code = isset($_POST['purchase_code']) ? sanitize_text_field($_POST['purchase_code']) : '';

        update_option('wcmlim_email', $wcmlim_email);
        update_option('purchase_code', $purchase_code);

        // Obfuscate the purchase code for frontend display
        $obfuscated_code = substr($purchase_code, 0, -3) . '***';
        update_option('obfuscated_purchase_code', $obfuscated_code);
      

        $domain = get_option('siteurl');

        $response = $this->multiloca_verify_purchase_code($wcmlim_email, $purchase_code, $domain);


         wp_send_json([
           
            'purchase_code' => $obfuscated_purchase_code,
        ]);

    }


   

    public function multiloca_menu_options_remove() {

      check_ajax_referer('multiloca_users_ajax_nonce', 'nonce');

        if ( ! current_user_can( 'manage_options' ) ) {
          wp_send_json_error([
              'message' => 'Unauthorized access',
          ], 403);
          return;
        }

        update_option('wcmlim_license','invalid');
        update_option('wcmlim_email','');
        update_option('purchase_code','');

    }

    public function multiloca_verify_purchase_code($wcmlim_email, $purchase_code, $domain){


        $json_array = array(
            "purchase_code" => $purchase_code,
            "wcmlim_email" => $wcmlim_email,
            "domain" => $domain,
            "email" => $wcmlim_email
          );
       

          $json_format = json_encode($json_array);
       
          $curl = curl_init();
          curl_setopt_array($curl, array(
            CURLOPT_URL => "https://verify.techspawn.com/wp-json/my-route/verify/",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $json_format,
            CURLOPT_HTTPHEADER => array(
              "accept: application/json",
              "content-type: application/json"
            ),
          ));

          $response = curl_exec($curl);
         
          
          $err = curl_error($curl);
          curl_close($curl);
         

          if ($err) {
            $message = "Invalid Email Or Purchase Code";
            
          } 

          
          
          $response_arr = json_decode($response);
        
          if ($response_arr->result == 1) {
            $message = "Your License Code Has Been Validated. Thank you for your purchase.";
            update_option('wcmlim_license','valid');
            update_option('wcmlim_email',$wcmlim_email);
            update_option('purchase_code',$purchase_code);

            $obfuscated_purchase_code = substr($purchase_code, 0, -3) . '***';
            update_option('obfuscated_purchase_code', $obfuscated_purchase_code); // Save obfuscated code to options

          $response_arr->obfuscated_purchase_code = $obfuscated_purchase_code;

          }else if($response_arr->result == 0){

            $message = $response_arr->message;
            update_option('wcmlim_license','invalid');
            update_option('wcmlim_email','');
            update_option('purchase_code','');

          }else{

            $response_arr->obfuscated_purchase_code = '';

          }

          $response_arr->message = $message;
          wp_send_json($response_arr);

    }


}

$multiloca_menu_helper = new multiloca_menu_helper();

?>