<?php
/**
 * Admin AJAX Controller for Pixelio Cart Abandonment Recovery More plugin.
 *
 * Handles all AJAX requests for the admin panel, such as:
 * - Saving plugin settings in JSON format
 * - Verifying the website domain via API
 * - Sending test emails
 * - Toggling the AI auto mode
 * - Resetting first-time plugin configuration
 *
 * @package PixelioCartAbandonRecoveryMore\Admin\Controllers
 */

namespace PixelioCartAbandonRecoveryMore\Admin\Controllers;

use PixelioCartAbandonRecoveryMore\Admin\Exception\Pixelio_Cart_Abandon_Recovery_More_Auto_Mode_Exception;
use PixelioCartAbandonRecoveryMore\Admin\Exception\Pixelio_Cart_Abandon_Recovery_More_Settings_Exception;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Auto_Mode_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Config_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Domain_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Email_Sender_Service;
use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use PixelioCartAbandonRecoveryMore\Frontend\Controllers\Pixelio_Cart_Abandon_Recovery_More_General_Controller;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;
use RuntimeException;

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


class Pixelio_Cart_Abandon_Recovery_More_Admin_Ajax_Controller extends Pixelio_Cart_Abandon_Recovery_More_General_Controller
{

	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper;
	private Pixelio_Cart_Abandon_Recovery_More_Config_Service $pixelio_settings_service;
	private Pixelio_Cart_Abandon_Recovery_More_Domain_Service $pixelio_domain_service;
	private $pixelio_auto_mode_service;
	private $pixelio_email;

	/**
	 * Constructor.
	 *
	 * Registers all AJAX actions handled by this controller.
	 */
	public function __construct(Pixelio_Cart_Abandon_Recovery_More_Util              $pixelio_util,
								Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $wordpress_wrapper,
								Pixelio_Cart_Abandon_Recovery_More_Domain_Service    $pixelio_domain_service,
								Pixelio_Cart_Abandon_Recovery_More_Email_Sender_Service      $pixelio_email,
								Pixelio_Cart_Abandon_Recovery_More_Config_Service            $pixelio_settings_service,
								Pixelio_Cart_Abandon_Recovery_More_Auto_Mode_Service         $pixelio_auto_mode_service
	)
	{
		parent::__construct($wordpress_wrapper, $pixelio_util);
		$this->pixelio_util = $pixelio_util;
		$this->pixelio_wordpress_wrapper = $wordpress_wrapper;
		$this->pixelio_domain_service = $pixelio_domain_service;
		$this->pixelio_settings_service = $pixelio_settings_service;
		$this->pixelio_auto_mode_service = $pixelio_auto_mode_service;
		$this->pixelio_email = $pixelio_email;
		$this->pixelio_wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_save_json_options', array($this, 'pixelio_cart_abandon_recovery_more_save_json_options'));
		$this->pixelio_wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_verify_domain', array($this, 'pixelio_cart_abandon_recovery_more_verify_domain_callback'));
		$this->pixelio_wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_toggle_auto_mode', array($this, 'pixelio_cart_abandon_recovery_more_toggle_auto_mode'));

		$this->pixelio_wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_send_email', array($this, 'pixelio_cart_abandon_recovery_more_send_email_ajax'));
		$this->pixelio_wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_reset_first_config', array($this, 'pixelio_cart_abandon_recovery_more_reset_first_config_callback'));
	}

	/**
	 * Resets the first-time configuration of the plugin.
	 *
	 * Creates a temporary option to indicate a reset.
	 * Only users with 'manage_options' capability can perform this action.
	 *
	 * @return void Sends JSON response success or error.
	 */
	public function pixelio_cart_abandon_recovery_more_reset_first_config_callback(): void
	{
		$this->pixelio_wordpress_wrapper->pixelio_check_ajax_referer('pixelio_verify_domain_nonce');
		$pixelio_config = new Pixelio_Cart_Abandon_Recovery_More_Config_Service($this->pixelio_wordpress_wrapper, $this->pixelio_util);
		$pixelio_config->pixelio_cart_abandon_recovery_more_reset_first_config_callback();
		$this->pixelio_wordpress_wrapper->pixelio_wp_send_json_success("");
	}

