<?php

class Wiass_REST_Delivery_Process_API {

	const BASE_NAME = WP_HOME . '/';

	const FILE_KEY_NAME = 'file';

	const PATH_PARTS_TO_EXTRACT = 7;
	
	const ACCEPTANCE_STATUS_FIELD_ID = 8;
	const EXPIRATION_DATE_FIELD_ID = 9;
	const DECLINE_REASON_FIELD_ID = 10;
	const UPLOADED_FILES_FIELD_ID = 12;

	const USER_INPUT_STEP_NAME = 'Upload acceptance file';
	const ACCEPT_STATUS_LABEL = 'accept';
	const DECLINE_STATUS_LABEL = 'decline';

	const ACCEPTABLE_STATUS = [self::ACCEPT_STATUS_LABEL, self::DECLINE_STATUS_LABEL];
	
	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	private static $namespace = 'wiaas';

	private static $rest_base = 'delivery';


	public static function register_routes() {
		register_rest_route( self::$namespace, '/' . self::$rest_base . '/next-actions', array(
			'methods' => 'GET',
			'callback' => array(__CLASS__, 'get_next_actions_for_user'),
			'permission_callback' => 'is_user_logged_in'
		) );

		register_rest_route( self::$namespace, '/' . self::$rest_base . '/(?P<order_id>\d+)/customer-acceptance', array(
			'methods' => 'GET',
			'callback' => array(__CLASS__, 'get_customer_acceptance'),
			'permission_callback' => 'is_user_logged_in'
		) );

		register_rest_route( self::$namespace, '/' . self::$rest_base . '/(?P<order_id>\d+)/customer-acceptance', array(
			'methods' => 'POST',
			'callback' => array(__CLASS__, 'submit_customer_acceptance'),
			'permission_callback' => 'is_user_logged_in'
		) );

		register_rest_route( self::$namespace, '/' . self::$rest_base . '/(?P<order_id>\d+)/customer-acceptance/upload' , array(
			'methods' => 'POST',
			'callback' => array(__CLASS__, 'upload_customer_acceptance'),
			'permission_callback' => 'is_user_logged_in'
		) );


		register_rest_route( self::$namespace, '/' . self::$rest_base . '/(?P<order_id>\d+)/customer-questionnaires', array(
			'methods' => 'GET',
			'callback' => array(__CLASS__, 'get_customer_questionnaires'),
			'permission_callback' => 'is_user_logged_in'
		) );

		register_rest_route( self::$namespace, '/' . self::$rest_base . '/(?P<order_id>\d+)/customer-questionnaires/upload/(?P<action_entry_id>\d+)', array(
			'methods' => 'POST',
			'callback' => array(__CLASS__, 'upload_customer_questionnaire'),
			'permission_callback' => 'is_user_logged_in'
		) );
	}

	public static function get_next_actions_for_user() {
		$current_user = wp_get_current_user();

		$field_filters   = array();
		$field_filters[] = array(
			'key'   => 'workflow_user_id_' . $current_user->ID,
			'value' => 'pending',
		);

		$field_filters['mode'] = 'any';

		$search_criteria                  = array();
		$search_criteria['field_filters'] = $field_filters;
		$search_criteria['status']        = 'active';

		$form_ids = gravity_flow()->get_workflow_form_ids();

		$entries = GFAPI::get_entries(
			$form_ids,
			$search_criteria,
			null,
			null);

		$data = array();
		foreach ($entries as $entry) {
			$step = gravity_flow()->get_step( $entry['workflow_step'] );
			$data[] = array(
				'order_id' => $entry['wiaas_delivery_order_id'],
				'order_number' => $entry['wiaas_delivery_order_id'],
				'status' => $entry['workflow_final_status'],
				'step_action' => $step->get_name(),
			);
		}

		return rest_ensure_response($data);
	}

	public function get_customer_questionnaires(WP_REST_Request $request) {

		$order_id = absint($request['order_id']);

		$data = Wiaas_Delivery_Process::get_customer_questionnaires_data($order_id);

		return rest_ensure_response($data);
	}

	public function upload_customer_questionnaire(WP_REST_Request $request) {

		$order_id = absint($request['order_id']);

		$action_entry_id = absint($request['action_entry_id']);

		Wiaas_Delivery_Process::upload_customer_questionnaire($order_id, $action_entry_id);

		return wiaas_api_notice('INSTALLATION_ACCEPTED', 'success');
	}

	public static function get_customer_acceptance(WP_REST_Request $request){

		$order_id = absint($request['order_id']);

		$data = Wiaas_Delivery_Process::get_customer_acceptance_data($order_id);

		return rest_ensure_response($data);
	}

	public static function submit_customer_acceptance(WP_REST_Request $request) {

		$status = $request['action_type'];
		$reason = $request['decline_reason'];

		if (!in_array($status, self::ACCEPTABLE_STATUS)){
			return wiaas_api_notice('ACCEPTANCE_STATUS_MISSING', 'error');
		}

		$installation_declined = ($status === self::DECLINE_STATUS_LABEL);
		if ($installation_declined && $reason === ''){
			return wiaas_api_notice('DECLINE_REASON_EMPTY', 'error');
		}


		$order_id = $request['order_id'];

		if (! $installation_declined && ! Wiaas_Delivery_Process::is_customer_acceptance_uploaded($order_id)) {
			return wiaas_api_notice('ACCEPTANCE_NOT_UPLOADED', 'error');
		}

		Wiaas_Delivery_Process::update_customer_acceptance_status($order_id, $status, $reason);

		if ($installation_declined){
			return wiaas_api_notice('INSTALLATION_DECLINED', 'success');
		}

		return wiaas_api_notice('INSTALLATION_ACCEPTED', 'success');
	}

	public static function upload_customer_acceptance(WP_REST_Request $request){

		$order_id = $request['order_id'];

		$success = Wiaas_Delivery_Process::upload_customer_acceptance_document($order_id);


		if ($success) {
			return wiaas_api_notice('FILE_UPLOADED','success');
		}

		return wiaas_api_notice('NOT_UPLOADED', 'error');
	}
}