<?php

namespace Unlockafe_addons\Widgets;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Repeater;

if (! defined('ABSPATH')) {
	exit; // Exit if accessed directly
}

class Cookie_Consent extends Widget_Base
{
	public function get_name()
	{
		return 'unlockafe-cookie-consent';
	}

	public function get_title()
	{
		return \esc_html__('Cookie Consent', 'unlock-addons-for-elementor');
	}

	public function get_icon()
	{
		return 'eicon-notification ulicon';
	}

	public function get_categories()
	{
		return ['unlockafe-addons'];
	}

	protected function register_controls()
	{
		$this->start_controls_section(
			'content_section',
			[
				'label' => \esc_html__('Content', 'unlock-addons-for-elementor'),
				'tab' => Controls_Manager::TAB_CONTENT,
			]
		);

		$this->add_control('title', [
			'label' => \esc_html__('Title', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => \esc_html__('We use cookies', 'unlock-addons-for-elementor'),
			'dynamic' => ['active' => true],
		]);

		$this->add_control('message', [
			'label' => \esc_html__('Message', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXTAREA,
			'default' => \esc_html__('We use cookies to enhance your browsing experience, serve personalized ads or content, and analyze our traffic.', 'unlock-addons-for-elementor'),
			'dynamic' => ['active' => true],
		]);

		$this->add_control('policy_url', [
			'label' => \esc_html__('Cookie Policy URL', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::URL,
			'default' => [ 'url' => '#', 'is_external' => true ],
		]);

		$this->add_control('policy_text', [
			'label' => \esc_html__('Policy Link Text', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => \esc_html__('Learn more', 'unlock-addons-for-elementor'),
			'dynamic' => ['active' => true],
		]);

		$this->add_control('accept_text', [
			'label' => \esc_html__('Accept Button Text', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => \esc_html__('Accept', 'unlock-addons-for-elementor'),
		]);

		$this->add_control('reject_text', [
			'label' => \esc_html__('Reject Button Text', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => \esc_html__('Reject', 'unlock-addons-for-elementor'),
		]);

		$this->add_control('customize_text', [
			'label' => \esc_html__('Customize Button Text', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => \esc_html__('Customize', 'unlock-addons-for-elementor'),
		]);

		$this->add_control('save_text', [
			'label' => \esc_html__('Save Preferences Button Text', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => \esc_html__('Save preferences', 'unlock-addons-for-elementor'),
		]);

		$repeater = new Repeater();
		$repeater->add_control('key', [
			'label' => \esc_html__('Key (slug)', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => 'analytics',
		]);
		$repeater->add_control('label', [
			'label' => \esc_html__('Label', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => \esc_html__('Analytics', 'unlock-addons-for-elementor'),
			'dynamic' => ['active' => true],
		]);
		$repeater->add_control('description', [
			'label' => \esc_html__('Description', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXTAREA,
			'default' => \esc_html__('Helps us understand how our website is used.', 'unlock-addons-for-elementor'),
			'dynamic' => ['active' => true],
		]);
		$repeater->add_control('required', [
			'label' => \esc_html__('Required (Always Active)', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SWITCHER,
			'default' => 'no',
		]);
		$repeater->add_control('enabled_by_default', [
			'label' => \esc_html__('Enabled by default', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SWITCHER,
			'default' => 'yes',
		]);

		$this->add_control('categories', [
			'label' => \esc_html__('Categories', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::REPEATER,
			'fields' => $repeater->get_controls(),
			'default' => [
				['key'=>'necessary','label'=>\esc_html__('Strictly Necessary','unlock-addons-for-elementor'),'description'=>\esc_html__('Essential for basic site functionality.','unlock-addons-for-elementor'),'required'=>'yes','enabled_by_default'=>'yes'],
				['key'=>'analytics','label'=>\esc_html__('Analytics','unlock-addons-for-elementor'),'description'=>\esc_html__('Helps us improve by collecting usage data.','unlock-addons-for-elementor'),'required'=>'','enabled_by_default'=>'yes'],
				['key'=>'marketing','label'=>\esc_html__('Marketing','unlock-addons-for-elementor'),'description'=>\esc_html__('Used to deliver personalized ads.','unlock-addons-for-elementor'),'required'=>'','enabled_by_default'=>''],
			],
			'title_field' => '{{{ label }}}',
		]);

		$this->add_control('brand_color', [
			'label' => \esc_html__('Brand Color', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::COLOR,
			'default' => '#3b82f6',
		]);

		$this->add_control('position', [
			'label' => \esc_html__('Position', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SELECT,
			'options' => [
				'bottom-right' => \esc_html__('Bottom Right', 'unlock-addons-for-elementor'),
				'bottom-left' => \esc_html__('Bottom Left', 'unlock-addons-for-elementor'),
				'bottom-center' => \esc_html__('Bottom Center', 'unlock-addons-for-elementor'),
				'top-right' => \esc_html__('Top Right', 'unlock-addons-for-elementor'),
				'top-left' => \esc_html__('Top Left', 'unlock-addons-for-elementor'),
				'top-center' => \esc_html__('Top Center', 'unlock-addons-for-elementor'),
			],
			'default' => 'bottom-right',
		]);

		$this->add_control('customize_title', [
			'label' => \esc_html__('Customize Panel Title', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => \esc_html__('Customise Consent Preferences', 'unlock-addons-for-elementor'),
			'dynamic' => ['active' => true],
		]);

		$this->add_control('customize_intro', [
			'label' => \esc_html__('Customize Intro Text', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXTAREA,
			'default' => \esc_html__('We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.', 'unlock-addons-for-elementor'),
			'dynamic' => ['active' => true],
		]);

		$this->add_control('drawer_width', [
			'label' => \esc_html__('Customize Drawer Width (px)', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::NUMBER,
			'default' => 380,
			'min' => 280,
			'max' => 640,
			'step' => 10,
		]);

		$this->add_control('overlay_blur', [
			'label' => \esc_html__('Overlay Blur Effect', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SWITCHER,
			'label_on' => \esc_html__('On', 'unlock-addons-for-elementor'),
			'label_off' => \esc_html__('Off', 'unlock-addons-for-elementor'),
			'condition' => [],
			'default' => 'yes',
		]);

		$this->add_control('trigger_enable', [
			'label' => \esc_html__('Show Sticky Customize Trigger', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SWITCHER,
			'default' => 'yes',
		]);
		$this->add_control('trigger_logo', [
			'label' => \esc_html__('Trigger Logo', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::MEDIA,
			'default' => [ 'url' => '' ],
		]);
		$this->add_control('trigger_size', [
			'label' => \esc_html__('Trigger Size (px)', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::NUMBER,
			'default' => 48,
			'min' => 28,
			'max' => 96,
			'step' => 2,
		]);
		$this->add_control('trigger_position', [
			'label' => \esc_html__('Trigger Position', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SELECT,
			'options' => [
				'bottom-right' => \esc_html__('Bottom Right', 'unlock-addons-for-elementor'),
				'bottom-left' => \esc_html__('Bottom Left', 'unlock-addons-for-elementor'),
				'bottom-center' => \esc_html__('Bottom Center', 'unlock-addons-for-elementor'),
				'top-right' => \esc_html__('Top Right', 'unlock-addons-for-elementor'),
				'top-left' => \esc_html__('Top Left', 'unlock-addons-for-elementor'),
				'top-center' => \esc_html__('Top Center', 'unlock-addons-for-elementor'),
			],
			'default' => 'bottom-right',
		]);
		$this->add_control('trigger_offset_x', [
			'label' => \esc_html__('Trigger Offset X (px)', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::NUMBER,
			'default' => 16,
		]);
		$this->add_control('trigger_offset_y', [
			'label' => \esc_html__('Trigger Offset Y (px)', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::NUMBER,
			'default' => 16,
		]);

		$this->end_controls_section();

		$this->start_controls_section(
			'content_style',
			[
				'label' => \esc_html__('Typography', 'unlock-addons-for-elementor'),
				'tab' => Controls_Manager::TAB_STYLE,
			]
		);
		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name' => 'text_typography',
				'selector' => '{{WRAPPER}} .unlockafe-cookie-consent',
			]
		);

		$this->add_control('bg_color', [
			'label' => \esc_html__('Background Color', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::COLOR,
			'default' => '#ffffff',
		]);
		$this->add_control('text_color', [
			'label' => \esc_html__('Text Color', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::COLOR,
			'default' => '#111827',
		]);
		$this->add_control('muted_color', [
			'label' => \esc_html__('Muted Text Color', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::COLOR,
			'default' => '#6b7280',
		]);
		$this->add_control('border_color', [
			'label' => \esc_html__('Border Color', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::COLOR,
			'default' => '#e5e7eb',
		]);
		$this->end_controls_section();
	}

	protected function render()
	{
		$settings = $this->get_settings_for_display();
		
		// Check if we're in Elementor editor or preview mode
		$is_editor_mode = \Elementor\Plugin::$instance->editor->is_edit_mode();
		$is_preview_mode = \Elementor\Plugin::$instance->preview->is_preview_mode();

		// Ensure assets are loaded
		if (!wp_style_is('unlockafe-cookie-consent-style', 'enqueued')) {
			wp_enqueue_style(
				'unlockafe-cookie-consent-style',
				UNLOCKAFE_ASSETS . 'front-end/css/cookie-consent.css',
				[],
				UNLOCKAFE_VERSION
			);
		}
		if (!wp_script_is('unlockafe-cookie-consent', 'enqueued')) {
			wp_enqueue_script(
				'unlockafe-cookie-consent',
				UNLOCKAFE_ASSETS . 'front-end/js/cookie-consent.js',
				['jquery', 'elementor-frontend'],
				UNLOCKAFE_VERSION,
				true
			);
		}

		$policy_url = isset($settings['policy_url']['url']) ? $settings['policy_url']['url'] : '#';
		$policy_target = !empty($settings['policy_url']['is_external']) ? ' target="_blank" rel="noopener"' : '';
		$data_settings = [
			'brandColor' => $settings['brand_color'] ?? '#3b82f6',
			'position' => $settings['position'] ?? 'bottom-right',
			'drawerWidth' => isset($settings['drawer_width']) ? intval($settings['drawer_width']) : 380,
			'overlayBlur' => !empty($settings['overlay_blur']) && $settings['overlay_blur'] === 'yes',
			'triggerEnabled' => !empty($settings['trigger_enable']) && $settings['trigger_enable'] === 'yes',
			'triggerSize' => isset($settings['trigger_size']) ? intval($settings['trigger_size']) : 48,
			'triggerPosition' => $settings['trigger_position'] ?? 'bottom-right',
			'triggerOffsetX' => isset($settings['trigger_offset_x']) ? intval($settings['trigger_offset_x']) : 16,
			'triggerOffsetY' => isset($settings['trigger_offset_y']) ? intval($settings['trigger_offset_y']) : 16,
			'triggerLogo' => isset($settings['trigger_logo']['url']) ? $settings['trigger_logo']['url'] : '',
		];
		$style_vars = sprintf('--cc-bg:%s;--cc-text:%s;--cc-muted:%s;--cc-border:%s;',
			isset($settings['bg_color']) ? $settings['bg_color'] : '#ffffff',
			isset($settings['text_color']) ? $settings['text_color'] : '#111827',
			isset($settings['muted_color']) ? $settings['muted_color'] : '#6b7280',
			isset($settings['border_color']) ? $settings['border_color'] : '#e5e7eb'
		);
		?>
		<div class="unlockafe-cookie-consent position-<?php echo \esc_attr($data_settings['position']); ?>" data-settings='<?php echo json_encode($data_settings); ?>' role="region" aria-label="Cookie consent banner" style="<?php echo \esc_attr($style_vars); ?>">
			<div class="cc-content">
				<h4 class="cc-title" id="cc-banner-title"><?php echo \esc_html($settings['title']); ?></h4>
				<p class="cc-text"><?php echo \esc_html($settings['message']); ?> <a href="<?php echo \esc_url($policy_url); ?>"<?php echo $policy_target; ?>><?php echo \esc_html($settings['policy_text']); ?></a></p>
				<div class="cc-overlay" aria-hidden="true"></div>
				<div class="cc-customize" role="dialog" aria-modal="true" aria-labelledby="cc-customize-title" aria-describedby="cc-customize-intro">
					<div class="cc-customize-inner" tabindex="-1" style="width: <?php echo (int)$data_settings['drawerWidth']; ?>px;">
						<div class="cc-customize-header">
							<div class="cc-customize-title" id="cc-customize-title"><?php echo \esc_html($settings['customize_title']); ?></div>
							<button type="button" class="cc-close" aria-label="Close preferences">×</button>
						</div>
						<div class="cc-customize-body">
							<p class="cc-intro" id="cc-customize-intro"><?php echo \esc_html($settings['customize_intro']); ?></p>
							<?php if (!empty($settings['categories']) && is_array($settings['categories'])): ?>
								<?php foreach ($settings['categories'] as $cat):
									$key = preg_replace('/[^a-z0-9_\-]/i', '', $cat['key'] ?? '');
									$label = $cat['label'] ?? '';
									$desc = $cat['description'] ?? '';
									$required = !empty($cat['required']) && $cat['required'] === 'yes';
									$enabled = !empty($cat['enabled_by_default']) && $cat['enabled_by_default'] === 'yes';
								?>
									<div class="cc-row" data-key="<?php echo \esc_attr($key); ?>" data-required="<?php echo $required ? '1':'0'; ?>">
										<div>
											<strong><?php echo \esc_html($label); ?></strong>
											<div class="cc-desc"><?php echo \esc_html($desc); ?></div>
										</div>
										<div>
											<?php if ($required): ?>
												<span aria-live="polite"><?php echo \esc_html__('Always Active', 'unlock-addons-for-elementor'); ?></span>
											<?php else: ?>
												<label>
													<input class="cc-toggle" type="checkbox" <?php echo $enabled ? 'checked' : ''; ?> aria-label="<?php echo \esc_attr($label); ?>">
													<?php echo \esc_html__('Enabled', 'unlock-addons-for-elementor'); ?>
												</label>
											<?php endif; ?>
										</div>
									</div>
								<?php endforeach; ?>
							<?php endif; ?>
						</div>
						<div class="cc-customize-footer">
							<button type="button" class="cc-btn cc-btn-reject cc-btn-reject-all"><?php echo \esc_html($settings['reject_text']); ?></button>
							<button type="button" class="cc-btn cc-btn-customize cc-btn-save"><?php echo \esc_html($settings['save_text'] ?: 'Save preferences'); ?></button>
							<button type="button" class="cc-btn cc-btn-accept cc-btn-accept-all"><?php echo \esc_html($settings['accept_text']); ?></button>
						</div>
					</div>
				</div>
			</div>
			<div class="cc-actions">
				<button type="button" class="cc-btn cc-btn-customize"><?php echo \esc_html($settings['customize_text']); ?></button>
				<button type="button" class="cc-btn cc-btn-reject"><?php echo \esc_html($settings['reject_text']); ?></button>
				<button type="button" class="cc-btn cc-btn-accept"><?php echo \esc_html($settings['accept_text']); ?></button>
			</div>
			<?php
			$trigger_style = sprintf('--cc-trigger-size:%dpx;--cc-off-x:%dpx;--cc-off-y:%dpx;', (int)$data_settings['triggerSize'], (int)$data_settings['triggerOffsetX'], (int)$data_settings['triggerOffsetY']);
			?>
			<button type="button" class="cc-trigger position-<?php echo \esc_attr($data_settings['triggerPosition']); ?>" style="<?php echo esc_attr($trigger_style); ?>" aria-label="Customize cookie preferences" title="Customize" data-trigger-logo="<?php echo \esc_attr($data_settings['triggerLogo']); ?>">
				<?php if (!empty($data_settings['triggerLogo'])): ?>
					<img src="<?php echo \esc_url($data_settings['triggerLogo']); ?>" alt="Customize" />
				<?php else: ?>
					<span class="cc-trigger-icn">⚙️</span>
				<?php endif; ?>
			</button>
		</div>
		<?php
		
		// Add inline script for editor/preview mode initialization
		if ($is_editor_mode || $is_preview_mode) {
			?>
			<script type="text/javascript">
			(function() {
				function initCookieConsent() {
					if (typeof jQuery === 'undefined') {
						setTimeout(initCookieConsent, 100);
						return;
					}
					
					var $ = jQuery;
					var $widget = $('.elementor-widget-unlockafe-cookie-consent').last();
					var $cookieConsent = $widget.find('.unlockafe-cookie-consent');
					
					if ($cookieConsent.length === 0) {
						setTimeout(initCookieConsent, 100);
						return;
					}
					
					// Force show in editor mode
					$cookieConsent.addClass('show');
					
					// Apply brand color if available
					var settings = $cookieConsent.data('settings');
					if (settings && settings.brandColor) {
						$cookieConsent[0].style.setProperty('--unlockafe-cookie-brand', settings.brandColor);
					}
					
					console.log('Cookie Consent: Initialized in editor mode');
				}
				
				// Start initialization
				if (document.readyState === 'loading') {
					document.addEventListener('DOMContentLoaded', function() {
						setTimeout(initCookieConsent, 100);
					});
				} else {
					setTimeout(initCookieConsent, 100);
				}
				
				// Also try after delays
				setTimeout(initCookieConsent, 300);
				setTimeout(initCookieConsent, 600);
			})();
			</script>
			<?php
		}
	}
} 