<?php

/**
 * Notifications REST API Controller
 * 
 * Bridge to WooCommerce emails + addon channel framework.
 * 
 * @package WooNooW\Api
 */

namespace WooNooW\Api;

use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WooNooW\Core\Notifications\TemplateProvider;
use WooNooW\Core\Notifications\EventRegistry;
use WooNooW\Core\Notifications\PushNotificationHandler;

class NotificationsController
{

	/**
	 * REST API namespace
	 */
	private $namespace = 'woonoow/v1';

	/**
	 * REST API base
	 */
	private $rest_base = 'notifications';

	/**
	 * Register routes
	 */
	public function register_routes()
	{
		// GET /woonoow/v1/notifications/channels
		register_rest_route($this->namespace, '/' . $this->rest_base . '/channels', [
			[
				'methods' => 'GET',
				'callback' => [$this, 'get_channels'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// GET /woonoow/v1/notifications/events
		register_rest_route($this->namespace, '/' . $this->rest_base . '/events', [
			[
				'methods' => 'GET',
				'callback' => [$this, 'get_events'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// POST /woonoow/v1/notifications/events/update
		register_rest_route($this->namespace, '/' . $this->rest_base . '/events/update', [
			[
				'methods' => 'POST',
				'callback' => [$this, 'update_event'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// GET /woonoow/v1/notifications/templates
		register_rest_route($this->namespace, '/' . $this->rest_base . '/templates', [
			[
				'methods' => 'GET',
				'callback' => [$this, 'get_templates'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// GET/POST /woonoow/v1/notifications/templates/:eventId/:channelId
		register_rest_route($this->namespace, '/' . $this->rest_base . '/templates/(?P<eventId>[a-zA-Z0-9_-]+)/(?P<channelId>[a-zA-Z0-9_-]+)', [
			[
				'methods' => 'GET',
				'callback' => [$this, 'get_template'],
				'permission_callback' => [$this, 'check_permission'],
			],
			[
				'methods' => 'POST',
				'callback' => [$this, 'save_template'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// POST /woonoow/v1/notifications/templates
		register_rest_route($this->namespace, '/' . $this->rest_base . '/templates', [
			[
				'methods' => 'POST',
				'callback' => [$this, 'save_template'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// DELETE /woonoow/v1/notifications/templates/:eventId/:channelId
		register_rest_route($this->namespace, '/' . $this->rest_base . '/templates/(?P<eventId>[a-zA-Z0-9_-]+)/(?P<channelId>[a-zA-Z0-9_-]+)', [
			[
				'methods' => 'DELETE',
				'callback' => [$this, 'delete_template'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// GET /woonoow/v1/notifications/push/vapid-key
		register_rest_route($this->namespace, '/' . $this->rest_base . '/push/vapid-key', [
			[
				'methods' => 'GET',
				'callback' => [$this, 'get_vapid_key'],
				'permission_callback' => '__return_true',
			],
		]);

		// POST /woonoow/v1/notifications/push/subscribe
		register_rest_route($this->namespace, '/' . $this->rest_base . '/push/subscribe', [
			[
				'methods' => 'POST',
				'callback' => [$this, 'push_subscribe'],
				'permission_callback' => '__return_true',
			],
		]);

		// POST /woonoow/v1/notifications/push/unsubscribe
		register_rest_route($this->namespace, '/' . $this->rest_base . '/push/unsubscribe', [
			[
				'methods' => 'POST',
				'callback' => [$this, 'push_unsubscribe'],
				'permission_callback' => '__return_true',
			],
		]);

		// GET /woonoow/v1/notifications/email-settings
		register_rest_route($this->namespace, '/' . $this->rest_base . '/email-settings', [
			[
				'methods' => 'GET',
				'callback' => [$this, 'get_email_settings'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// POST /woonoow/v1/notifications/email-settings
		register_rest_route($this->namespace, '/' . $this->rest_base . '/email-settings', [
			[
				'methods' => 'POST',
				'callback' => [$this, 'save_email_settings'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// DELETE /woonoow/v1/notifications/email-settings
		register_rest_route($this->namespace, '/' . $this->rest_base . '/email-settings', [
			[
				'methods' => 'DELETE',
				'callback' => [$this, 'reset_email_settings'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// GET /woonoow/v1/notifications/push/settings
		register_rest_route($this->namespace, '/' . $this->rest_base . '/push/settings', [
			[
				'methods' => 'GET',
				'callback' => [$this, 'get_push_settings'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// POST /woonoow/v1/notifications/push/settings
		register_rest_route($this->namespace, '/' . $this->rest_base . '/push/settings', [
			[
				'methods' => 'POST',
				'callback' => [$this, 'update_push_settings'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// POST /woonoow/v1/notifications/channels/toggle
		register_rest_route($this->namespace, '/' . $this->rest_base . '/channels/toggle', [
			[
				'methods' => 'POST',
				'callback' => [$this, 'toggle_channel'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// GET /woonoow/v1/notifications/staff/events
		register_rest_route($this->namespace, '/' . $this->rest_base . '/staff/events', [
			[
				'methods' => 'GET',
				'callback' => [$this, 'get_staff_events'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// GET /woonoow/v1/notifications/customer/events
		register_rest_route($this->namespace, '/' . $this->rest_base . '/customer/events', [
			[
				'methods' => 'GET',
				'callback' => [$this, 'get_customer_events'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// GET /woonoow/v1/notifications/system-mode
		register_rest_route($this->namespace, '/' . $this->rest_base . '/system-mode', [
			[
				'methods' => 'GET',
				'callback' => [$this, 'get_system_mode'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// POST /woonoow/v1/notifications/system-mode
		register_rest_route($this->namespace, '/' . $this->rest_base . '/system-mode', [
			[
				'methods' => 'POST',
				'callback' => [$this, 'set_system_mode'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// GET /woonoow/v1/notifications/logs
		register_rest_route($this->namespace, '/' . $this->rest_base . '/logs', [
			[
				'methods' => 'GET',
				'callback' => [$this, 'get_logs'],
				'permission_callback' => [$this, 'check_permission'],
			],
		]);

		// POST /woonoow/v1/notifications/templates/:eventId/:channelId/send-test
		register_rest_route($this->namespace, '/' . $this->rest_base . '/templates/(?P<eventId>[a-zA-Z0-9_-]+)/(?P<channelId>[a-zA-Z0-9_-]+)/send-test', [
			[
				'methods' => 'POST',
				'callback' => [$this, 'send_test_email'],
				'permission_callback' => [$this, 'check_permission'],
				'args' => [
					'email' => [
						'required' => true,
						'type' => 'string',
						'sanitize_callback' => 'sanitize_email',
					],
					'recipient' => [
						'default' => 'customer',
						'type' => 'string',
					],
				],
			],
		]);
	}

	/**
	 * Get available notification channels
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function get_channels(WP_REST_Request $request)
	{
		// Get channel enabled states
		$email_enabled = get_option('woonoow_email_notifications_enabled', true);
		$push_enabled = get_option('woonoow_push_notifications_enabled', true);

		$channels = [
			[
				'id' => 'email',
				'label' => __('Email', 'woonoow'),
				'icon' => 'mail',
				'enabled' => (bool) $email_enabled,
				'builtin' => true,
			],
			[
				'id' => 'push',
				'label' => __('Push Notifications', 'woonoow'),
				'icon' => 'bell',
				'enabled' => (bool) $push_enabled,
				'builtin' => true,
			],
		];

		// Allow addons to register their channels
		$channels = apply_filters('woonoow_notification_channels', $channels);

		return new WP_REST_Response($channels, 200);
	}

	/**
	 * Get notification events
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function get_events(WP_REST_Request $request)
	{
		$settings = get_option('woonoow_notification_settings', []);

		// Get all events from EventRegistry (single source of truth)
		$all_events = EventRegistry::get_all_events();

		// Group by category and add settings
		$grouped_events = [];
		foreach ($all_events as $event) {
			$category = $event['category'];
			if (!isset($grouped_events[$category])) {
				$grouped_events[$category] = [];
			}

			// Add channels from settings
			$event_id = $event['id'];
			$event['channels'] = $settings[$event_id]['channels'] ?? [
				'email' => ['enabled' => false, 'recipient' => $event['recipient_type']],
				'push' => ['enabled' => false, 'recipient' => $event['recipient_type']]
			];
			$event['recipients'] = [$event['recipient_type']];

			$grouped_events[$category][] = $event;
		}

		return new WP_REST_Response($grouped_events, 200);
	}

	/**
	 * Get staff notification events (admin/staff recipient)
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function get_staff_events(WP_REST_Request $request)
	{
		$all_events = $this->get_all_events();

		// Filter events where recipient_type is 'staff'
		$staff_events = [];
		foreach ($all_events as $category => $events) {
			$filtered = array_filter($events, function ($event) {
				return ($event['recipient_type'] ?? 'staff') === 'staff';
			});

			if (!empty($filtered)) {
				$staff_events[$category] = array_values($filtered);
			}
		}

		return new WP_REST_Response($staff_events, 200);
	}

	/**
	 * Get customer notification events (customer recipient)
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function get_customer_events(WP_REST_Request $request)
	{
		$all_events = $this->get_all_events();

		// Filter events where recipient_type is 'customer'
		$customer_events = [];
		foreach ($all_events as $category => $events) {
			$filtered = array_filter($events, function ($event) {
				return ($event['recipient_type'] ?? 'staff') === 'customer';
			});

			if (!empty($filtered)) {
				$customer_events[$category] = array_values($filtered);
			}
		}

		return new WP_REST_Response($customer_events, 200);
	}

	/**
	 * Get all events (internal helper)
	 * 
	 * @return array
	 */
	private function get_all_events()
	{
		// Use EventRegistry - same as get_events() but returns ungrouped
		$settings = get_option('woonoow_notification_settings', []);

		// Get all events from EventRegistry (single source of truth)
		$all_events = EventRegistry::get_all_events();

		// Group by category and add settings
		$grouped_events = [];
		foreach ($all_events as $event) {
			$category = $event['category'];
			if (!isset($grouped_events[$category])) {
				$grouped_events[$category] = [];
			}

			// Add channels from settings
			$event_id = $event['id'];
			$event['channels'] = $settings[$event_id]['channels'] ?? [
				'email' => ['enabled' => false, 'recipient' => $event['recipient_type']],
				'push' => ['enabled' => false, 'recipient' => $event['recipient_type']]
			];

			$grouped_events[$category][] = $event;
		}

		return $grouped_events;
	}

	/**
	 * Update event settings
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_event(WP_REST_Request $request)
	{
		$params = $request->get_json_params();
		$event_id = isset($params['eventId']) ? $params['eventId'] : null;
		$channel_id = isset($params['channelId']) ? $params['channelId'] : null;
		$enabled = isset($params['enabled']) ? $params['enabled'] : null;
		$recipient = isset($params['recipient']) ? $params['recipient'] : null;

		if (empty($event_id) || empty($channel_id)) {
			return new WP_Error(
				'invalid_params',
				__('Event ID and Channel ID are required', 'woonoow'),
				['status' => 400]
			);
		}

		// Get current settings
		$settings = get_option('woonoow_notification_settings', []);

		// Update settings
		if (!isset($settings[$event_id])) {
			$settings[$event_id] = ['channels' => []];
		}

		if (!isset($settings[$event_id]['channels'])) {
			$settings[$event_id]['channels'] = [];
		}

		$settings[$event_id]['channels'][$channel_id] = [
			'enabled' => (bool) $enabled,
			'recipient' => $recipient ?? 'admin',
		];

		// Save settings
		update_option('woonoow_notification_settings', $settings, false);

		// Fire action for addons to react
		do_action('woonoow_notification_event_updated', $event_id, $channel_id, $enabled, $recipient);

		return new WP_REST_Response([
			'success' => true,
			'message' => __('Event settings updated successfully', 'woonoow'),
		], 200);
	}

	/**
	 * Check if user has permission
	 * 
	 * @return bool
	 */
	public function check_permission()
	{
		return current_user_can('manage_woocommerce') || current_user_can('manage_options');
	}

	/**
	 * Get all templates
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function get_templates(WP_REST_Request $request)
	{
		$templates = TemplateProvider::get_templates();
		return new WP_REST_Response($templates, 200);
	}

	/**
	 * Get single template
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response|WP_Error
	 */
	public function get_template(WP_REST_Request $request)
	{
		$event_id = $request->get_param('eventId');
		$channel_id = $request->get_param('channelId');
		$recipient_type = $request->get_param('recipient') ?? 'customer';

		$template = TemplateProvider::get_template($event_id, $channel_id, $recipient_type);

		if (!$template) {
			return new WP_Error(
				'template_not_found',
				__('Template not found', 'woonoow'),
				['status' => 404]
			);
		}

		// Add event and channel labels for UI
		// Get events from controller method
		$events_response = $this->get_events(new WP_REST_Request());
		$events_data = $events_response->get_data();

		// Get channels from controller method
		$channels_response = $this->get_channels(new WP_REST_Request());
		$channels_data = $channels_response->get_data();

		// Find event label
		foreach ($events_data as $category => $event_list) {
			foreach ($event_list as $event) {
				if ($event['id'] === $event_id) {
					$template['event_label'] = $event['label'];
					break 2;
				}
			}
		}

		// Find channel label
		foreach ($channels_data as $channel) {
			if ($channel['id'] === $channel_id) {
				$template['channel_label'] = $channel['label'];
				break;
			}
		}

		// Add available variables for this event (contextual)
		$template['available_variables'] = EventRegistry::get_variables_for_event($event_id, $recipient_type);

		return new WP_REST_Response($template, 200);
	}

	/**
	 * Save template
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response|WP_Error
	 */
	public function save_template(WP_REST_Request $request)
	{
		$event_id = $request->get_param('eventId');
		$channel_id = $request->get_param('channelId');
		$recipient_type = $request->get_param('recipient') ?? 'customer';
		$subject = $request->get_param('subject');
		$body = $request->get_param('body');
		$variables = $request->get_param('variables');

		$template = [
			'subject' => $subject,
			'body' => $body,
			'variables' => $variables,
		];

		$result = TemplateProvider::save_template($event_id, $channel_id, $template, $recipient_type);

		if (!$result) {
			return new WP_Error(
				'save_failed',
				__('Failed to save template', 'woonoow'),
				['status' => 500]
			);
		}

		return new WP_REST_Response([
			'success' => true,
			'message' => __('Template saved successfully', 'woonoow'),
		], 200);
	}

	/**
	 * Delete template (revert to default)
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function delete_template(WP_REST_Request $request)
	{
		$event_id = $request->get_param('eventId');
		$channel_id = $request->get_param('channelId');
		$recipient_type = $request->get_param('recipient') ?? 'customer';

		TemplateProvider::delete_template($event_id, $channel_id, $recipient_type);

		return new WP_REST_Response([
			'success' => true,
			'message' => __('Template reverted to default', 'woonoow'),
		], 200);
	}

	/**
	 * Get VAPID public key for push notifications
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function get_vapid_key(WP_REST_Request $request)
	{
		$public_key = PushNotificationHandler::get_public_key();

		return new WP_REST_Response([
			'publicKey' => $public_key,
		], 200);
	}

	/**
	 * Subscribe to push notifications
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response|WP_Error
	 */
	public function push_subscribe(WP_REST_Request $request)
	{
		$subscription = $request->get_param('subscription');
		$user_id = get_current_user_id();

		if (empty($subscription)) {
			return new WP_Error(
				'invalid_subscription',
				__('Subscription data is required', 'woonoow'),
				['status' => 400]
			);
		}

		$success = PushNotificationHandler::subscribe($subscription, $user_id);

		if (!$success) {
			return new WP_Error(
				'subscribe_failed',
				__('Failed to subscribe to push notifications', 'woonoow'),
				['status' => 500]
			);
		}

		return new WP_REST_Response([
			'success' => true,
			'message' => __('Subscribed to push notifications', 'woonoow'),
		], 200);
	}

	/**
	 * Unsubscribe from push notifications
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function push_unsubscribe(WP_REST_Request $request)
	{
		$subscription_id = $request->get_param('subscriptionId');

		PushNotificationHandler::unsubscribe($subscription_id);

		return new WP_REST_Response([
			'success' => true,
			'message' => __('Unsubscribed from push notifications', 'woonoow'),
		], 200);
	}

	/**
	 * Get push notification settings
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function get_push_settings(WP_REST_Request $request)
	{
		$settings = PushNotificationHandler::get_settings();

		return new WP_REST_Response($settings, 200);
	}

	/**
	 * Update push notification settings
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function update_push_settings(WP_REST_Request $request)
	{
		$settings = $request->get_json_params();

		if (empty($settings)) {
			return new WP_Error(
				'invalid_settings',
				__('Settings data is required', 'woonoow'),
				['status' => 400]
			);
		}

		$success = PushNotificationHandler::update_settings($settings);

		if (!$success) {
			return new WP_Error(
				'update_failed',
				__('Failed to update push notification settings', 'woonoow'),
				['status' => 500]
			);
		}

		return new WP_REST_Response([
			'success' => true,
			'message' => __('Push notification settings updated', 'woonoow'),
			'settings' => PushNotificationHandler::get_settings(),
		], 200);
	}

	/**
	 * Toggle notification channel
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function toggle_channel(WP_REST_Request $request)
	{
		$params = $request->get_json_params();
		$channel_id = isset($params['channelId']) ? $params['channelId'] : null;
		$enabled = isset($params['enabled']) ? $params['enabled'] : null;

		if (empty($channel_id)) {
			return new WP_Error(
				'invalid_channel',
				__('Channel ID is required', 'woonoow'),
				['status' => 400]
			);
		}

		if ($enabled === null) {
			return new WP_Error(
				'invalid_enabled',
				__('Enabled parameter is required', 'woonoow'),
				['status' => 400]
			);
		}

		// Only allow toggling built-in channels
		$option_key = '';
		if ($channel_id === 'email') {
			$option_key = 'woonoow_email_notifications_enabled';
		} elseif ($channel_id === 'push') {
			$option_key = 'woonoow_push_notifications_enabled';
		} else {
			return new WP_Error(
				'invalid_channel',
				__('Invalid channel ID', 'woonoow'),
				['status' => 400]
			);
		}

		// Update the option
		update_option($option_key, (bool) $enabled, false); // false = don't autoload

		// Verify the update
		$verified = get_option($option_key);

		return new WP_REST_Response([
			'success' => true,
			'message' => sprintf(
				__('%s notifications %s', 'woonoow'),
				$channel_id === 'email' ? __('Email', 'woonoow') : __('Push', 'woonoow'),
				$enabled ? __('enabled', 'woonoow') : __('disabled', 'woonoow')
			),
			'channelId' => $channel_id,
			'enabled' => (bool) $verified,
		], 200);
	}

	/**
	 * Get email customization settings
	 */
	public function get_email_settings(WP_REST_Request $request)
	{
		$defaults = [
			'primary_color' => '#7f54b3',
			'secondary_color' => '#7f54b3',
			'hero_gradient_start' => '#667eea',
			'hero_gradient_end' => '#764ba2',
			'hero_text_color' => '#ffffff',
			'button_text_color' => '#ffffff',
			'body_bg_color' => '#f8f8f8',
			'social_icon_color' => 'white',
			'logo_url' => '',
			'header_text' => '',
			'footer_text' => '',
			'social_links' => [],
		];

		$settings = get_option('woonoow_email_settings', $defaults);

		// Ensure social_links is an array
		if (!isset($settings['social_links']) || !is_array($settings['social_links'])) {
			$settings['social_links'] = [];
		}

		// Merge with defaults to ensure all fields exist
		$settings = array_merge($defaults, $settings);

		return new WP_REST_Response($settings, 200);
	}

	/**
	 * Save email customization settings
	 */
	public function save_email_settings(WP_REST_Request $request)
	{
		$data = $request->get_json_params();

		$settings = [
			'primary_color' => sanitize_hex_color($data['primary_color'] ?? '#7f54b3'),
			'secondary_color' => sanitize_hex_color($data['secondary_color'] ?? '#7f54b3'),
			'hero_gradient_start' => sanitize_hex_color($data['hero_gradient_start'] ?? '#667eea'),
			'hero_gradient_end' => sanitize_hex_color($data['hero_gradient_end'] ?? '#764ba2'),
			'hero_text_color' => sanitize_hex_color($data['hero_text_color'] ?? '#ffffff'),
			'button_text_color' => sanitize_hex_color($data['button_text_color'] ?? '#ffffff'),
			'body_bg_color' => sanitize_hex_color($data['body_bg_color'] ?? '#f8f8f8'),
			'social_icon_color' => in_array($data['social_icon_color'] ?? 'white', ['white', 'black']) ? $data['social_icon_color'] : 'white',
			'logo_url' => esc_url_raw($data['logo_url'] ?? ''),
			'header_text' => sanitize_text_field($data['header_text'] ?? ''),
			'footer_text' => sanitize_text_field($data['footer_text'] ?? ''),
			'social_links' => $this->sanitize_social_links($data['social_links'] ?? []),
		];

		update_option('woonoow_email_settings', $settings);

		return new WP_REST_Response([
			'success' => true,
			'message' => __('Email settings saved successfully', 'woonoow'),
			'settings' => $settings,
		], 200);
	}

	/**
	 * Reset email customization settings to defaults
	 */
	public function reset_email_settings(WP_REST_Request $request)
	{
		delete_option('woonoow_email_settings');

		return new WP_REST_Response([
			'success' => true,
			'message' => __('Email settings reset to defaults', 'woonoow'),
		], 200);
	}

	/**
	 * Sanitize social links array
	 */
	private function sanitize_social_links($links)
	{
		if (!is_array($links)) {
			return [];
		}

		$sanitized = [];
		$allowed_platforms = ['facebook', 'x', 'instagram', 'linkedin', 'youtube', 'discord', 'spotify', 'telegram', 'whatsapp', 'threads', 'website'];

		foreach ($links as $link) {
			if (!is_array($link) || !isset($link['platform']) || !isset($link['url'])) {
				continue;
			}

			$platform = sanitize_text_field($link['platform']);
			$url = esc_url_raw($link['url']);

			if (in_array($platform, $allowed_platforms) && !empty($url)) {
				$sanitized[] = [
					'platform' => $platform,
					'url' => $url,
				];
			}
		}

		return $sanitized;
	}

	/**
	 * Get notification system mode
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function get_system_mode(WP_REST_Request $request)
	{
		$mode = get_option('woonoow_notification_system_mode', 'woonoow');

		return new WP_REST_Response([
			'mode' => $mode,
			'available_modes' => [
				'woonoow' => __('WooNooW Notifications', 'woonoow'),
				'woocommerce' => __('WooCommerce Default Emails', 'woonoow'),
			],
		], 200);
	}

	/**
	 * Set notification system mode
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response|WP_Error
	 */
	public function set_system_mode(WP_REST_Request $request)
	{
		$params = $request->get_json_params();
		$mode = isset($params['mode']) ? $params['mode'] : null;

		if (!in_array($mode, ['woonoow', 'woocommerce'])) {
			return new WP_Error(
				'invalid_mode',
				__('Invalid notification system mode', 'woonoow'),
				['status' => 400]
			);
		}

		// Update the mode
		update_option('woonoow_notification_system_mode', $mode);

		// Trigger action for other systems to react
		do_action('woonoow_notification_system_mode_changed', $mode);

		return new WP_REST_Response([
			'success' => true,
			'mode' => $mode,
			'message' => sprintf(
				__('Notification system switched to %s', 'woonoow'),
				$mode === 'woonoow' ? __('WooNooW', 'woonoow') : __('WooCommerce', 'woonoow')
			),
		], 200);
	}

	/**
	 * Get notification activity logs
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response
	 */
	public function get_logs(WP_REST_Request $request)
	{
		$page = (int) $request->get_param('page') ?: 1;
		$per_page = (int) $request->get_param('per_page') ?: 20;
		$channel = $request->get_param('channel');
		$status = $request->get_param('status');
		$search = $request->get_param('search');

		// Get logs from option (in a real app, use a custom table)
		$all_logs = get_option('woonoow_notification_logs', []);

		// Apply filters
		if ($channel && $channel !== 'all') {
			$all_logs = array_filter($all_logs, fn($log) => $log['channel'] === $channel);
		}

		if ($status && $status !== 'all') {
			$all_logs = array_filter($all_logs, fn($log) => $log['status'] === $status);
		}

		if ($search) {
			$search_lower = strtolower($search);
			$all_logs = array_filter($all_logs, function ($log) use ($search_lower) {
				return strpos(strtolower($log['recipient'] ?? ''), $search_lower) !== false ||
					strpos(strtolower($log['subject'] ?? ''), $search_lower) !== false;
			});
		}

		// Sort by date descending
		usort($all_logs, function ($a, $b) {
			return strtotime($b['created_at'] ?? '') - strtotime($a['created_at'] ?? '');
		});

		$total = count($all_logs);
		$offset = ($page - 1) * $per_page;
		$logs = array_slice(array_values($all_logs), $offset, $per_page);

		return new WP_REST_Response([
			'logs' => $logs,
			'total' => $total,
			'page' => $page,
			'per_page' => $per_page,
		], 200);
	}

	/**
	 * Send test email for a notification template
	 * 
	 * @param WP_REST_Request $request Request object
	 * @return WP_REST_Response|WP_Error
	 */
	public function send_test_email(WP_REST_Request $request)
	{
		$event_id = $request->get_param('eventId');
		$channel_id = $request->get_param('channelId');
		$recipient_type = $request->get_param('recipient') ?? 'customer';
		$to_email = $request->get_param('email');

		// Validate email
		if (!is_email($to_email)) {
			return new \WP_Error(
				'invalid_email',
				__('Invalid email address', 'woonoow'),
				['status' => 400]
			);
		}

		// Only support email channel for test
		if ($channel_id !== 'email') {
			return new \WP_Error(
				'unsupported_channel',
				__('Test sending is only available for email channel', 'woonoow'),
				['status' => 400]
			);
		}

		// Get template
		$template = TemplateProvider::get_template($event_id, $channel_id, $recipient_type);

		if (!$template) {
			return new \WP_Error(
				'template_not_found',
				__('Template not found', 'woonoow'),
				['status' => 404]
			);
		}

		// Build sample data for variables
		$sample_data = $this->get_sample_data_for_event($event_id);

		// Replace variables in subject and body
		$subject = '[TEST] ' . $this->replace_variables($template['subject'] ?? '', $sample_data);
		$body_markdown = $this->replace_variables($template['body'] ?? '', $sample_data);

		// Render email using EmailRenderer
		$email_renderer = \WooNooW\Core\Notifications\EmailRenderer::instance();

		// We need to manually render since we're not triggering a real event
		$html = $this->render_test_email($body_markdown, $subject, $sample_data);

		// Set content type to HTML
		$headers = ['Content-Type: text/html; charset=UTF-8'];

		// Send email
		$sent = wp_mail($to_email, $subject, $html, $headers);

		if (!$sent) {
			return new \WP_Error(
				'send_failed',
				__('Failed to send test email. Check your mail server configuration.', 'woonoow'),
				['status' => 500]
			);
		}

		return new WP_REST_Response([
			'success' => true,
			'message' => sprintf(__('Test email sent to %s', 'woonoow'), $to_email),
		], 200);
	}

	/**
	 * Get sample data for an event type
	 * 
	 * @param string $event_id
	 * @return array
	 */
	private function get_sample_data_for_event($event_id)
	{
		$base_data = [
			'site_name' => get_bloginfo('name'),
			'store_name' => get_bloginfo('name'),
			'site_url' => home_url(),
			'shop_url' => get_permalink(wc_get_page_id('shop')),
			'my_account_url' => get_permalink(wc_get_page_id('myaccount')),
			'support_email' => get_option('admin_email'),
			'current_year' => date('Y'),
			'customer_name' => 'John Doe',
			'customer_first_name' => 'John',
			'customer_last_name' => 'Doe',
			'customer_email' => 'john@example.com',
			'customer_phone' => '+1 234 567 8900',
			'login_url' => wp_login_url(),
		];

		// Order-related events
		if (strpos($event_id, 'order') !== false) {
			$base_data = array_merge($base_data, [
				'order_number' => '12345',
				'order_id' => '12345',
				'order_date' => date('F j, Y'),
				'order_total' => wc_price(129.99),
				'order_subtotal' => wc_price(109.99),
				'order_tax' => wc_price(10.00),
				'order_shipping' => wc_price(10.00),
				'order_discount' => wc_price(0),
				'order_status' => 'Processing',
				'order_url' => '#',
				'payment_method' => 'Credit Card',
				'payment_status' => 'Paid',
				'payment_date' => date('F j, Y'),
				'transaction_id' => 'TXN123456789',
				'shipping_method' => 'Standard Shipping',
				'estimated_delivery' => date('F j', strtotime('+3 days')) . '-' . date('j', strtotime('+5 days')),
				'completion_date' => date('F j, Y'),
				'billing_address' => '123 Main St, City, State 12345, Country',
				'shipping_address' => '123 Main St, City, State 12345, Country',
				'tracking_number' => 'TRACK123456',
				'tracking_url' => '#',
				'shipping_carrier' => 'Standard Carrier',
				'payment_retry_url' => '#',
				'review_url' => '#',
				'order_items' => $this->get_sample_order_items_html(),
				'order_items_table' => $this->get_sample_order_items_html(),
			]);
		}

		// Customer account events
		if (strpos($event_id, 'customer') !== false || strpos($event_id, 'account') !== false) {
			$base_data = array_merge($base_data, [
				'customer_username' => 'johndoe',
				'user_temp_password' => 'SamplePass123',
				'reset_link' => '#',
				'reset_key' => 'abc123xyz',
				'user_login' => 'johndoe',
				'user_email' => 'john@example.com',
			]);
		}

		return $base_data;
	}

	/**
	 * Get sample order items HTML
	 * 
	 * @return string
	 */
	private function get_sample_order_items_html()
	{
		return '<table style="width: 100%; border-collapse: collapse; margin: 16px 0;">
			<thead>
				<tr style="background: #f5f5f5;">
					<th style="padding: 12px; text-align: left; border-bottom: 2px solid #ddd;">Product</th>
					<th style="padding: 12px; text-align: center; border-bottom: 2px solid #ddd;">Qty</th>
					<th style="padding: 12px; text-align: right; border-bottom: 2px solid #ddd;">Price</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td style="padding: 12px; border-bottom: 1px solid #eee;">
						<strong>Sample Product</strong><br>
						<span style="color: #666; font-size: 13px;">Size: M, Color: Blue</span>
					</td>
					<td style="padding: 12px; text-align: center; border-bottom: 1px solid #eee;">2</td>
					<td style="padding: 12px; text-align: right; border-bottom: 1px solid #eee;">' . wc_price(59.98) . '</td>
				</tr>
				<tr>
					<td style="padding: 12px; border-bottom: 1px solid #eee;">
						<strong>Another Product</strong><br>
						<span style="color: #666; font-size: 13px;">Option: Standard</span>
					</td>
					<td style="padding: 12px; text-align: center; border-bottom: 1px solid #eee;">1</td>
					<td style="padding: 12px; text-align: right; border-bottom: 1px solid #eee;">' . wc_price(50.01) . '</td>
				</tr>
			</tbody>
		</table>';
	}

	/**
	 * Replace variables in text
	 * 
	 * @param string $text
	 * @param array $variables
	 * @return string
	 */
	private function replace_variables($text, $variables)
	{
		foreach ($variables as $key => $value) {
			$text = str_replace('{' . $key . '}', $value, $text);
		}
		return $text;
	}

	/**
	 * Render test email HTML
	 * 
	 * @param string $body_markdown
	 * @param string $subject
	 * @param array $variables
	 * @return string
	 */
	private function render_test_email($body_markdown, $subject, $variables)
	{
		// Parse cards
		$content = $this->parse_cards_for_test($body_markdown);

		// Get appearance settings for colors
		$appearance = get_option('woonoow_appearance_settings', []);
		$colors = $appearance['general']['colors'] ?? [];
		$primary_color = $colors['primary'] ?? '#7f54b3';
		$secondary_color = $colors['secondary'] ?? '#7f54b3';
		$hero_gradient_start = $colors['gradientStart'] ?? '#667eea';
		$hero_gradient_end = $colors['gradientEnd'] ?? '#764ba2';

		// Get email settings for branding
		$email_settings = get_option('woonoow_email_settings', []);
		$logo_url = $email_settings['logo_url'] ?? '';
		$header_text = $email_settings['header_text'] ?? $variables['store_name'];
		$footer_text = $email_settings['footer_text'] ?? sprintf('© %s %s. All rights reserved.', date('Y'), $variables['store_name']);
		$footer_text = str_replace('{current_year}', date('Y'), $footer_text);

		// Build header
		if (!empty($logo_url)) {
			$header = sprintf(
				'<a href="%s"><img src="%s" alt="%s" style="max-width: 200px; max-height: 60px;"></a>',
				esc_url($variables['site_url']),
				esc_url($logo_url),
				esc_attr($variables['store_name'])
			);
		} else {
			$header = sprintf(
				'<a href="%s" style="font-size: 24px; font-weight: 700; color: #333; text-decoration: none;">%s</a>',
				esc_url($variables['site_url']),
				esc_html($header_text)
			);
		}

		// Build full HTML
		$html = '<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>' . esc_html($subject) . '</title>
	<style>
		body { font-family: "Inter", Arial, sans-serif; background: #f8f8f8; margin: 0; padding: 20px; }
		.container { max-width: 600px; margin: 0 auto; }
		.header { padding: 32px; text-align: center; background: #f8f8f8; }
		.card-gutter { padding: 0 16px; }
		.card { background: #ffffff; border-radius: 8px; margin-bottom: 24px; padding: 32px 40px; width: 100%; box-sizing: border-box; }
		.card-hero { background: linear-gradient(135deg, ' . esc_attr($hero_gradient_start) . ' 0%, ' . esc_attr($hero_gradient_end) . ' 100%); color: #ffffff; }
		.card-hero * { color: #ffffff !important; }
		.card-success { background-color: #f0fdf4; }
		.card-info { background-color: #f0f7ff; }
		.card-warning { background-color: #fff8e1; }
		.card-basic { background: none; padding: 0; }
		h1, h2, h3 { margin-top: 0; color: #333; }
		p { font-size: 16px; line-height: 1.6; color: #555; margin-bottom: 16px; }
		.button { display: inline-block; background: ' . esc_attr($primary_color) . '; color: #ffffff !important; padding: 14px 28px; border-radius: 6px; text-decoration: none; font-weight: 600; }
		.button-outline { display: inline-block; background: transparent; color: ' . esc_attr($secondary_color) . ' !important; padding: 12px 26px; border: 2px solid ' . esc_attr($secondary_color) . '; border-radius: 6px; text-decoration: none; font-weight: 600; }
		.footer { padding: 32px; text-align: center; color: #888; font-size: 13px; }
	</style>
</head>
<body>
	<div class="container">
		<div class="header">' . $header . '</div>
		<div class="card-gutter">' . $content . '</div>
		<div class="footer"><p>' . nl2br(esc_html($footer_text)) . '</p></div>
	</div>
</body>
</html>';

		return $html;
	}

	/**
	 * Parse cards for test email
	 * 
	 * @param string $content
	 * @return string
	 */
	private function parse_cards_for_test($content)
	{
		// Parse [card:type] syntax
		$content = preg_replace_callback(
			'/\[card:(\w+)\](.*?)\[\/card\]/s',
			function ($matches) {
				$type = $matches[1];
				$card_content = $this->markdown_to_html($matches[2]);
				return '<div class="card card-' . esc_attr($type) . '">' . $card_content . '</div>';
			},
			$content
		);

		// Parse [card type="..."] syntax
		$content = preg_replace_callback(
			'/\[card([^\]]*)\](.*?)\[\/card\]/s',
			function ($matches) {
				$attrs = $matches[1];
				$card_content = $this->markdown_to_html($matches[2]);
				$type = 'default';
				if (preg_match('/type=["\']([^"\']+)["\']/', $attrs, $type_match)) {
					$type = $type_match[1];
				}
				return '<div class="card card-' . esc_attr($type) . '">' . $card_content . '</div>';
			},
			$content
		);

		// Parse buttons - new [button:style](url)Text[/button] syntax
		$content = preg_replace_callback(
			'/\[button:(\w+)\]\(([^)]+)\)([^\[]+)\[\/button\]/',
			function ($matches) {
				$style = $matches[1];
				$url = $matches[2];
				$text = trim($matches[3]);
				$class = $style === 'outline' ? 'button-outline' : 'button';
				// Don't escape URLs with variable placeholders
				$escaped_url = preg_match('/\{[a-z_]+\}/', $url) ? $url : esc_url($url);
				return '<p style="text-align: center;"><a href="' . $escaped_url . '" class="' . $class . '">' . esc_html($text) . '</a></p>';
			},
			$content
		);

		// Parse buttons - old [button url="..." style="..."]Text[/button] syntax
		$content = preg_replace_callback(
			'/\[button\s+url=["\']([^"\']+)["\'](?:\s+style=["\'](\w+)["\'])?\]([^\[]+)\[\/button\]/',
			function ($matches) {
				$url = $matches[1];
				$style = $matches[2] ?? 'solid';
				$text = trim($matches[3]);
				$class = $style === 'outline' ? 'button-outline' : 'button';
				// Don't escape URLs with variable placeholders
				$escaped_url = preg_match('/\{[a-z_]+\}/', $url) ? $url : esc_url($url);
				return '<p style="text-align: center;"><a href="' . $escaped_url . '" class="' . $class . '">' . esc_html($text) . '</a></p>';
			},
			$content
		);

		// If no cards found, wrap in default card
		if (strpos($content, '<div class="card') === false) {
			$content = '<div class="card">' . $this->markdown_to_html($content) . '</div>';
		}

		return $content;
	}

	/**
	 * Basic markdown to HTML conversion
	 * 
	 * @param string $text
	 * @return string
	 */
	private function markdown_to_html($text)
	{
		// Parse buttons FIRST - new [button:style](url)Text[/button] syntax
		$text = preg_replace_callback(
			'/\[button:(\w+)\]\(([^)]+)\)([^\[]+)\[\/button\]/',
			function ($matches) {
				$style = $matches[1];
				$url = $matches[2];
				$btn_text = trim($matches[3]);
				$class = $style === 'outline' ? 'button-outline' : 'button';
				// Don't escape URLs with variable placeholders
				$escaped_url = preg_match('/\{[a-z_]+\}/', $url) ? $url : esc_url($url);
				return '<p style="text-align: center;"><a href="' . $escaped_url . '" class="' . $class . '">' . esc_html($btn_text) . '</a></p>';
			},
			$text
		);

		// Parse buttons - old [button url="..."] syntax
		$text = preg_replace_callback(
			'/\[button\s+url=["\']([^"\']+)["\'](?:\s+style=[\'"](\\w+)[\'"])?\]([^\[]+)\[\/button\]/',
			function ($matches) {
				$url = $matches[1];
				$style = $matches[2] ?? 'solid';
				$btn_text = trim($matches[3]);
				$class = $style === 'outline' ? 'button-outline' : 'button';
				// Don't escape URLs with variable placeholders
				$escaped_url = preg_match('/\{[a-z_]+\}/', $url) ? $url : esc_url($url);
				return '<p style="text-align: center;"><a href="' . $escaped_url . '" class="' . $class . '">' . esc_html($btn_text) . '</a></p>';
			},
			$text
		);

		// Headers
		$text = preg_replace('/^### (.+)$/m', '<h3>$1</h3>', $text);
		$text = preg_replace('/^## (.+)$/m', '<h2>$1</h2>', $text);
		$text = preg_replace('/^# (.+)$/m', '<h1>$1</h1>', $text);

		// Bold
		$text = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $text);

		// Italic
		$text = preg_replace('/\*(.+?)\*/', '<em>$1</em>', $text);

		// Links (but not button syntax - already handled above)
		$text = preg_replace('/\[(?!button)([^\]]+)\]\(([^)]+)\)/', '<a href="$2">$1</a>', $text);

		// List items
		$text = preg_replace('/^- (.+)$/m', '<li>$1</li>', $text);
		$text = preg_replace('/(<li>.*<\/li>)/s', '<ul>$1</ul>', $text);

		// Paragraphs - wrap lines that aren't already wrapped
		$lines = explode("\n", $text);
		$result = [];
		foreach ($lines as $line) {
			$line = trim($line);
			if (empty($line)) continue;
			if (!preg_match('/^<(h[1-6]|ul|li|div|p|table|tr|td|th)/', $line)) {
				$line = '<p>' . $line . '</p>';
			}
			$result[] = $line;
		}

		return implode("\n", $result);
	}
}
