<?php

namespace PixelioCartAbandonRecoveryMore\Admin\Wrapper;


use WP_Error;
use WP_Query;

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

class Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper
{
	public function __construct()
	{

	}
	public function pixelio_plugin_dir_path($file): string {
		if (function_exists('plugin_dir_path')) {
			return plugin_dir_path($file);
		}
		// fallback pour les tests unitaires
		return __DIR__ . '/../../'; // chemin relatif vers la racine du plugin
	}



	public function pixelio_set_transient(string $key, mixed $value, int $ttl = 600): void
	{
		set_transient($key, $value, $ttl);
	}

	public function pixelio_get_transient(string $key, mixed $default = null): mixed
	{
		$value = get_transient($key);

		return ($value === false) ? $default : $value;
	}

	public function pixelio_delete_transient(string $key): bool
	{
		return (bool) delete_transient($key);
	}

	public function has(string $key): bool
	{
		return get_transient($key) !== false;
	}
	public function pixelio_wc_get_session($name)
	{
		if ( WC()->session ) {
			return WC()->session->get($name);
		}
		return null;
	}



	public function pixelio_update_post_meta($post_id, $meta_key, $meta_value)
	{
		return update_post_meta($post_id, $meta_key, $meta_value);
	}

	public function pixelio_trailingslashit(string $string): string
	{
		return trailingslashit($string);
	}
	public function pixelio_get_upgrade_db(): void
	{
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
	}

	public function pixelio_wp_query($args)
	{
		return new WP_Query($args);
	}

	public function pixelio_get_wpdb()
	{
		global $wpdb;
		return $wpdb;
	}

	public function pixelio_is_email($email)
	{
		return is_email($email);
	}

	public function pixelio_wp_get_attachment_image_url($id, $type): false|string
	{
		return wp_get_attachment_image_url($id, $type);
	}

	public function pixelio_current_time(): int|string
	{
		return current_time('mysql');
	}

	public function pixelio_get_wpdb_prefix()
	{
		global $wpdb;
		return $wpdb->prefix;
	}

	public function pixelio_add_action($name, $callback, $priority = 10, $args = 1)
	{
		add_action($name, $callback, $priority, $args);
	}

	public function pixelio_get_user_by_email($email)
	{
		return get_user_by("email", $email);
	}

	public function pixelio_wp_json_encode($data)
	{
		return wp_json_encode($data);
	}

	public function pixelio_wp_parse_args($args)
	{
		return wp_parse_args($args);
	}

	public function pixelio_add_filter($name, $callback, $priority = 10, $arguments = 1)
	{
		add_filter($name, $callback, $priority, $arguments);
	}

	public function pixelio_wp_upload_dir()
	{
		return wp_upload_dir();
	}

	public function pixelio_add_shortcode($name, $callback)
	{
		add_shortcode($name, $callback);
	}

	public function pixelio_wp_next_scheduled($name)
	{
		return wp_next_scheduled($name);
	}

	public function pixelio_is_category()
	{
		return is_category();
	}

	public function pixelio_is_404()
	{
		return is_404();
	}

	public function pixelio_is_tag()
	{
		return is_tag();
	}

	public function pixelio_is_archive()
	{
		return is_archive();
	}

	public function pixelio_check_ajax_referer($name = "", $query_arg = "nonce")
	{
		return check_ajax_referer($name, $query_arg);
	}

	public function pixelio_getcookie(){
		$uuid = null;
		if (isset($_COOKIE['pixelio_uuid'])) {
			$uuid = sanitize_text_field($_COOKIE['pixelio_uuid']);
		}
		return $uuid;
	}
	public function pixelio_sanitize_email($email = "")
	{
		return sanitize_email($email);
	}

	public function pixelio_cart_abandon_recovery_more_access_temporarely_to_config()
	{
		add_option('pixelio-first-config-temporary', true);
	}

	public function pixelio_esc_html($html = "")
	{
		// phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
		return esc_html($html);
	}

	public function pixelio_esc_sql($data = "")
	{
		return esc_sql($data);
	}

	public function pixelio_esc_html__($html = "")
	{
		// phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
		return esc_html__($html,'rivio-ai-cart-recovery-marketing-email-automation');
	}

	public function pixelio_esc_url($url = "")
	{
		return esc_url($url);
	}

	public function pixelio_wp_remote_retrieve_body($response = "")
	{
		return wp_remote_retrieve_body($response);
	}

	public function pixelio_is_wp_error($verify_response)
	{
		return is_wp_error($verify_response);
	}

	public function pixelio_esc_attr($value)
	{
		return esc_attr($value);
	}

	public function pixelio_get_current_user_id()
	{
		return get_current_user_id();
	}

	public function pixelio_current_user_can($option)
	{
		return current_user_can($option);
	}

	public function pixelio_isset_in_post($name)
	{
		return isset($_POST[$name]);
	}

