<?php

namespace PixelioCartAbandonRecoveryMore\Admin\Services;


use PixelioCartAbandonRecoveryMore\Admin\Exception\Pixelio_Cart_Abandon_Recovery_More_Settings_Exception;
use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

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

/**
 * Class Pixelio_Cart_Abandon_Recovery_More_Config
 *
 * Handles configuration and options for the Pixelio Cart Abandon Recovery More plugin.
 * This class encapsulates:
 *  - Retrieving plugin settings from POST requests
 *  - Saving options via the utility service
 *  - Managing configuration flags and the AI (IA) mode
 *
 * @package PixelioCartAbandonRecoveryMore\Admin\Service
 */
class Pixelio_Cart_Abandon_Recovery_More_Config_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 $wordpress_wrapper WordPress wrapper object
	 * @param Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util Pixelio utility service
	 */
	public function __construct(Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $wordpress_wrapper,
								Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util)
	{
		$this->pixelio_wordpress_wrapper = $wordpress_wrapper;
		$this->pixelio_util = $pixelio_util;
	}

	/**
	 * Resets the initial plugin configuration based on POST request.
	 *
	 * Disconnects the plugin if requested, or temporarily grants access to the configuration panel.
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_reset_first_config_callback(): void
	{
		$disconnect = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
			$this->pixelio_wordpress_wrapper->pixelio_get_post('pixelio_disconnect')
		);
		if (!$this->pixelio_wordpress_wrapper->pixelio_current_user_can('manage_options')) {
			$this->pixelio_wordpress_wrapper->pixelio_wp_send_json_error('Unauthorized');
		}

		if ($disconnect) {
			$this->pixelio_util->pixelio_cart_abandon_recovery_more_disconnect();
		} else {
			$this->pixelio_wordpress_wrapper->pixelio_cart_abandon_recovery_more_access_temporarely_to_config();
		}
	}

	/**
	 * Saves the configuration from a POST request.
	 *
	 * Extracts settings, persists them, handles the configuration flags,
	 * and manages the AI mode flag.
	 *
	 * @throws Pixelio_Cart_Abandon_Recovery_More_Settings_Exception
	 * @return array Returns a JSON-ready array with a message for the UI
	 */
	public function pixelio_cart_abandon_recovery_more_save_from_request($is_ia,$settings,$config, $shop_type): array
	{


		$this->pixelio_save_settings_array($settings);

		$this->pixelio_handle_config_flag($config, $shop_type);

		$this->pixelio_handle_ia_mode($is_ia);

		return array(
			'message' => $this->pixelio_wordpress_wrapper->pixelio_translate(
				'Options updated',
				'rivio-ai-cart-recovery-marketing-email-automation'
			)
		);
	}



	/**
	 * Persists the extracted settings array to the database via the utility service.
	 *
	 * @param array $settings Associative array of settings
	 * @return void
	 */
	private function pixelio_save_settings_array($settings): void
	{

		if (empty($settings['data']) || !is_array($settings['data'])) {
			return;
		}

		foreach ($settings['data'] as $item) {
			if (!isset($item['setting_key'], $item['value'])) {
				continue;
			}
			$option_name = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field($item['setting_key']);
			$option_value = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field($item['value']);
			$this->pixelio_util
				->pixelio_cart_abandon_recovery_more_add_or_update_option(
					$option_name,
					$option_value
				);
		}
	}
	/**
	 * Handles the "first_config_done" flag and the shop type option.
	 *
	 * Saves the configuration completion flag and optionally the shop type if provided.
	 *
	 * @return void
	 */
	private function pixelio_handle_config_flag(?string $config, ?string $shop_type): void
	{
		if ($config !== 'done') {
			return;
		}

		if ($shop_type !== null) {

			$shop_type = trim($shop_type);

			$this->pixelio_util
				->pixelio_cart_abandon_recovery_more_add_or_update_option(
					'pixelio_shop_type',
					$shop_type
				);
		}

		$this->pixelio_util
			->pixelio_cart_abandon_recovery_more_add_or_update_option(
				'pixelio_first_config_done',
				true
			);
	}


	/**
	 * Activates or deactivates the AI (IA) mode based on the POST request.
	 *
	 * If "is_ia" is provided in POST, cleans the value and updates the 'ia-setup-mode' option.
	 *
	 * @return void
	 */
	private function pixelio_handle_ia_mode($is_ia): void
	{

		$clean_value = preg_replace('/\s+/', '', $is_ia);

		$value = ('manual' !== $clean_value);
		$this->pixelio_util
			->pixelio_cart_abandon_recovery_more_add_or_update_option(
				'ia-setup-mode',
				$value
			);
	}


}
