<?php
/**
 * Notification Manager for Automation Web Platform.
 *
 * Handles database operations for notification rules, languages, and campaigns.
 *
 * @package automation-web-platform
 */

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

/**
 * Class WAWP_Notification_Manager
 *
 * Handles database operations for notification rules, languages, and campaigns.
 */
class WAWP_Notification_Manager {
	use WAWP_Settings_Handler;

	/**
	 * Database object.
	 *
	 * @var wpdb
	 */
	public $wpdb;

	/**
	 * Table prefix.
	 *
	 * @var string
	 */
	private $table_prefix;

	/**
	 * Tables mapping.
	 *
	 * @var array
	 */
	private $tables;

	/**
	 * Constructor.
	 */
	public function __construct() {
		global $wpdb;
		$this->wpdb         = $wpdb;
		$this->table_prefix = $wpdb->prefix . 'wawp_';

		// Map tables (shared with Database_Manager for now to ensure consistency).
		$this->tables = array(
			'languages'    => $this->table_prefix . 'notif_languages',
			'flows'        => $this->table_prefix . 'flows',
			'flow_steps'   => $this->table_prefix . 'flow_steps',
			'flow_meta'    => $this->table_prefix . 'flow_step_meta',
			'translations' => $this->table_prefix . 'flow_translations',
			'campaigns'    => $this->table_prefix . 'campaigns',
			'queue'        => $this->table_prefix . 'campaigns_queue',
		);
	}

	/**
	 * Get all configured notification languages.
	 */
	public function get_languages() {
		global $wpdb;
		$table = $this->tables['languages'];
		$query = $wpdb->prepare( 'SELECT language_code AS code, name, is_main FROM %i ORDER BY is_main DESC, name ASC', $table );

		return WAWP()->db->get_results_cached( $query, 'wawp_notif_languages', 'wawp_notif' );
	}

	/**
	 * Add or update a language.
	 *
	 * @param string $code    Language code.
	 * @param string $name    Language name.
	 * @param int    $is_main Whether it is the main language.
	 */
	public function upsert_language( $code, $name, $is_main = 0 ) {
		WAWP()->db->upsert_row(
			'languages',
			array(
				'language_code' => $code,
				'name'          => $name,
				'is_main'       => $is_main ? 1 : 0,
			)
		);
		wp_cache_delete( 'wawp_notif_languages', 'wawp_notif' );
	}

	/**
	 * Get campaigns list.
	 */
	public function get_campaigns() {
		global $wpdb;
		$table = $this->tables['campaigns'];
		$query = $wpdb->prepare( 'SELECT * FROM %i ORDER BY id DESC', $table );

		return WAWP()->db->get_results_cached( $query, 'wawp_campaigns_list', 'wawp_notif' );
	}

	/**
	 * Get pending queue items for campaigns.
	 *
	 * @param int $limit Max items to return.
	 */
	public function get_campaigns_queue( $limit = 50 ) {
		global $wpdb;
		$table     = $this->tables['queue'];
		$cache_key = 'wawp_campaign_queue_pending_' . (int) $limit;
		$query     = $wpdb->prepare( 'SELECT * FROM %i WHERE status = %s LIMIT %d', $table, 'pending', $limit );

		return WAWP()->db->get_results_cached( $query, $cache_key, 'wawp_notif', 30 );
	}

	/**
	 * Get global notification settings with legacy migration support.
	 */
	public function get_global_settings() {
		$selected_instance_ids       = $this->get_wawp_setting( WAWP_Settings_Registry::NOTIF_SELECTED_INSTANCE_IDS, null );
		$admin_selected_instance_ids = $this->get_wawp_setting( WAWP_Settings_Registry::NOTIF_ADMIN_SELECTED_INSTANCE_IDS, null );

		// Clear dashboard caches to ensure we don't return old data.
		if ( class_exists( 'WAWP_Menu' ) ) {
			WAWP_Menu::clear_all_dashboard_transients();
		} else {
			wp_cache_delete( 'wawp_dashboard_data_full_' . get_current_user_id(), 'wawp_database' );
			delete_transient( 'wawp_dashboard_data_full_' . get_current_user_id() );
		}

		// Fast path: use options if they exist.
		if ( null !== $selected_instance_ids ) {

			return array(
				'selected_instance_ids'       => $selected_instance_ids,
				'admin_selected_instance_ids' => $admin_selected_instance_ids ? $admin_selected_instance_ids : '',
			);
		}

		return array(
			'selected_instance_ids'       => $selected_instance_ids ? $selected_instance_ids : '',
			'admin_selected_instance_ids' => $admin_selected_instance_ids ? $admin_selected_instance_ids : '',
		);
	}

	/**
	 * Update global notification settings.
	 *
	 * @param string $ids_csv       Selected instance IDs.
	 * @param string $admin_ids_csv Admin selected instance IDs.
	 */
	public function set_global_settings( $ids_csv, $admin_ids_csv = '' ) {
		if ( null !== $ids_csv ) {
			$this->update_wawp_setting( WAWP_Settings_Registry::NOTIF_SELECTED_INSTANCE_IDS, $ids_csv );
		}

		if ( null !== $admin_ids_csv ) {
			$this->update_wawp_setting( WAWP_Settings_Registry::NOTIF_ADMIN_SELECTED_INSTANCE_IDS, $admin_ids_csv );
		}
	}
}