	public function pixelio_get_post($name)
	{
		if (isset($_POST[$name])) {
			return $this->pixelio_wp_unslash($_POST[$name]);
		}
		return "";
	}
	public function pixelio_wp_kses_post($value)
	{
		return wp_kses_post($value);

	}

	public function pixelio_wp_unslash($value)
	{
		return wp_unslash($value);
	}

	public function pixelio_wp_enqueue_style($slug, $src = '', $deps = array(), $ver = false, $media = 'all')
	{
		wp_enqueue_style($slug, $src, $deps, $ver);
	}

	public function pixelio_wp_enqueue_script($slug, $src = '', $deps = array(), $ver = false, $media = 'all')
	{
		wp_enqueue_script($slug, $src, $deps, $ver);
	}

	public function pixelio_wp_kses($html, $allowed_html)
	{
		return wp_kses($html, $allowed_html);
	}

	public function pixelio_is_product()
	{
		return is_product();
	}

	public function pixelio_wp_get_current_user()
	{
		return wp_get_current_user();
	}

	public function pixelio_get_permalink($post)
	{
		return get_permalink($post);
	}

	public function pixelio_get_filter()
	{
		global $wp_filter;
		return $wp_filter;
	}

	public function pixelio_get_bloginfo($name)
	{
		return get_bloginfo($name);
	}


	public function pixelio_wc_price(float $amount): string
	{
		if (!function_exists('wc_price')) {
			return (string)$amount;
		}

		return wc_price($amount);
	}

	public function pixelio_wp_trim_words(string $text, int $num_words = 55, string $more = '...'): string
	{
		if (!function_exists('wp_trim_words')) {
			$words = preg_split('/\s+/', $text);
			$trimmed = array_slice($words, 0, $num_words);
			return implode(' ', $trimmed) . $more;
		}

		return wp_trim_words($text, $num_words, $more);
	}

	public function pixelio_wp_strip_all_tags(string $text): string
	{
		if (!function_exists('wp_strip_all_tags')) {
			//phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags
			return strip_tags($text);
		}

		return wp_strip_all_tags($text);
	}

	public function pixelio_get_attachment_image_url(int $attachment_id, string $size = 'thumbnail'): ?string
	{
		if (!function_exists('wp_get_attachment_image_url')) {
			return null;
		}

		$url = wp_get_attachment_image_url($attachment_id, $size);

		return $url ?: null;
	}

