<?php

namespace PixelioCartAbandonRecoveryMore\Admin\Services;


use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;
use RuntimeException;

if (!defined('ABSPATH')) exit;


/**
 * Class Pixelio_Cart_Abandon_Recovery_More_Domain
 *
 * Handles domain registration and verification for the Pixelio Cart Abandon Recovery More plugin.
 *
 * Responsibilities include:
 *  - Retrieving and validating domain from POST requests
 *  - Registering domain via the plugin API
 *  - Creating verification files in the uploads directory
 *  - Verifying the domain with the API
 *  - Optionally storing the API key securely
 *
 * @package PixelioCartAbandonRecoveryMore\Admin\Service
 */
class Pixelio_Cart_Abandon_Recovery_More_Domain_Service
{
	/**
	 * WordPress abstraction layer (POST, sanitize, esc_html, etc).
	 *
	 * @var Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper
	 */
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper;

	/**
	 * Pixelio utility service (options + business logic).
	 *
	 * @var Pixelio_Cart_Abandon_Recovery_More_Util
	 */
	private Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util;


	/**
	 * Constructor.
	 *
	 * @param Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper WordPress wrapper
	 * @param Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util Pixelio utility service
	 */
	public function __construct(Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper, Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util)
	{
		$this->pixelio_wordpress_wrapper = $pixelio_wordpress_wrapper;
		$this->pixelio_util = $pixelio_util;
	}

	/**
	 * Retrieves and validates a domain submitted via POST.
	 *
	 * Sends a JSON error and terminates if no valid domain is provided.
	 *
	 * @return string Validated domain
	 */
	public function pixelio_get_validated_domain($domain)
	{

		if (empty($domain)) {
			$this->pixelio_wordpress_wrapper->pixelio_wp_send_json_error(
				'No domain provided. Please enter a valid domain name.'
			);
			$this->pixelio_wordpress_wrapper->pixelio_wp_die();
		}

		return $domain;
	}

	/**
	 * Registers a domain with the Pixelio API and returns the UUID.
	 *
	 * Sends a JSON error and terminates if the API response is invalid.
	 *
	 * @param string $domain Domain to register
	 * @return string UUID returned by API
	 */
	public function pixelio_register_domain_and_get_uuid(string $domain): string
	{
		$response = $this->pixelio_util->pixelio_cart_abandon_recovery_more_call_api(
			$this->pixelio_util->pixelio_cart_abandon_recovery_more_get_url() . 'register_domain',
			"POST",
			['domain' => $domain]
		);

		if ($this->pixelio_wordpress_wrapper->pixelio_is_wp_error($response) || !isset($response['uuid'])) {
			throw new RuntimeException('Invalid response from API');
		}

		return $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field($response['uuid']);
	}

	/**
	 * Creates a verification file in the uploads directory containing the UUID.
	 *
	 * Sends a JSON error and terminates if the file cannot be written.
	 *
	 * @param string $uuid UUID to write in the verification file
	 * @return void
	 */
	public function pixelio_create_verification_file( $uuid ) {

		$upload_dir = $this->pixelio_wordpress_wrapper->pixelio_wp_upload_dir();
		$file_path  = $this->pixelio_wordpress_wrapper->pixelio_trailingslashit( $upload_dir['basedir'] ) . 'pixelio-domain-verification.txt';

		if ( $this->pixelio_wordpress_wrapper->pixelio_file_exists( $file_path ) ) {
			$this->pixelio_wordpress_wrapper->pixelio_wp_delete_file( $file_path );
		}

		if ( ! $this->pixelio_wordpress_wrapper->pixelio_put_contents( $file_path, $uuid ) ) {
			$this->pixelio_wordpress_wrapper->pixelio_wp_send_json_error(
				'Could not save verification file locally. Check write permissions on the uploads directory.'
			);
			$this->pixelio_wordpress_wrapper->pixelio_wp_die();
		}

	}


	/**
	 * Verifies the domain with the Pixelio API using the UUID.
	 *
	 * Sends a JSON error and terminates if verification fails.
	 *
	 * @param string $domain Domain to verify
	 * @param string $uuid UUID used for verification
	 * @return array API response body as associative array
	 */
	function pixelio_verify_domain_with_api( $domain, $uuid ) {

		$response = $this->pixelio_util->pixelio_cart_abandon_recovery_more_call_api(
			$this->pixelio_util->pixelio_cart_abandon_recovery_more_get_url() . 'verify_domain',
			"POST",
			array(
				'domain' => $domain,
				'uuid'   => $uuid,
			)
		);

		if ( $this->pixelio_wordpress_wrapper->pixelio_is_wp_error( $response ) ) {
			$this->pixelio_wordpress_wrapper->pixelio_wp_send_json_error(
				'Could not reach the verification server. Ensure the API is running and accessible or make sure the verification file is accessible.'
			);
			$this->pixelio_wordpress_wrapper->pixelio_wp_die();
		}

		if ( ! isset( $response['verified'] ) || true !== $response['verified'] ) {
			throw new RuntimeException('Domain verification failed. Ensure the verification file is accessible on the domain.');
		}

		return $response;
	}

	/**
	 * Stores the API key if present in the verification response.
	 *
	 * The API key is encrypted before saving to options.
	 *
	 * @param array $verify_body API verification response body
	 * @return bool True if the API key was stored, false otherwise
	 */
	public function pixelio_maybe_store_api_key( $api_key ) {

		if ( ! $api_key ) {
			return false;
		}



		$this->pixelio_util
			->pixelio_cart_abandon_recovery_more_add_or_update_option(
				'pixelio_api_key',
				"$api_key"
			);

		return true;
	}

}
