<?php

namespace Dobare\Lead_Magnet;

use Dobare\Abstracts\Dobare_REST_Controller;
use Dobare\Utils\Dobare_Utils;
use WP_REST_Request;
use WP_REST_Response;

class Dobare_Lead_Magnet_REST_Controller extends Dobare_REST_Controller
{
	public function __construct()
	{
		$this->resource_name = 'lead-magnet';
	}

	public function register_routes()
	{
		register_rest_route($this->namespace, '/' . $this->resource_name . '/', array(
			'methods'             => 'GET',
			'callback'            => array($this, 'get_lead_magnet_details'),
			// Endpoint serves marketing content only; intentionally public but behind a filterable callback.
			'permission_callback' => array($this, 'lead_magnet_permissions_check'),
		));

		// Render custom lead magnet template
		register_rest_route($this->namespace, '/' . $this->resource_name . '/render', array(
			'methods'             => 'GET',
			'callback'            => array($this, 'render_lead_magnet_template'),
			// This endpoint is intentionally public: it renders HTML templates for iframe display.
			'permission_callback' => array($this, 'lead_magnet_permissions_check'),
		));
	}


	public function get_lead_magnet_details(WP_REST_Request $request)
	{
		$lead_magnet_data    = Dobare_Lead_Magnet_Service::get_lead_magnet_data();
		$normalized_response = Dobare_Utils::normalize_response_body($lead_magnet_data, 200);

		return is_wp_error($normalized_response) ? $normalized_response : new WP_REST_Response($normalized_response, 200);
	}

	/**
	 * Render lead magnet template (custom or redirect to default)
	 * Returns complete HTML document with CSS and JS for iframe
	 *
	 * @param WP_REST_Request $request
	 * @return WP_REST_Response|void
	 */
	public function render_lead_magnet_template(WP_REST_Request $request)
	{
		// Check if custom templates are enabled
		if (!Dobare_Utils::is_custom_lead_magnet_enabled()) {
			// Redirect to default static file
			$default_url = plugin_dir_url(DOBARE_MAIN_PLUGIN_FILE) . 'build/assets/lead-magnet/index.html';
			wp_redirect($default_url);
			exit;
		}

		// Detect device type from user agent
		$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';
		// Validate user agent string
		if (!empty($user_agent) && strlen($user_agent) > 500) {
			$user_agent = substr($user_agent, 0, 500);
		}
		$is_mobile = preg_match('/Mobile|Android|iPhone|iPad/i', $user_agent);
		$device = $is_mobile ? 'mobile' : 'desktop';

		// Get template data
		$template_data = Dobare_Lead_Magnet_Service::get_lead_magnet_template_data($device);
		$html = $template_data['html'];
		$css = $template_data['css'];

		// Ensure content is sanitized (defense in depth)
		$sanitized_html = Dobare_Lead_Magnet_Validator::sanitize_html($html);
		$sanitized_css = Dobare_Lead_Magnet_Validator::sanitize_css($css);

		// Build complete HTML document
		$complete_html = $this->build_custom_template_html($sanitized_html, $sanitized_css, $device);

		// Return as HTML
		header('Content-Type: text/html; charset=UTF-8');
		echo $complete_html;
		exit;
	}

	/**
	 * Build complete HTML document for custom template
	 *
	 * @param string $html Custom HTML content
	 * @param string $css Custom CSS styles
	 * @param string $device Device type
	 * @return string Complete HTML document
	 */
	private function build_custom_template_html(string $html, string $css, string $device): string
	{
		$viewport = $device === 'mobile'
			? 'width=device-width,height=device-height,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no'
			: 'width=device-width,initial-scale=1';

		$fonts_url = plugin_dir_url(DOBARE_MAIN_PLUGIN_FILE) . 'build/assets/lead-magnet/styles/fonts.css';
		$loading_url = plugin_dir_url(DOBARE_MAIN_PLUGIN_FILE) . 'build/assets/lead-magnet/styles/loading.css';

		// JavaScript runtime for timer, redirect, and communication
		$js = $this->get_template_javascript();

		return sprintf(
			'<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="%s">
	<link rel="stylesheet" href="%s">
	<link rel="stylesheet" href="%s">
	<style>%s</style>
</head>
<body>
	<div id="dobare-lead-magnet-wrraper">%s</div>
	<script>%s</script>
</body>
</html>',
			esc_attr($viewport),
			esc_url($fonts_url),
			esc_url($loading_url),
			$css, // Already sanitized
			$html, // Already sanitized
			$js
		);
	}

