<?php
/**
 * Notification System - Main Engine
 *
 * @package KNS_Dynamic_Discounts
 */

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

/**
 * Main notification system class
 */
class KNSDD_Notifications {

	/**
	 * Singleton instance
	 *
	 * @var KNSDD_Notifications|null
	 */
	private static $instance = null;

	/**
	 * Registered notification types
	 *
	 * @var KNSDD_INotificationType[]
	 */
	private $types = array();

	/**
	 * Get singleton instance
	 *
	 * @return KNSDD_Notifications
	 */
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor
	 */
	private function __construct() {
		// Register notification types
		add_action( 'init', array( $this, 'register_types' ), 5 );

		// Admin hooks
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'admin_footer', array( $this, 'render_fab' ) );

		// AJAX handlers
		add_action( 'wp_ajax_knsdd_get_notifications', array( $this, 'ajax_get_notifications' ) );
		add_action( 'wp_ajax_knsdd_dismiss_notification', array( $this, 'ajax_dismiss_notification' ) );
		add_action( 'wp_ajax_knsdd_mark_notification_read', array( $this, 'ajax_mark_notification_read' ) );

		// Cache invalidation hooks
		add_action( 'knsdd_group_updated', array( $this, 'invalidate_cache' ) );
		add_action( 'knsdd_rules_updated', array( $this, 'invalidate_cache' ) );

		// Cron job - only if notifications are enabled
		$settings = get_option( 'knsdd_global_settings', array() );
		$notifications_enabled = isset( $settings['notifications_enabled'] ) ? $settings['notifications_enabled'] : 1;
		
