<?php


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

class AIEO_DMM_Consent extends AIEO_DMM_Module_Base {

	const OPTION_KEY = 'aieo_consent_settings';

	public function get_id()       { return 'consent'; }
	public function get_label()    { return __( 'Consent / GDPR', 'ai-eshop-optimizer' ); }
	public function get_priority() { return 25; } 
	public function get_group()    { return 'attribution'; }

	public function register_hooks() {
		add_action( 'wp_ajax_aieo_dmm_consent_save', array( $this, 'ajax_save' ) );
		add_action( 'wp_ajax_aieo_dmm_consent_classify', array( $this, 'ajax_classify' ) );
		add_action( 'wp_ajax_aieo_dmm_consent_clear', array( $this, 'ajax_clear' ) );
	}

	
	public function enqueue_admin_assets() {
		if ( ! class_exists( 'AIEO_Admin_Color' ) && defined( 'AIEO_DIR' ) && file_exists( AIEO_DIR . 'includes/class-aieo-admin-color.php' ) ) {
			require_once AIEO_DIR . 'includes/class-aieo-admin-color.php';
		}
		if ( class_exists( 'AIEO_Admin_Color' ) ) {
			AIEO_Admin_Color::enqueue();
		} else {
			wp_enqueue_style( 'wp-color-picker' );
			wp_enqueue_script( 'wp-color-picker' );
			wp_add_inline_script( 'wp-color-picker', 'jQuery(function($){$(".aieo-cmp-color").wpColorPicker();});' );
		}
	}

	public function render_subtab() {
		$settings  = class_exists( 'AIEO_Consent' ) ? AIEO_Consent::settings() : array();
		$inventory = class_exists( 'AIEO_Consent' ) ? AIEO_Consent::get_inventory() : array();
		$this->render_template( 'consent.php', array(
			'settings'  => $settings,
			'inventory' => $inventory,
		) );
	}

	
	
	

