<?php

namespace Dobare\Lead_Magnet;

use Dobare\Abstracts\Dobare_REST_Controller;
use Dobare\Utils\Dobare_Utils;
use Dobare\Customer_Credit\Dobare_Customer_Credit_Service;

class Dobare_Lead_Magnet_Service
{

	public static function get_lead_magnet_data(): array
	{
		$api_key          = Dobare_Utils::get_dob_api_key();
		$lead_magnet_data = array(
			"is_active"      => false,
			"position"       => null,
			"credit_amount"  => null,
			"redirect_to"    => site_url('/my-account/'),
			"business_title" => get_option('blogname', '')
		);

		// Check if customer credit indicator is active and should take precedence
		if (class_exists('Dobare\Customer_Credit\Dobare_Customer_Credit_Service')) {
			$customer_credit_data = Dobare_Customer_Credit_Service::get_customer_credit_data();
			if ($customer_credit_data['is_active'] === true) {
				// Customer credit is active, so lead magnet should not show
				return $lead_magnet_data;
			}
		}

		$allow_without_login_plugin = Dobare_Utils::is_lead_magnet_without_login_plugin_enabled();

		if (
			empty($api_key)
			|| (self::is_user_authenticated())
			|| (
				! $allow_without_login_plugin
				&& ! function_exists('digits_version')
				&& ! self::is_mobits_active()
				&& ! self::is_kerasno_sms_active()
				&& ! self::is_voorodak_active()
			)
		) {
			return $lead_magnet_data;
		}
		$transient_name = 'dobare_lead_magnet_data';

		$cached_data = get_transient($transient_name);

		if ($cached_data !== false) {
			$lead_magnet_settings_data = $cached_data;
		} else {
			$lead_magnet_settings_data = Dobare_REST_Controller::dobare_remote_get(
				'v1/integrations/wp/lead-magnet-data',
				array('API-KEY' => $api_key)
			);

			if ($lead_magnet_settings_data['status'] != 200) {
				return $lead_magnet_data;
			}
			set_transient($transient_name, $lead_magnet_settings_data, 10 * MINUTE_IN_SECONDS);
		}

		$lead_magnet_data['credit_amount'] = $lead_magnet_settings_data['data']['data']['credit_amount'];
		$lead_magnet_data['is_active']     = true;
		$lead_magnet_data['position']      = $lead_magnet_settings_data['data']['data']['position'];

		return $lead_magnet_data;
	}

	static function is_user_authenticated()
	{
		// Method 1: Standard WordPress check
		if (is_user_logged_in()) {
			return true;
		}

		// Method 2: Check current user ID
		if (get_current_user_id() > 0) {
			return true;
		}

		// Method 3: Check authentication cookie
		$cookie = wp_parse_auth_cookie('', 'logged_in');
		if (!empty($cookie)) {
			return true;
		}

		// If all checks fail, user is not authenticated
		return false;
	}

	static function is_mobits_active()
	{
		return (defined('DLR_PLUGIN_FILE') && defined('DLR_VERSION')) || class_exists('Mobits');
	}

	static function is_kerasno_sms_active()
	{
		return defined('MREEIR_PATH') || function_exists('mreeir_kerasno_create_tables');
	}

	static function is_voorodak_active()
	{
		return class_exists('Voorodak_Auth') || function_exists('voorodak_license_check');
	}

	/**
	 * Get lead magnet template HTML/CSS (custom or default)
	 * Auto-detects if custom content exists, otherwise falls back to default files
	 *
	 * @param string $device 'desktop' or 'mobile'
	 * @return array ['html' => string, 'css' => string, 'is_custom' => bool]
	 */
	public static function get_lead_magnet_template_data(string $device = 'desktop'): array
	{
		// Check for custom content first
		if (Dobare_Utils::has_custom_lead_magnet($device)) {
			$custom_html = Dobare_Utils::get_custom_lead_magnet_html($device);
			$custom_css  = Dobare_Utils::get_custom_lead_magnet_css($device);

			// If only HTML is custom, get default CSS
			if ($custom_html && !$custom_css) {
				$custom_css = self::get_default_css($device);
			}

			// If only CSS is custom, get default HTML
			if ($custom_css && !$custom_html) {
				$custom_html = self::get_default_html();
			}

			return array(
				'html'      => $custom_html ?: '',
				'css'       => $custom_css ?: '',
				'is_custom' => true,
			);
		}

		// Fallback to default files
		return array(
			'html'      => self::get_default_html(),
			'css'       => self::get_default_css($device),
			'is_custom' => false,
		);
	}

	/**
	 * Get default HTML template from file
	 *
	 * @return string
	 */
	public static function get_default_html(): string
	{
		// Try build directory first (production), then src (development)
		$build_file = plugin_dir_path(DOBARE_MAIN_PLUGIN_FILE) . 'build/assets/lead-magnet/index.html';
		$src_file = plugin_dir_path(DOBARE_MAIN_PLUGIN_FILE) . 'src/assets/lead-magnet/index.html';

		$html_file = file_exists($build_file) ? $build_file : $src_file;

		if (file_exists($html_file)) {
			$content = file_get_contents($html_file);
			// Extract content from template tag for the editor
			if (preg_match('/<template[^>]*>(.*?)<\/template>/s', $content, $matches)) {
				return trim($matches[1]);
			}
			return $content;
		}

		return '';
	}

	/**
	 * Get default CSS from file based on device type
	 *
	 * @param string $device 'desktop' or 'mobile'
	 * @return string
	 */
	public static function get_default_css(string $device = 'desktop'): string
	{
		$css_filename = $device === 'mobile' ? 'mobile-style.css' : 'desktop-style.css';

		// Try build directory first (production), then src (development)
		$build_file = plugin_dir_path(DOBARE_MAIN_PLUGIN_FILE) . 'build/assets/lead-magnet/styles/' . $css_filename;
		$src_file = plugin_dir_path(DOBARE_MAIN_PLUGIN_FILE) . 'src/assets/lead-magnet/styles/' . $css_filename;

		$css_file = file_exists($build_file) ? $build_file : $src_file;

		if (file_exists($css_file)) {
			return file_get_contents($css_file);
		}

		return '';
	}
}