	function pixelio_get_coupons_from_email($email)
	{
		global $wpdb;

		return $wpdb->get_results($wpdb->prepare("
        SELECT p.ID, p.post_name
        FROM {$wpdb->prefix}posts p
        INNER JOIN {$wpdb->prefix}postmeta pm
            ON p.ID = pm.post_id
        WHERE p.post_type = 'shop_coupon'
            AND pm.meta_key = 'customer_email'
            AND pm.meta_value LIKE %s
        ORDER BY p.ID DESC
    ", "%:%" . $email . "%"));
	}



	public function pixelio_home_url(string $path = ''): string
	{
		return home_url($path);
	}

	public function pixelio_add_query_arg(array $args, string $url): string
	{
		return add_query_arg($args, $url);
	}

	public function pixelio_wp_generate_password($length = 12, $special_chars = true, $extra_special_chars = false)
	{
		return $this->pixelio_get_password($length, $special_chars, $extra_special_chars);
	}

	/**
	 * @param mixed $length
	 * @param mixed $special_chars
	 * @param mixed $extra_special_chars
	 * @return mixed|null
	 */
	private function pixelio_get_password(mixed $length, mixed $special_chars, mixed $extra_special_chars): mixed
	{
		return wp_generate_password($length, $special_chars, $extra_special_chars);
	}

	public
	function pixelio_wp_get_attachment_url($id)
	{
		return wp_get_attachment_url($id);
	}

	public
	function pixelio_do_action($action)
	{
		do_action($action);
	}

	public
	function pixelio_throw_wp_error($name, $message)
	{
		return new WP_Error($name, $message);
	}

	public
	function pixelio_wp_die()
	{
		wp_die();
	}

	public
	function pixelio_wp_mail($user_email, $subject, $message, $headers=[])
	{
		return wp_mail($user_email, $subject, $message, $headers);
	}

	public
	function pixelio_get_users($array)
	{
		return get_user($array);
	}

	public
	function pixelio_set_cookie($name, $value, $expiration, $path = '', $domain = '')
	{
		return setcookie($name, $value, $expiration, $path, $domain);
	}

	public
	function pixelio_get_current_post_id()
	{
		global $post;

		return $post->ID;
	}

	public
	function pixelio_wp_doing_ajax()
	{
		return wp_doing_ajax();
	}

	public
	function pixelio_is_admin()
	{
		return is_admin();
	}

	public
	function pixelio_is_user_logged_in()
	{
		return is_user_logged_in();
	}

	public
	function pixelio_admin_url($url)
	{
		return admin_url($url);
	}

	public
	function pixelio_get_option($option, $default = "")
	{
		return get_option($option, $default);
	}

	public
	function pixelio_is_plugin_active($plugin_name)
	{
		return is_plugin_active($plugin_name);
	}

	public
	function pixelio_wp_safe_redirect($url)
	{
		wp_safe_redirect($url);
	}

	public
	function pixelio_plugins_url($url, $plugin_file)
	{
		return plugins_url($url, $plugin_file);
	}

	public
	function pixelio_delete_option($option)
	{
		return delete_option($option);
	}

	public
	function pixelio_wp_create_nonce($nonce_name)
	{
		return wp_create_nonce($nonce_name);
	}

	public
	function pixelio_wp_localize_script($slug, $name, $array)
	{
		return wp_localize_script($slug, $name, $array);
	}

	public
	function pixelio_translate($text, $domain= "rivio-ai-cart-recovery-marketing-email-automation")
	{
		// phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
		return __($text, "rivio-ai-cart-recovery-marketing-email-automation");
	}



	public
	function pixelio_esc_html_e($text, $domain="rivio-ai-cart-recovery-marketing-email-automation")
	{
		esc_html_e($text, "rivio-ai-cart-recovery-marketing-email-automation");
	}

	function pixelio_put_contents(string $file_path, string $content): bool
	{
		if (!function_exists('WP_Filesystem')) {
			return false;
		}

		WP_Filesystem();
		global $wp_filesystem;

		if (!$wp_filesystem) {
			return false;
		}

		return $wp_filesystem->put_contents($file_path, $content, FS_CHMOD_FILE);
	}

	public
	function pixelio_wp_send_json_success($name)
	{
		wp_send_json_success($name);
	}

	public
	function pixelio_file_exists($file_path)
	{
		return file_exists($file_path);
	}

	public
	function pixelio_wp_delete_file($file_path)
	{
		return wp_delete_file($file_path);
	}

	public
	function pixelio_wp_send_json_error($name)
	{
		wp_send_json_error($name);
	}

	public
	function pixelio_wp_schedule_event(int $timestamp, string $recurrence, string $hook, array $args = []): bool
	{
		if (!wp_next_scheduled($hook)) {
			return wp_schedule_event($timestamp, $recurrence, $hook, $args);
		}
		return false;
	}

	public function pixelio_get_current_admin_page(): ?string
	{
		if (!is_admin() || !isset($_GET['page'])) {
			return null;
		}

		return $this->pixelio_sanitize_text_field($this->pixelio_wp_unslash($_GET['page']));
	}

	public function pixelio_sanitize_text_field($text = "")
	{
		return sanitize_text_field($text);
	}

	/**
	 * Wrapper for setcookie to support options array.
	 *
	 * @param string $name  Cookie name.
	 * @param string $value Cookie value.
	 * @param array|int $options Expiration time as int OR options array.
	 *   If array, supports keys: expires, path, domain, secure, httponly, samesite.
	 *
	 * @return bool True on success, false on failure.
	 */
	public function pixelio_setcookie(string $name, string $value, $options = []): bool
	{
		if (is_array($options)) {
			// Merge with defaults
			$defaults = [
				'expires'  => 0,
				'path'     => '/',
				'domain'   => '',
				'secure'   => isset($_SERVER['HTTPS']),
				'httponly' => false,
				'samesite' => 'Lax',
			];
			$options = array_merge($defaults, $options);
			return setcookie(
				$name,
				$value,
				[
					'expires'  => $options['expires'],
					'path'     => $options['path'],
					'domain'   => $options['domain'],
					'secure'   => $options['secure'],
					'httponly' => $options['httponly'],
					'samesite' => $options['samesite'],
				]
			);
		}

		// Fallback for old signature: $options is int = expire
		return setcookie($name, $value, (int)$options, '/');
	}

	public function pixelio_get_current_post()
	{
		global $post;
		return $post;
	}

	public function pixelio_esc_attr__(string $text): string
	{
		// phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
		return esc_attr__(
			$text,
			'rivio-ai-cart-recovery-marketing-email-automation'
		);
	}

	public function pixelio_sanitize_url(array|string $pixelio_url)
	{
		return sanitize_url($pixelio_url);
	}

	public function pixelio_wp_insert_post(array $array)
	{
		return wp_insert_post($array);
	}



	public function pixelio_wp_timezone()
	{
		return wp_timezone();
	}

	public function pixelio_rawurlencode(mixed $pixelio_wp_generate_password)
	{
		return rawurlencode($pixelio_wp_generate_password);
	}

	public function pixelio_esc_url_raw(string $url)
	{
		return esc_url_raw($url);
	}

	public function pixelio_wp_add_inline_script(
		string $handle,
		string $data,
		string $position = 'after'
	): bool {
		return wp_add_inline_script($handle, $data, $position);
	}

	public function pixelio_sanitize_key(array|string $pixelio_wp_unslash)
	{
		return sanitize_key($pixelio_wp_unslash);
	}


}