	/**
	 * Sends a test email from the admin panel via AJAX.
	 *
	 * Accepts recipient, subject, content, and optional coupon information.
	 * Replaces coupon placeholders in content if provided.
	 *
	 * @return void Sends JSON response success or error.
	 */
	public function pixelio_cart_abandon_recovery_more_send_email_ajax(): void
	{
		$this->pixelio_wordpress_wrapper->pixelio_check_ajax_referer('pixelio_toggle_nonce', "nonce");


		$sent = $this->pixelio_email->pixelio_get_recovery_more_send_email_to();

		if ($sent) {
			$this->pixelio_wordpress_wrapper->pixelio_wp_send_json_success("");
		} else {
			$this->pixelio_wordpress_wrapper->pixelio_wp_send_json_error($this->pixelio_wordpress_wrapper->pixelio_esc_attr($this->pixelio_wordpress_wrapper->pixelio_translate('Failed to send email', 'rivio-ai-cart-recovery-marketing-email-automation')));
		}
	}

	public function pixelio_cart_abandon_recovery_more_verify_domain_callback(): void
	{

		$this->pixelio_wordpress_wrapper->pixelio_check_ajax_referer('pixelio_verify_domain_nonce');

		$domain = $this->pixelio_wordpress_wrapper->pixelio_isset_in_post('domain')
			? $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
				$this->pixelio_wordpress_wrapper->pixelio_get_post('domain')
			)
			: '';

		$domain = $this->pixelio_domain_service->pixelio_get_validated_domain($domain);


		try {
			$uuid = $this->pixelio_domain_service->pixelio_register_domain_and_get_uuid($domain);
			$this->pixelio_domain_service->pixelio_create_verification_file($uuid);
			$verify_body = $this->pixelio_domain_service->pixelio_verify_domain_with_api($domain, $uuid);



		} catch (RuntimeException $e) {
		     error_log($e->getMessage());
			$this->pixelio_wordpress_wrapper->pixelio_wp_send_json_error(['error'=>$e->getMessage()]);
			$this->pixelio_wordpress_wrapper->pixelio_wp_die();
		}

		$encrypted_key = $this->pixelio_util
			->pixelio_cart_abandon_recovery_more_encrypt_api_key($verify_body['api_key']);

