<?php

namespace Dobare\Abandoned_Cart;

use Dobare\Abstracts\Dobare_REST_Controller;
use Dobare\Utils\Dobare_Utils;

class Dobare_Abandoned_Cart_Notifier
{
	private static ?self $instance = null;
	private ?string $last_error = null;
	private const ENDPOINT = 'v1/integrations/abandoned-carts/';
	private const RETRY_DELAYS = array(
		60,
		300,
		900,
	);

	public static function instance(): self
	{
		if (null === self::$instance) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	public function dispatch(array $payload, int $attempt = 1): bool
	{
		$this->last_error = null;

		$prepared_payload = $this->normalize_payload($payload);

		$headers = $this->build_headers();
		$response = Dobare_REST_Controller::dobare_remote_post(self::ENDPOINT, $prepared_payload, $headers);

		if (is_wp_error($response)) {
			$this->last_error = $response->get_error_message();

			return false;
		}

		$status = isset($response['status']) ? (int) $response['status'] : 500;

		if ($status >= 200 && $status < 300) {
			return true;
		}

		$this->last_error = $this->extract_error_message($response);

		return false;
	}

	public function schedule_retry(string $cart_hash, int $attempt): void
	{
		$delay_index = max(0, min($attempt - 1, count(self::RETRY_DELAYS) - 1));
		$delay = self::RETRY_DELAYS[$delay_index];

		wp_schedule_single_event(
			time() + $delay,
			'dobare_abandoned_cart_retry_notification',
			array(
				$cart_hash,
				$attempt
			)
		);
	}

	public function get_last_error(): ?string
	{
		return $this->last_error;
	}

	private function normalize_payload(array $payload): array
	{
		$normalized = array();

		if (isset($payload['user_phone']) && is_string($payload['user_phone']) && $payload['user_phone'] !== '') {
			$normalized['user_phone'] = $payload['user_phone'];
		}

		if (isset($payload['user_name']) && is_string($payload['user_name']) && $payload['user_name'] !== '') {
			$normalized['user_name'] = $payload['user_name'];
		}

		if (isset($payload['cart_hash']) && is_string($payload['cart_hash']) && $payload['cart_hash'] !== '') {
			$normalized['cart_hash'] = $payload['cart_hash'];
		}

		if (isset($payload['extra_details']) && is_array($payload['extra_details']) && ! empty($payload['extra_details'])) {
			$normalized['extra_details'] = $payload['extra_details'];
		}

		return $normalized;
	}

	private function build_headers(): array
	{
		$headers = array();
		$api_key = Dobare_Utils::get_dob_api_key();

		if (! empty($api_key)) {
			$headers['API-KEY'] = $api_key;
		}

		return $headers;
	}

	private function extract_error_message(array $response): string
	{
		if (isset($response['data']['message']) && is_string($response['data']['message'])) {
			return $response['data']['message'];
		}

		if (isset($response['data']['error']) && is_string($response['data']['error'])) {
			return $response['data']['error'];
		}

		return __('ارسال اعلان سبد خرید با خطا مواجه شد.', 'dobare');
	}
}