	/**
	 * Get JavaScript runtime for custom template
	 * Includes timer countdown, redirect, and BroadcastChannel communication
	 *
	 * @return string JavaScript code
	 */
	private function get_template_javascript(): string
	{
		return <<<'JS'
// BroadcastChannel communication
const dobareChannel = new BroadcastChannel('DOBARE-IFRAME');
const LOCAL_STORAGE_LEAD_MAGNET_KEY = 'is_lead_magnet_show';

// Timer variables
let timerElement = null;
let progressTimer = null;
let timeLeft = 60;
let totalTime = 60;
let countdownInterval = null;

// Helpers
const toPersianNumber = (number) => {
	return number.toString().replace(/\d/g, (digit) => '۰۱۲۳۴۵۶۷۸۹'[digit]);
};

const priceFormatNumberWithCommas = (number) => {
	const numberWithCommas = number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
	return toPersianNumber(numberWithCommas);
};

const setCookie = (name, value) => {
	const daysToExpire = 7;
	const date = new Date();
	date.setTime(date.getTime() + daysToExpire * 24 * 60 * 60 * 1000);
	const expires = 'expires=' + date.toUTCString();
	document.cookie = `${name}=${encodeURIComponent(value)}; ${expires}; path=/`;
};

// Global functions for template buttons
window.removeIframeFromDom = function() {
	setCookie(LOCAL_STORAGE_LEAD_MAGNET_KEY, 'true');
	dobareChannel.postMessage({ key: 'REMOVE_DOBARE_IFRAME' });
};

window.goToLoginPage = function() {
	const intervalId = setInterval(() => {
		dobareChannel.postMessage({ key: 'REDIRECT_TO_LOGIN_PAGE' });
		dobareChannel.onmessage = function(event) {
			if (event.data.key === 'CONFRIM_REDIRECT_TO_LOGIN_PAGE') {
				clearInterval(intervalId);
			}
		};
	}, 200);
};

// Height communication
const sendHeightToParent = () => {
	const wrapper = document.getElementById('dobare-lead-magnet-wrraper');
	if (!wrapper) return;
	const height = Math.max(wrapper.scrollHeight, 180);
	dobareChannel.postMessage({ key: 'SET_DOBARE_IFRAME_HEIGHT', height: height });
};

// Timer countdown
const startCountdown = () => {
	timerElement = document.getElementById('dobare-timer');
	progressTimer = document.getElementById('dobare-progress-timer');

	if (!timerElement || !progressTimer) return;

	countdownInterval = setInterval(() => {
		if (timeLeft < 0) {
			clearInterval(countdownInterval);
			window.removeIframeFromDom();
			return;
		}

		const minutes = Math.floor(timeLeft / 60);
		const seconds = timeLeft % 60;
		const formattedMinutes = String(minutes).padStart(2, '0');
		const formattedSeconds = String(seconds).padStart(2, '0');

		timerElement.textContent = `${toPersianNumber(formattedMinutes)}:${toPersianNumber(formattedSeconds)}`;

		if (seconds === 50) {
			setCookie(LOCAL_STORAGE_LEAD_MAGNET_KEY, 'true');
		}

		// Note: We don't apply inline timer background styles here
		// because this is for custom lead magnets that have their own CSS styling

		timeLeft--;
	}, 1000);
};

// Update UI with data from parent
const updateUI = (data) => {
	const creditEl = document.getElementById('dobare-gift-credit-amount');
	const businessEl = document.getElementById('business-name');
	const currencyEl = document.getElementById('dobare-currency-word');

	if (creditEl && data.credit_amount) {
		creditEl.textContent = priceFormatNumberWithCommas(data.credit_amount);
	}
	if (businessEl && data.business_title) {
		businessEl.textContent = data.business_title;
	}
	if (currencyEl && data.currency) {
		currencyEl.textContent = data.currency;
	}

	setTimeout(sendHeightToParent, 100);
};

// Attach event listeners to buttons
const attachButtonListeners = () => {
	// Close button - supports both class and ID selectors
	const closeBtn = document.getElementById('dobare-close-btn') || document.querySelector('.dobare-close-button');
	if (closeBtn) {
		closeBtn.addEventListener('click', window.removeIframeFromDom);
	}

	// Login/CTA button - supports both class and ID selectors
	const loginBtn = document.getElementById('dobare-login-btn') || document.querySelector('.dobare-submit-button');
	if (loginBtn) {
		loginBtn.addEventListener('click', window.goToLoginPage);
	}
};

// Initialize on load
window.addEventListener('load', () => {
	sendHeightToParent();
	startCountdown();
	attachButtonListeners();

	// Setup resize observer
	const wrapper = document.getElementById('dobare-lead-magnet-wrraper');
	if (wrapper && window.ResizeObserver) {
		const observer = new ResizeObserver(() => sendHeightToParent());
		observer.observe(wrapper);
	}
});

// Handle messages from parent
dobareChannel.onmessage = function(event) {
	if (event.data.key === 'SEND_LEAD_MAGNET_DATA_TO_DOBARE_IFRAME') {
		updateUI(event.data.data);
	}
	if (event.data.key === 'SEND_WIDTH_TO_DOBARE_IFRAME') {
		// Adjust layout based on width if needed
	}
};
JS;
	}

	/**
	 * Public permission callback for lead magnet endpoints.
	 *
	 * While the data is intentionally public (it powers a storefront marketing widget),
	 * we still expose a filter so site owners can harden access if needed.
	 *
	 * @param WP_REST_Request $request
	 * @return bool|\WP_Error
	 */
	public function lead_magnet_permissions_check(WP_REST_Request $request)
	{
		/**
		 * Filter whether the lead magnet endpoints should respond.
		 *
		 * Returning a WP_Error will short-circuit the request.
		 *
		 * @param bool|\WP_Error $allowed
		 * @param WP_REST_Request $request
		 */
		$allowed = apply_filters('dobare_lead_magnet_permissions_check', true, $request);

		return $allowed instanceof \WP_Error ? $allowed : (bool) $allowed;
	}
}
