<?php

namespace Dobare\Admin;

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

class Dobare_Notices
{
	private $api_key;

	public function __construct()
	{
		$this->api_key = Dobare_Utils::get_dob_api_key();
		add_action('admin_notices', array($this, 'display_notices'));
		add_action('wp_ajax_dismiss_dobare_notice', array($this, 'handle_dismiss_ajax'));
		add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
	}

	public function display_notices()
	{
		$notices = $this->fetch_notices();

		if (empty($notices)) {
			return;
		}

		foreach ($notices as $notice) {
			if (! is_array($notice)) {
				continue;
			}

			$notice_id   = isset($notice['id']) ? $notice['id'] : '';
			$notice_type = isset($notice['type']) ? $notice['type'] : '';
			$title       = isset($notice['title']) ? $notice['title'] : __('Notice', 'dobare');
			$message     = isset($notice['message']) ? $notice['message'] : '';

			// Skip notices without a valid identifier
			if ($notice_id === '') {
				continue;
			}

			if (get_user_meta(get_current_user_id(), 'dismissed_dobare_notice_' . $notice_id, true)) {
				continue;
			}
			$class = 'notice';

			switch ($notice_type) {
				case 'error':
					$class .= ' notice-error';
					break;
				case 'warning':
					$class .= ' notice-warning';
					break;
				case 'success':
					$class .= ' notice-success';
					break;
				default:
					$class .= ' notice-info';
					break;
			}

			if (! empty($notice['dismissible'])) {
				$class .= ' is-dismissible';
			}

			$cta_button_html = '';
			$cta_link = isset($notice['cta_link']) ? $notice['cta_link'] : '';
			$cta_text = isset($notice['cta_text']) ? $notice['cta_text'] : '';
			if (! empty($cta_link) && ! empty($cta_text)) {
				if (strpos($cta_link, 'http://') === 0 || strpos($cta_link, 'https://') === 0) {
					$link = esc_url($cta_link);
				} else {
					$link = esc_url(admin_url($cta_link));
				}

				$cta_button_html = sprintf(
					'<p><a href="%s" class="button">%s</a></p>',
					$link,
					esc_html($cta_text)
				);
			}

			printf(
				'<div id="dobare-notice-%1$s" class="%2$s"><p><strong>%3$s:</strong> %4$s</p>%5$s</div>',
				esc_attr($notice_id),
				esc_attr($class),
				esc_html($title),
				wp_kses_post($message),
				wp_kses_post($cta_button_html)
			);
		}
	}

	public function fetch_notices(): array
	{

		$cache_key     = 'dobare_notices';
		$notifications = get_transient($cache_key);

		if (false === $notifications) {
			$response = Dobare_REST_Controller::dobare_remote_get('v1/integrations/wp/notices/', array(
				'API-KEY' => $this->api_key,
			));

			if (is_wp_error($response) || $response['status'] != 200) {
				return array();
			}

			$notifications = $response['data']['data'];
			set_transient($cache_key, $notifications, MINUTE_IN_SECONDS);
		}

		return $notifications;
	}

	public function enqueue_scripts($hook)
	{
		if ('index.php' !== $hook && 'plugins.php' !== $hook && false === strpos($hook, 'woocommerce')) {
			return;
		}
		wp_enqueue_script(
			'dobare-notices',
			plugin_dir_url(DOBARE_MAIN_PLUGIN_FILE) . 'build/assets/dobare-notices.js',
			array('jquery'),
			DOBARE_VERSION,
			true
		);

		wp_localize_script('dobare-notices', 'DobareNotices', array(
			'ajax_url' => admin_url('admin-ajax.php'),
			'nonce'    => wp_create_nonce('dobare_dismiss_notice'),
		));
	}

	public function handle_dismiss_ajax()
	{
		check_ajax_referer('dobare_dismiss_notice', 'nonce');

		if (! current_user_can('manage_options')) {
			wp_send_json_error(__('You do not have permission to dismiss this notice.', 'dobare'));
			wp_die();
		}

		if (isset($_POST['id'])) {
			$notice_id = sanitize_text_field(wp_unslash($_POST['id']));
		} else {
			wp_send_json_error(__('No notice ID provided.', 'dobare'));
			wp_die();
		}

		update_user_meta(get_current_user_id(), 'dismissed_dobare_notice_' . $notice_id, true);
		$response = Dobare_REST_Controller::dobare_remote_post(
			'v1/integrations/wp/notices/dismiss/',
			array('notice_id' => $notice_id),
			array('API-KEY' => $this->api_key)
		);

		if (is_wp_error($response)) {
			wp_send_json_error(__('Failed to dismiss notification.', 'dobare'));
		} else {
			wp_send_json_success(__('Notification dismissed.', 'dobare'));
		}
	}
}