		$this->pixelio_domain_service->pixelio_maybe_store_api_key($encrypted_key);
		$this->pixelio_wordpress_wrapper->pixelio_wp_send_json_success(array('message' =>$this->pixelio_wordpress_wrapper->pixelio_translate('Domain verified successfully.', 'rivio-ai-cart-recovery-marketing-email-automation'),'uuid' => $uuid, 'api_key_saved' => isset($verify_body['api_key']),));
		$this->pixelio_wordpress_wrapper->pixelio_wp_die();
	}

	public function pixelio_cart_abandon_recovery_more_save_json_options(): void
	{

		$this->pixelio_wordpress_wrapper
			->pixelio_check_ajax_referer('pixelio_verify_domain_nonce');

		try {

			if (!$this->pixelio_wordpress_wrapper->pixelio_isset_in_post('is_ia')) {
				$this->pixelio_wordpress_wrapper
					->pixelio_wp_send_json_error($this->pixelio_wordpress_wrapper->pixelio_translate('Missing is_ia parameter', 'rivio-ai-cart-recovery-marketing-email-automation'));
				$this->pixelio_wordpress_wrapper->pixelio_wp_die();
			}

			$is_ia = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
				$this->pixelio_wordpress_wrapper->pixelio_get_post('is_ia')
			);
			$config = $this->pixelio_wordpress_wrapper->pixelio_get_post('config');
			$shopType = $this->pixelio_wordpress_wrapper->pixelio_get_post('pixelio_shop_type');
			$settings = $this->pixelio_extract_settings_from_request();
			$result = $this->pixelio_settings_service->pixelio_cart_abandon_recovery_more_save_from_request($is_ia, $settings, $config, $shopType);;

			$this->pixelio_wordpress_wrapper
				->pixelio_wp_send_json_success($result);
			$this->pixelio_wordpress_wrapper->pixelio_wp_die();
		} catch (Pixelio_Cart_Abandon_Recovery_More_Settings_Exception $e) {

			$this->pixelio_wordpress_wrapper
				->pixelio_wp_send_json_error($e->pixelio_get_error_data());
			$this->pixelio_wordpress_wrapper->pixelio_wp_die();
		}
	}

	/**
	 * Extracts and decodes settings from the POST request.
	 *
	 * @return array Returns an associative array of settings
	 * @throws Pixelio_Cart_Abandon_Recovery_More_Settings_Exception
	 */
	private function pixelio_extract_settings_from_request(): array
	{

		if (!$this->pixelio_wordpress_wrapper->pixelio_isset_in_post('value')) {
			$this->pixelio_wordpress_wrapper
				->pixelio_wp_send_json_error($this->pixelio_wordpress_wrapper->pixelio_translate("Missing Settings parameter", 'rivio-ai-cart-recovery-marketing-email-automation'));
			$this->pixelio_wordpress_wrapper->pixelio_wp_die();
		}

		$raw = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
			$this->pixelio_wordpress_wrapper->pixelio_get_post('value')
		);

		$decoded = json_decode(stripslashes($raw), true);

		if (!is_array($decoded)) {
			$this->pixelio_wordpress_wrapper
				->pixelio_wp_send_json_error($this->pixelio_wordpress_wrapper->pixelio_translate("Invalid JSON format", 'rivio-ai-cart-recovery-marketing-email-automation'));
			$this->pixelio_wordpress_wrapper->pixelio_wp_die();
		}

		return $decoded;
	}

	/**
	 * Toggles the AI auto mode via AJAX.
	 *
	 * @return void Sends JSON response indicating new mode status.
	 */
	public function pixelio_cart_abandon_recovery_more_toggle_auto_mode(): void
	{
		$this->pixelio_wordpress_wrapper
			->pixelio_check_ajax_referer('pixelio_toggle_nonce', 'nonce');

		try {
			$enabled = $this->pixelio_extract_enabled_from_request();
			$result = $this->pixelio_auto_mode_service->pixelio_toggle_from_request($enabled);

			$this->pixelio_wordpress_wrapper
				->pixelio_wp_send_json_success($result);
			$this->pixelio_wordpress_wrapper->pixelio_wp_die();
		} catch (Pixelio_Cart_Abandon_Recovery_More_Auto_Mode_Exception $e) {
			$this->pixelio_wordpress_wrapper
				->pixelio_wp_send_json_error($e->pixelio_get_error_data());
			$this->pixelio_wordpress_wrapper->pixelio_wp_die();
		}
	}

	/**
	 * Extract and normalize the "enabled" value from POST.
	 *
	 * @return bool True if POST value equals string "true", false otherwise.
	 *
	 * @throws Pixelio_Cart_Abandon_Recovery_More_Auto_Mode_Exception
	 *         If "enabled" is not present in POST.
	 */
	private function pixelio_extract_enabled_from_request(): bool
	{
		if (!$this->pixelio_wordpress_wrapper->pixelio_isset_in_post('enabled')) {
			$this->pixelio_wordpress_wrapper
				->pixelio_wp_send_json_error($this->pixelio_wordpress_wrapper->pixelio_translate('Missing "enabled" parameter', 'rivio-ai-cart-recovery-marketing-email-automation'));
			$this->pixelio_wordpress_wrapper->pixelio_wp_die();
		}

		$raw = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
			$this->pixelio_wordpress_wrapper->pixelio_get_post('enabled')
		);

		return ('true' === $raw);
	}


}
