<?php

namespace Dobare\Admin\API\Merchant_Journey;

use Dobare\Abstracts\Dobare_REST_Controller;
use Dobare\Utils\Dobare_Utils;
use Exception;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

class Dobare_Merchant_Journey_REST_Controller extends Dobare_REST_Controller
{
	public function __construct()
	{
		$this->resource_name  = 'merchant-journey';
		$this->jwt_header_key = 'X-DOB-JWT';
	}

	public function register_routes()
	{
		register_rest_route($this->namespace, '/' . $this->resource_name . '/submit-phone', array(
			'methods'             => 'POST',
			'callback'            => array($this, 'submit_phone'),
			'permission_callback' => array($this, 'merchant_journey_permissions_check'),
		));
		register_rest_route($this->namespace, '/' . $this->resource_name . '/submit-code', array(
			'methods'             => 'POST',
			'callback'            => array($this, 'submit_code'),
			'permission_callback' => array($this, 'merchant_journey_permissions_check'),
		));
		register_rest_route($this->namespace, '/' . $this->resource_name . '/create-business', array(
			'methods'             => 'POST',
			'callback'            => array($this, 'create_business'),
			'permission_callback' => array($this, 'create_business_permissions_check'),
		));
		register_rest_route($this->namespace, '/' . $this->resource_name . '/select-business', array(
			'methods'             => 'POST',
			'callback'            => array($this, 'select_business'),
			'permission_callback' => array($this, 'create_business_permissions_check'),
		));
		register_rest_route($this->namespace, '/' . $this->resource_name . '/status', array(
			'methods'             => 'GET',
			'callback'            => array($this, 'status'),
			'permission_callback' => array($this, 'merchant_journey_permissions_check'),
		));
		register_rest_route($this->namespace, '/' . $this->resource_name . '/avg-weekly-revenue', array(
			'methods'             => 'GET',
			'callback'            => array($this, 'avg_weekly_revenue'),
			'permission_callback' => array($this, 'merchant_journey_permissions_check'),
		));
	}

	public function merchant_journey_permissions_check(WP_REST_Request $request)
	{
		// Verify nonce for CSRF protection
		if (! wp_verify_nonce($request->get_header('X-WP-Nonce'), 'wp_rest')) {
			if (! is_user_logged_in()) {
				return new WP_Error(
					'rest_forbidden',
					esc_html__('Invalid security token.', 'dobare'),
					array('status' => 403)
				);
			}
		}

		if (! current_user_can('manage_options')) {
			return new WP_Error(
				'permission_denied',
				esc_html__('You cannot view the post resource.', 'dobare'),
				array('status' => $this->dobare_authorization_status_code())
			);
		}

		return true;
	}

	public function avg_weekly_revenue(WP_REST_Request $request): WP_REST_Response
	{
		return new WP_REST_Response(Dobare_Utils::normalize_response_body(array('avg_weekly_revenue' => Dobare_Utils::get_average_weekly_revenue()), 200), 200);
	}

	public function status(WP_REST_Request $request): WP_REST_Response
	{
		return new WP_REST_Response(Dobare_Utils::normalize_response_body(array('success' => Dobare_Utils::has_been_onboarded()), 200), 200);
	}

	public function submit_phone($request)
	{
		$params       = $request->get_json_params();
		$phone_number = isset($params['phone']) ? sanitize_text_field($params['phone']) : '';
		$response     = self::dobare_remote_post('v1/integrations/auth/send-otp', array('phone' => $phone_number));

		return is_wp_error($response) ? $response : new WP_REST_Response($response["data"], $response["status"] ?: 500);
	}

	public function submit_code($request)
	{
		$params           = $request->get_json_params();
		$otp_code         = isset($params['code']) ? sanitize_text_field($params['code']) : '';
		$verification_key = isset($params['verification_key']) ? sanitize_text_field($params['verification_key']) : '';
		$phone            = isset($params['phone']) ? sanitize_text_field($params['phone']) : '';

		// Verify OTP code with Dobare API
		$verify_response = self::dobare_remote_post('v1/integrations/auth/validate-otp', array(
			'otp'   => $otp_code,
			'key'   => $verification_key,
			'phone' => $phone
		));

		// If OTP verification fails or has an error, return the error response
		if (is_wp_error($verify_response)) {
			return $verify_response;
		}

		if ($verify_response['status'] !== 200) {
			return new WP_REST_Response($verify_response["data"], $verify_response["status"]);
		}

		// OTP is valid, get the access token from response
		$access_token = isset($verify_response['data']['data']['access']) ? $verify_response['data']['data']['access'] : null;

		if (! $access_token) {
			return new WP_REST_Response(
				Dobare_Utils::normalize_error_body(array('Access token not found in response'), 400),
				400
			);
		}

		// Get merchant's business list using the access token
		$businesses_response = self::dobare_remote_get(
			'v1/integrations/wp/merchant-businesses/',
			array('Authorization' => 'Bearer ' . $access_token)
		);

		if (is_wp_error($businesses_response)) {
			return $businesses_response;
		}

		// Parse the business list from the response
		$businesses = isset($businesses_response['data']['data']) ? $businesses_response['data']['data'] : array();

		$response_data = array(
			'verification_successful' => true,
			'access_token' => $access_token,
			'phone' => $phone
		);
		$response_data['businesses'] = $businesses;
		$response_data['business_created'] = false;

		return new WP_REST_Response(
			Dobare_Utils::normalize_response_body($response_data, 200),
			200
		);
	}


