<?php

namespace Clonable\Controllers;

use Clonable\Helpers\Functions;
use Clonable\Traits\Validation;
use Clonable\Views\EmailTranslationsView;
use Clonable\Models\EmailTranslations;

class EmailTranslationsController extends Controller
{
	use Validation;

	private static $instance = null;

	public static function get_instance()
	{
		if (self::$instance === null) {
			self::$instance = new EmailTranslationsController();
		}

		return self::$instance;
	}

	private function __construct()
	{
		// Keep constructor private
		$this->view = new EmailTranslationsView();
	}

	public function validate($request)
	{
		$this->validate_fields($request, EmailTranslations::$fields);
	}

	public function clonable_email_translations_enabled_validate($input)
	{
		return $this->validate_checkbox($input, 'clonable_email_translations_enabled');
	}

	public function clonable_woocommerce_enable_pdf_invoice_translation_validate($input)
	{
		return $this->validate_checkbox($input, 'clonable_woocommerce_enable_pdf_invoice_translation');
	}

	public function clonable_email_translations_excluded_addresses_validate($input)
	{
		if (!is_string($input)) {
			$input = '';
		}

		$input = trim($input);
		if ($input === '') {
			return '';
		}

		$parts = preg_split('/[\s,;]+/', $input, -1, PREG_SPLIT_NO_EMPTY);

		$valid   = [];
		$invalid = [];

		foreach ($parts as $part) {
			$email = sanitize_email($part);

			if ($this->validate_email_strict($email)) {
				$valid[] = $email;
			} else {
				$invalid[] = $part;
			}
		}

		$valid = array_values(array_unique($valid));

		if (!empty($invalid) && \function_exists('add_settings_error')) {
			add_settings_error(
				'clonable_email_translations_excluded_addresses',
				'clonable_invalid_excluded_emails',
				'Invalid email address(es): ' . implode(', ', $invalid),
				'error'
			);
		}

		return implode(', ', $valid);
	}