		if ( $notifications_enabled ) {
			add_action( 'knsdd_check_notifications_cron', array( $this, 'cron_check' ) );
			if ( ! wp_next_scheduled( 'knsdd_check_notifications_cron' ) ) {
				wp_schedule_event( time(), 'twicedaily', 'knsdd_check_notifications_cron' );
			}
		} else {
			// Clear scheduled cron if notifications are disabled
			$timestamp = wp_next_scheduled( 'knsdd_check_notifications_cron' );
			if ( $timestamp ) {
				wp_unschedule_event( $timestamp, 'knsdd_check_notifications_cron' );
			}
		}
	}

	/**
	 * Register notification types
	 */
	public function register_types() {
		// Load notification type files
		require_once KNSDD_PLUGIN_DIR . 'includes/notifications/types/class-notification-campaign-ending.php';
		require_once KNSDD_PLUGIN_DIR . 'includes/notifications/types/class-notification-campaign-starting.php';
		require_once KNSDD_PLUGIN_DIR . 'includes/notifications/types/class-notification-campaign-status.php';

		// Register types
		$this->types = array(
			new KNSDD_Notification_Campaign_Ending(),
			new KNSDD_Notification_Campaign_Starting(),
			new KNSDD_Notification_Campaign_Status(),
		);

		// Allow third-party registration
		$this->types = apply_filters( 'knsdd_register_notification_types', $this->types );
	}

	/**
	 * Get all notifications
	 *
	 * @param bool $force_refresh Force cache refresh
	 * @return array
	 */
	public function get_notifications( $force_refresh = false ) {
		// Check if notifications are enabled
		$settings = get_option( 'knsdd_global_settings', array() );
		$notifications_enabled = isset( $settings['notifications_enabled'] ) ? $settings['notifications_enabled'] : 1;
		
		if ( ! $notifications_enabled ) {
			return array();
		}

		$cache_key = 'knsdd_notifications';

		if ( ! $force_refresh ) {
			$cached = get_transient( $cache_key );
			if ( false !== $cached && is_array( $cached ) ) {
				return $cached;
			}
		}

		$notifications = array();

		// Run all registered types
		foreach ( $this->types as $type ) {
			if ( $type->is_enabled() ) {
				$type_notifications = $type->check();
				if ( is_array( $type_notifications ) ) {
					$notifications = array_merge( $notifications, $type_notifications );
				}
			}
		}

		// Sort by priority (highest first)
		usort( $notifications, function( $a, $b ) {
			$priority_a = isset( $a['priority'] ) ? (int) $a['priority'] : 50;
			$priority_b = isset( $b['priority'] ) ? (int) $b['priority'] : 50;
			return $priority_b - $priority_a;
		});

		// Limit to 100 notifications
		$notifications = array_slice( $notifications, 0, 100 );

		// Cache for 1 hour
		set_transient( $cache_key, $notifications, HOUR_IN_SECONDS );

		return $notifications;
	}

	/**
	 * Get unread notification count
	 *
	 * @return int
	 */
	public function get_unread_count() {
		$all_notifications = $this->get_notifications();
		$dismissed = $this->get_dismissed_notifications();

		$unread = array_filter( $all_notifications, function( $notification ) use ( $dismissed ) {
			$id = isset( $notification['id'] ) ? $notification['id'] : '';
			return ! in_array( $id, $dismissed, true );
		});

		return count( $unread );
	}

	/**
	 * Get dismissed notifications from cookie
	 *
	 * @return array
	 */
	private function get_dismissed_notifications() {
		$cookie_name = 'knsdd_dismissed_notifications';
		if ( isset( $_COOKIE[ $cookie_name ] ) ) {
			// Sanitize cookie data before json_decode (WordPress.org requirement)
			$raw = sanitize_text_field( wp_unslash( $_COOKIE[ $cookie_name ] ) );
			$dismissed = json_decode( $raw, true );
			return is_array( $dismissed ) ? $dismissed : array();
		}
		return array();
	}

	/**
	 * Enqueue admin assets
	 *
	 * @param string $hook Current admin page hook
	 */
	public function enqueue_assets( $hook ) {
		// Only load on KNSDD pages
		if ( strpos( $hook, 'kns-dynamic-discounts-for-woocommerce' ) === false ) {
			return;
		}

		// Iconify for notification icons - Yerel dosya (WordPress.org uyumluluğu)
		wp_enqueue_script(
			'iconify',
			KNSDD_PLUGIN_URL . 'assets/js/vendor/iconify.min.js',
			array(),
			'3.1.1',
			true
		);

		// CSS
		wp_enqueue_style(
			'knsdd-notifications',
			KNSDD_PLUGIN_URL . 'assets/css/notifications.css',
			array(),
			KNSDD_VERSION
		);

		// JavaScript
		wp_enqueue_script(
			'knsdd-notifications',
			KNSDD_PLUGIN_URL . 'assets/js/notifications.js',
			array( 'jquery', 'iconify' ),
			KNSDD_VERSION,
			true
		);

		// Localize script
		wp_localize_script(
			'knsdd-notifications',
			'knsddNotifications',
			array(
				'ajaxUrl'    => admin_url( 'admin-ajax.php' ),
				'nonce'      => wp_create_nonce( 'knsdd_notifications' ),
				'i18n'       => KNSDD_I18n::get_notifications_js_i18n(),
			)
		);
	}

	/**
	 * Render FAB (Floating Action Button)
	 */
	public function render_fab() {
		// Check if notifications are enabled
		$settings = get_option( 'knsdd_global_settings', array() );
		$notifications_enabled = isset( $settings['notifications_enabled'] ) ? $settings['notifications_enabled'] : 1;
		
		if ( ! $notifications_enabled ) {
			return;
		}

		// Only on KNSDD pages
		$screen = get_current_screen();
		if ( ! $screen || strpos( $screen->id, 'kns-dynamic-discounts-for-woocommerce' ) === false ) {
			return;
		}

		// Check capability
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		require_once KNSDD_PLUGIN_DIR . 'includes/notifications/class-knsdd-notification-renderer.php';
		$renderer = new KNSDD_Notification_Renderer();
		$renderer->render_fab( $this->get_unread_count() );
	}

	/**
	 * AJAX: Get notifications
	 */
	public function ajax_get_notifications() {
		// Security checks
		check_ajax_referer( 'knsdd_notifications', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kns-dynamic-discounts-for-woocommerce' ) ), 403 );
		}

		// Check if notifications are enabled
		$settings = get_option( 'knsdd_global_settings', array() );
		$notifications_enabled = isset( $settings['notifications_enabled'] ) ? $settings['notifications_enabled'] : 1;
		
		if ( ! $notifications_enabled ) {
			wp_send_json_success( array(
				'notifications' => array(),
				'total'         => 0,
				'offset'        => 0,
				'limit'         => 0,
				'hasMore'       => false,
			) );
		}

		$offset = isset( $_POST['offset'] ) ? absint( $_POST['offset'] ) : 0;
		$limit  = isset( $_POST['limit'] ) ? absint( $_POST['limit'] ) : 20;

		$all_notifications = $this->get_notifications();
		$dismissed = $this->get_dismissed_notifications();

		// Filter out dismissed
		$active_notifications = array_filter( $all_notifications, function( $notification ) use ( $dismissed ) {
			$id = isset( $notification['id'] ) ? $notification['id'] : '';
			return ! in_array( $id, $dismissed, true );
		});

		// Re-index array
		$active_notifications = array_values( $active_notifications );

		// Paginate
		$total = count( $active_notifications );
		$notifications = array_slice( $active_notifications, $offset, $limit );

		wp_send_json_success( array(
			'notifications' => $notifications,
			'total'         => $total,
			'offset'        => $offset,
			'limit'         => $limit,
			'hasMore'       => ( $offset + $limit ) < $total,
		) );
	}

	/**
	 * AJAX: Dismiss notification
	 */
	public function ajax_dismiss_notification() {
		// Security checks
		check_ajax_referer( 'knsdd_notifications', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kns-dynamic-discounts-for-woocommerce' ) ), 403 );
		}

		$notification_id = isset( $_POST['notification_id'] ) ? sanitize_text_field( wp_unslash( $_POST['notification_id'] ) ) : '';

		if ( empty( $notification_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Geçersiz bildirim.', 'kns-dynamic-discounts-for-woocommerce' ) ) );
		}

		// Get current dismissed list
		$dismissed = $this->get_dismissed_notifications();
		
		// Add new ID
		if ( ! in_array( $notification_id, $dismissed, true ) ) {
			$dismissed[] = $notification_id;
		}

		// Save to cookie (30 days)
		setcookie(
			'knsdd_dismissed_notifications',
			wp_json_encode( $dismissed ),
			time() + ( 30 * DAY_IN_SECONDS ),
			COOKIEPATH,
			COOKIE_DOMAIN,
			is_ssl(),
			true
		);

		wp_send_json_success( array(
			'message'      => __( 'Bildirim kapatıldı.', 'kns-dynamic-discounts-for-woocommerce' ),
			'unreadCount'  => $this->get_unread_count() - 1,
		) );
	}

	/**
	 * AJAX: Mark notification as read (without dismissing)
	 */
	public function ajax_mark_notification_read() {
		// Security checks
		check_ajax_referer( 'knsdd_notifications', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kns-dynamic-discounts-for-woocommerce' ) ), 403 );
		}

		$notification_id = isset( $_POST['notification_id'] ) ? sanitize_text_field( wp_unslash( $_POST['notification_id'] ) ) : '';

		if ( empty( $notification_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Geçersiz bildirim.', 'kns-dynamic-discounts-for-woocommerce' ) ) );
		}

		// Just return success with updated count
		// We don't add to dismissed list, so notification stays visible
		wp_send_json_success( array(
			'message'      => __( 'Bildirim okundu olarak işaretlendi.', 'kns-dynamic-discounts-for-woocommerce' ),
			'unreadCount'  => $this->get_unread_count() - 1,
		) );
	}

	/**
	 * Invalidate cache
	 */
	public function invalidate_cache() {
		delete_transient( 'knsdd_notifications' );
		
		// Also trigger action for third-party integrations
		do_action( 'knsdd_notifications_cache_invalidated' );
	}

	/**
	 * Cron job: Pre-calculate notifications
	 */
	public function cron_check() {
		$this->get_notifications( true );
	}

	/**
	 * Clear notifications for a specific group
	 *
	 * @param string $group_name Group name
	 */
	public static function clear_notifications_for_group( $group_name ) {
		if ( empty( $group_name ) ) {
			return;
		}

		// Invalidate cache to force refresh
		delete_transient( 'knsdd_notifications' );

		// Clear dismissed notifications for this group from cookie
		$dismissed = array();
		if ( isset( $_COOKIE['knsdd_dismissed_notifications'] ) ) {
			// Sanitize cookie data before json_decode (WordPress.org requirement)
			$raw = sanitize_text_field( wp_unslash( $_COOKIE['knsdd_dismissed_notifications'] ) );
			$dismissed = json_decode( $raw, true );
			if ( ! is_array( $dismissed ) ) {
				$dismissed = array();
			}
		}

		// Filter out notifications related to this group
		$dismissed = array_filter( $dismissed, function( $id ) use ( $group_name ) {
			return strpos( $id, $group_name ) === false;
		});

		// Update cookie
		setcookie(
			'knsdd_dismissed_notifications',
			wp_json_encode( array_values( $dismissed ) ),
			time() + ( 30 * DAY_IN_SECONDS ),
			COOKIEPATH,
			COOKIE_DOMAIN,
			is_ssl(),
			true
		);
	}
}