	public function ajax_save() {
		AIEO_DMM::verify_ajax_request();

		
		
		$cur = class_exists( 'AIEO_Consent' ) ? AIEO_Consent::settings() : array();

		$layout = isset( $_POST['layout'] ) ? sanitize_text_field( wp_unslash( $_POST['layout'] ) ) : 'bar';
		if ( ! in_array( $layout, array( 'bar', 'modal' ), true ) ) {
			$layout = 'bar';
		}

		$default_state = ( isset( $_POST['default_state'] ) && 'granted' === $_POST['default_state'] ) ? 'granted' : 'denied';

		
		$one_tap_default = ( isset( $_POST['one_tap_consent_default'] ) && 'checked' === $_POST['one_tap_consent_default'] ) ? 'checked' : 'unchecked';

		$new = array(
			'enabled'        => ! empty( $_POST['enabled'] ) ? 'yes' : 'no',
			'eea_only'       => ! empty( $_POST['eea_only'] ) ? 'yes' : 'no',
			'default_state'  => $default_state,
			'one_tap_enabled'         => ! empty( $_POST['one_tap_enabled'] ) ? 'yes' : 'no',
			'one_tap_consent_default' => $one_tap_default,
			'title'          => isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '',
			'message'        => isset( $_POST['message'] ) ? wp_kses_post( wp_unslash( $_POST['message'] ) ) : '',

			'layout'         => $layout,
			'policy_version' => isset( $_POST['policy_version'] ) ? max( 1, absint( $_POST['policy_version'] ) ) : 1,

			'desc_necessary'  => isset( $_POST['desc_necessary'] ) ? wp_kses_post( wp_unslash( $_POST['desc_necessary'] ) ) : '',
			'desc_functional' => isset( $_POST['desc_functional'] ) ? wp_kses_post( wp_unslash( $_POST['desc_functional'] ) ) : '',
			'desc_analytics'  => isset( $_POST['desc_analytics'] ) ? wp_kses_post( wp_unslash( $_POST['desc_analytics'] ) ) : '',
			'desc_marketing'  => isset( $_POST['desc_marketing'] ) ? wp_kses_post( wp_unslash( $_POST['desc_marketing'] ) ) : '',

			'reopen_enabled' => ! empty( $_POST['reopen_enabled'] ) ? 'yes' : 'no',
			'reopen_label'   => isset( $_POST['reopen_label'] ) ? sanitize_text_field( wp_unslash( $_POST['reopen_label'] ) ) : '',
			'reopen_pos_desktop'    => in_array( isset( $_POST['reopen_pos_desktop'] ) ? sanitize_key( $_POST['reopen_pos_desktop'] ) : '', array( 'left', 'center', 'right' ), true ) ? sanitize_key( $_POST['reopen_pos_desktop'] ) : 'left',
			'reopen_x_desktop'      => isset( $_POST['reopen_x_desktop'] ) ? min( 2000, absint( $_POST['reopen_x_desktop'] ) ) : 86,
			'reopen_bottom_desktop' => isset( $_POST['reopen_bottom_desktop'] ) ? min( 2000, absint( $_POST['reopen_bottom_desktop'] ) ) : 20,
			'reopen_pos_mobile'     => in_array( isset( $_POST['reopen_pos_mobile'] ) ? sanitize_key( $_POST['reopen_pos_mobile'] ) : '', array( 'left', 'center', 'right' ), true ) ? sanitize_key( $_POST['reopen_pos_mobile'] ) : 'left',
			'reopen_x_mobile'       => isset( $_POST['reopen_x_mobile'] ) ? min( 2000, absint( $_POST['reopen_x_mobile'] ) ) : 86,
			'reopen_bottom_mobile'  => isset( $_POST['reopen_bottom_mobile'] ) ? min( 2000, absint( $_POST['reopen_bottom_mobile'] ) ) : 20,
			'cookie_scan'    => ! empty( $_POST['cookie_scan'] ) ? 'yes' : 'no',
			'cookie_scan_days' => isset( $_POST['cookie_scan_days'] ) ? max( 1, min( 365, absint( $_POST['cookie_scan_days'] ) ) ) : 30,

			'cookie_overrides' => isset( $cur['cookie_overrides'] ) && is_array( $cur['cookie_overrides'] ) ? $cur['cookie_overrides'] : array(),
		);

		
		foreach ( array( 'accept', 'decline', 'customize' ) as $btn ) {
			foreach ( array( 'bg', 'fg', 'border', 'bg_hover', 'fg_hover', 'border_hover' ) as $field ) {
				$key       = 'btn_' . $btn . '_' . $field;
				$raw       = isset( $_POST[ $key ] ) ? wp_unslash( $_POST[ $key ] ) : '';
				$clean     = self::sanitize_color( $raw );
				
				
				$new[ $key ] = '' !== $clean ? $clean : ( isset( $cur[ $key ] ) ? $cur[ $key ] : '' );
			}
		}

		
		$new['logo'] = isset( $_POST['logo'] ) ? esc_url_raw( wp_unslash( $_POST['logo'] ) ) : '';
		
		foreach ( array( 'bar_bg', 'bar_text_color', 'bar_desc_color', 'bar_link_color' ) as $bk ) {
			$clean      = self::sanitize_color( isset( $_POST[ $bk ] ) ? wp_unslash( $_POST[ $bk ] ) : '' );
			$new[ $bk ] = '' !== $clean ? $clean : ( isset( $cur[ $bk ] ) ? $cur[ $bk ] : '' );
		}
		
		foreach ( array( 'bar_text_size', 'bar_desc_size' ) as $bk ) {
			$raw        = isset( $_POST[ $bk ] ) ? trim( (string) wp_unslash( $_POST[ $bk ] ) ) : '';
			$new[ $bk ] = preg_match( '/^[0-9]{1,3}(\.[0-9]{1,2})?(px|rem|em|%)?$/', $raw ) ? $raw : ( isset( $cur[ $bk ] ) ? $cur[ $bk ] : '' );
		}

		update_option( self::OPTION_KEY, $new, false );
		wp_send_json_success( array( 'message' => __( 'Consent settings saved.', 'ai-eshop-optimizer' ) ) );
	}

	
	private static function sanitize_color( $val ) {
		if ( class_exists( 'AIEO_Admin_Color' ) ) {
			return AIEO_Admin_Color::sanitize( $val );
		}
		$val = trim( (string) $val );
		if ( '' === $val ) { return ''; }
		if ( 'transparent' === strtolower( $val ) ) { return 'transparent'; }
		return preg_match( '/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $val ) ? $val : '';
	}

	
	
	

	
	public function ajax_classify() {
		AIEO_DMM::verify_ajax_request();
		if ( ! class_exists( 'AIEO_Consent' ) ) {
			wp_send_json_error( array( 'message' => __( 'Consent engine unavailable.', 'ai-eshop-optimizer' ) ) );
		}
		$name     = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
		$category = isset( $_POST['category'] ) ? sanitize_key( wp_unslash( $_POST['category'] ) ) : '';
		$service  = isset( $_POST['service'] ) ? sanitize_text_field( wp_unslash( $_POST['service'] ) ) : '';
		$allowed  = array( 'necessary', 'functional', 'analytics', 'marketing', '' );
		if ( '' === $name || ! in_array( $category, $allowed, true ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid input.', 'ai-eshop-optimizer' ) ) );
		}
		AIEO_Consent::review_cookie( $name, $category, $service );
		wp_send_json_success( array( 'message' => __( 'Saved.', 'ai-eshop-optimizer' ) ) );
	}

	
	public function ajax_clear() {
		AIEO_DMM::verify_ajax_request();
		if ( ! class_exists( 'AIEO_Consent' ) ) {
			wp_send_json_error();
		}
		AIEO_Consent::clear_inventory();
		wp_send_json_success( array( 'message' => __( 'Inventory cleared.', 'ai-eshop-optimizer' ) ) );
	}
}
