<?php
class CDAjaxHandler {

	public function action( $controller_string, $method ) {

		$error = false;
		$no_method = true;

    $controller = cd_get_controller_class($controller_string);

		if( class_exists ( $controller ) ){

			$public_method = 'ajax_'.$method;
      if( method_exists ( $controller , $public_method ) ){
				$no_method = false;
        $controller::$public_method();
      }else{
				if( is_user_logged_in() ){
					$priv_method = 'ajax_priv_'.$method;
		      if( method_exists ( $controller , $priv_method ) ){
						$no_method = false;
		        $controller::$priv_method();
		      }
				}else{
					$nopriv_method = 'ajax_nopriv_'.$method;
		      if( method_exists ( $controller , $nopriv_method ) ){
						$no_method = false;
		        $controller::$nopriv_method();
		      }
				}
			}
			if( $no_method ){
				$error['message'] = 'No method '.$method.' found in '.$controller;
				$error['code'] = 404;
			}
		}else{
			$error['message'] = 'No class '.$controller.' found.';
			$error['code'] = 404;
    }

		if( is_array($error) ){
			wp_send_json_error( array('message' => $error['message']), $error['code'] );
		}

	}

	public static function localize_js_object($js_file, $object_name, $controller, $method, $additional_data = null 	) {
		$options = 	array(
			'url' => admin_url('admin-ajax.php'),
			'action' => 'cd_ajax_request',
			'_controller' => $controller,
			'_method' => $method,
			'_nonce' => wp_create_nonce($method),
			'_additional_data' => $additional_data
		);

		if( wp_script_is( $js_file, 'queue' ) ){
			wp_localize_script(
	      $js_file,
	      $object_name,
				$options
	    );
		}else{
			add_action(
				'wp_enqueue_scripts',
				function() use( $js_file, $object_name, $options ) {
					wp_localize_script(
			      $js_file,
			      $object_name,
						$options
			    );
				},
				10
			);
		}

	}

}
?>