	public function clonable_email_headers_by_domain_validate($input)
	{
		// The UI may submit a JSON string; normalize to array.
		if (is_string($input)) {
			$decoded = json_decode(stripslashes($input), true);
			if (json_last_error() === JSON_ERROR_NONE) {
				$input = $decoded;
			}
		}

		if (!is_array($input)) {
			return '[]';
		}

		$validated_rows = [];
		foreach ($input as $row) {
			if (!is_array($row)) {
				continue;
			}

			$clone_id = isset($row['clone_id']) ? trim((string) $row['clone_id']) : '';
			$domain   = isset($row['domain']) ? trim((string) $row['domain']) : '';
			if ($domain === '') {
				continue;
			}

			$from_address = isset($row['from_address']) ? trim((string) $row['from_address']) : '';
			$reply_to     = isset($row['reply_to']) ? trim((string) $row['reply_to']) : '';
			$sender_name  = isset($row['sender_name']) ? trim((string) $row['sender_name']) : '';
			$email_logo   = isset($row['email_logo']) ? trim((string) $row['email_logo']) : '';

			if ($from_address !== '') {
				$from_address = sanitize_email($from_address);
				if (!$this->validate_email_strict($from_address)) {
					$from_address = '';
					if (function_exists('add_settings_error')) {
						add_settings_error(
							'clonable_email_headers_by_domain',
							'clonable_invalid_from_address_' . md5($domain),
							"Invalid From Address for domain '{$domain}': " . $row['from_address']
						);
					}
				}
			}

			if ($reply_to !== '') {
				$reply_to = sanitize_email($reply_to);
				if (!$this->validate_email_strict($reply_to)) {
					$reply_to = '';
					if (function_exists('add_settings_error')) {
						add_settings_error(
							'clonable_email_headers_by_domain',
							'clonable_invalid_reply_to_' . md5($domain),
							"Invalid Reply-To Address for domain '{$domain}': " . (string) $row['reply_to'],
							'error'
						);
					}
				}
			}

			if ($sender_name !== '') {
				$sender_name = sanitize_text_field($sender_name);
				if ($sender_name === '') {
					if (function_exists('add_settings_error')) {
						add_settings_error(
							'clonable_email_headers_by_domain',
							'clonable_invalid_sender_name_' . md5($domain),
							"Invalid Sender Name for domain '{$domain}': " . $row['sender_name']
						);
					}
				}
			}

			if ($email_logo !== '') {
				$email_logo = trim($email_logo);

				// Sanitize + validate URL
				$sanitized_logo = \function_exists('esc_url_raw')
					? esc_url_raw($email_logo)
					: (string) filter_var($email_logo, FILTER_SANITIZE_URL);

				// Check if the URL entered is an image URL
				$path     = parse_url($sanitized_logo, PHP_URL_PATH);
				$ext      = is_string($path) ? strtolower((string) pathinfo($path, PATHINFO_EXTENSION)) : '';
				$is_image = in_array($ext, ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'], true);

				if (!$sanitized_logo || !$is_image) {
					$email_logo = '';
					if (\function_exists('add_settings_error')) {
						add_settings_error(
							'clonable_email_headers_by_domain',
							'clonable_invalid_email_logo_' . $domain,
							"Invalid Email Logo URL for clone domain '{$domain}': " . ($row['email_logo'] ?? '')
						);
					}
				} else {
					$email_logo = $sanitized_logo;
				}
			}

			$validated_rows[] = [
				'clone_id'     => $clone_id,
				'domain'       => $domain,
				'from_address' => $from_address,
				'reply_to'     => $reply_to,
				'sender_name'  => $sender_name,
				'email_logo'   => $email_logo,
			];
		}

		return wp_json_encode($validated_rows);
	}

	public function clonable_wpo_replacements_by_domain_validate($input)
	{
		// The UI submits a JSON string via a hidden input; normalize to array.
		if (is_string($input)) {
			$decoded = json_decode(stripslashes($input), true);
			if (json_last_error() === JSON_ERROR_NONE) {
				$input = $decoded;
			}
		}

		if (!is_array($input)) {
			return '[]';
		}

		$validated_rows = [];
		foreach ($input as $row) {
			if (!is_array($row)) {
				continue;
			}

			// These are shown as disabled/readonly in the view, but still validate/normalize.
			$clone_id = Functions::sanitize_text($row['clone_id'] ?? '');
			$domain   = Functions::sanitize_text($row['domain'] ?? '');

			if ($domain === '') {
				continue;
			}

			$shop_phone_number       = Functions::sanitize_text($row['shop_phone_number'] ?? '');
			$shop_name               = Functions::sanitize_text($row['shop_name'] ?? '');
			$vat_number              = Functions::sanitize_text($row['vat_number'] ?? '');
			$coc_number              = Functions::sanitize_text($row['coc_number'] ?? '');
			$shop_address_line_1     = Functions::sanitize_text($row['shop_address_line_1'] ?? '');
			$shop_address_line_2     = Functions::sanitize_text($row['shop_address_line_2'] ?? '');
			$shop_address_country    = Functions::sanitize_text($row['shop_address_country'] ?? '');
			$shop_address_state      = Functions::sanitize_text($row['shop_address_state'] ?? '');
			$shop_address_city       = Functions::sanitize_text($row['shop_address_city'] ?? '');
			$shop_address_postcode   = Functions::sanitize_text($row['shop_address_postcode'] ?? '');
			$shop_address_additional = Functions::sanitize_text($row['shop_address_additional'] ?? '');

			$shop_email_address = '';
			if (!empty($row['shop_email_address'])) {
				$shop_email_address = $row['shop_email_address'];
				if (!$this->validate_email_strict($shop_email_address)) {
					if (function_exists('add_settings_error')) {
						add_settings_error(
							'clonable_wpo_replacements_by_domain',
							'clonable_invalid_shop_email_' . md5($domain),
							"Invalid shop email address for domain '$domain': " . $shop_email_address
						);
					}
					$shop_email_address = '';
				}
			}

			$validated_rows[] = [
				'clone_id'                => $clone_id,
				'domain'                  => $domain,
				'shop_phone_number'       => $shop_phone_number,
				'shop_email_address'      => $shop_email_address,
				'shop_name'               => $shop_name,
				'vat_number'              => $vat_number,
				'coc_number'              => $coc_number,
				'shop_address_line_1'     => $shop_address_line_1,
				'shop_address_line_2'     => $shop_address_line_2,
				'shop_address_country'    => $shop_address_country,
				'shop_address_state'      => $shop_address_state,
				'shop_address_city'       => $shop_address_city,
				'shop_address_postcode'   => $shop_address_postcode,
				'shop_address_additional' => $shop_address_additional,
			];
		}

		if (function_exists('wp_json_encode')) {
			return (string) \wp_json_encode($validated_rows);
		}

		return (string) json_encode($validated_rows);
	}
}