	/**
	 * Handle the selection of an existing business from the list
	 *
	 * @param WP_REST_Request $request The request object
	 *
	 * @return WP_REST_Response The response object
	 */
	public function select_business(WP_REST_Request $request)
	{
		$params = $request->get_json_params();
		// Sanitize JWT header
		$jwt_key = sanitize_text_field($request->get_header($this->jwt_header_key));
		// Sanitize business ID - use sanitize_key for IDs
		$business_id = isset($params['business_id']) ? sanitize_key($params['business_id']) : '';

		if (empty($business_id)) {
			return new WP_REST_Response(
				Dobare_Utils::normalize_error_body(array('Business ID is required'), 400),
				400
			);
		}

		// Call the initialize-dobare endpoint with the business ID
		$response = self::dobare_remote_post(
			'v1/integrations/wp/initialize-dobare/' . $business_id . '/',
			array(),
			array('Authorization' => 'Bearer ' . $jwt_key)
		);

		if (is_wp_error($response)) {
			return $response;
		}

		// Check if we received a valid API key
		if (! empty($response["data"]['data']["full_api_key"])) {
			Dobare_Utils::set_dob_api_key($response["data"]['data']["full_api_key"]);
			return new WP_REST_Response(
				Dobare_Utils::normalize_response_body(array("success" => true), 200),
				200
			);
		}

		// Handle error responses
		$error_messages = isset($response["data"]['meta']['detail']['global_error_messages'])
			? $response["data"]['meta']['detail']['global_error_messages']
			: array('خطایی رخ داده است. لطفاً دوباره امتحان کنید.');

		return new WP_REST_Response(
			Dobare_Utils::normalize_error_body($error_messages, $response["status"] ?: 400),
			$response["status"] ?: 400
		);
	}

	public function create_business_permissions_check(WP_REST_Request $request)
	{
		// Verify nonce for CSRF protection
		if (! wp_verify_nonce($request->get_header('X-WP-Nonce'), 'wp_rest')) {
			if (! is_user_logged_in()) {
				return new WP_Error(
					'rest_forbidden',
					esc_html__('Invalid security token.', 'dobare'),
					array('status' => 403)
				);
			}
		}

		if (! current_user_can('manage_options') or $request->get_header($this->jwt_header_key) == null) {
			return new WP_Error(
				'permission_denied',
				esc_html__('You cannot view the post resource.', 'dobare'),
				array('status' => $this->dobare_authorization_status_code())
			);
		}

		return true;
	}

	public function get_current_user_full_name(): string
	{
		$current_user = wp_get_current_user();
		if ($current_user->exists()) {
			if (! empty($current_user->first_name) or ! empty($current_user->last_name)) {
				return $current_user->first_name . ' ' . $current_user->last_name;
			} else if (! empty($current_user->user_firstname) or ! empty($current_user->user_lastname)) {
				return $current_user->user_firstname . ' ' . $current_user->user_lastname;
			} else {
				return $current_user->display_name;
			}
		}

		return '.';
	}

	public function get_site_domain(): string
	{
		$site_url   = get_site_url();
		$parsed_url = wp_parse_url($site_url);
		$domain     = $parsed_url['host'];

		return 'WP-' . str_replace('.', '-', $domain);
	}

	public function create_business(WP_REST_Request $request)
	{
		$params       = $request->get_json_params();
		// Sanitize JWT header
		$jwt_key      = sanitize_text_field($request->get_header($this->jwt_header_key));
		// Sanitize phone number
		$phone_number = isset($params['phone']) ? sanitize_text_field($params['phone']) : '';
		try {

			$description = Dobare_Utils::get_business_description();
		} catch (Exception $e) {
			$description = '-';
		}
		$name        = $this->get_current_user_full_name();
		$title       = get_bloginfo('name');
		$site_domain = $this->get_site_domain();
		$response    = self::dobare_remote_post('v1/integrations/wp/initialize-dobare/', array(
			'owner_phone'    => $phone_number,
			'owner_name'     => $name,
			'business_title' => $title,
			'site_domain'    => $site_domain,
			'description'    => $description
		), array('Authorization' => 'Bearer ' . $jwt_key));

		if (is_wp_error($response)) {
			return $response;
		}

		if (! empty($response["data"]['data']["full_api_key"])) {
			Dobare_Utils::set_dob_api_key($response["data"]['data']["full_api_key"]);
			return new WP_REST_Response(Dobare_Utils::normalize_response_body(array("success" => true), 201), 201);
		}

		// If we get here, we have a response but no API key
		return new WP_REST_Response($response['data'], $response["status"] ?: 400);
	}
}
