<?php
/**
 * Plugin Name: Mersal Notifications
 * Plugin URI:  https://mersal.it
 * Description: Event-driven WhatsApp / SMS / Email notifications for WordPress & WooCommerce — order status updates, customer & admin alerts, user events — delivered through your connected Mersal account, wearing the Mersal design system.
 * Version:     1.3.1
 * Author:      mersal.it
 * Author URI:  https://mersal.it
 * License:     GPLv3 or later
 * License URI: https://www.gnu.org/licenses/gpl-3.0.html
 * Text Domain: mersal-notifications
 * Domain Path: /languages
 *
 * @package Mersal_Notif
 */

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

define( 'MNOTIF_VERSION', '1.3.1' );
define( 'MNOTIF_FILE', __FILE__ );
define( 'MNOTIF_DIR', plugin_dir_path( __FILE__ ) );
define( 'MNOTIF_URL', plugin_dir_url( __FILE__ ) );
define( 'MNOTIF_MENU_SLUG', 'mersal-notifications' );

if ( ! defined( 'MNOTIF_UPDATE_BASE' ) ) {
	define( 'MNOTIF_UPDATE_BASE', 'https://mersal.it/Wordpress-Plugins' );
}

require_once MNOTIF_DIR . 'includes/class-mersal-notif-settings.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-icons.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-security.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-connect.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-core.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-updater.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-email-templates.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-order-actions.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-chat-widget.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-abandoned-cart.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-integrations.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-email-tracking.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-cache-compat.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-order-statuses.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-library.php';

// Admin-only: loaded only in wp-admin to reduce front-end memory.
if ( is_admin() ) {
	require_once MNOTIF_DIR . 'includes/class-mersal-notif-admin.php';
}

// ---- Mersal Suite: shared unified dashboard (works standalone too) ----
require_once MNOTIF_DIR . 'includes/suite/suite-loader.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-suite-pages.php';
require_once MNOTIF_DIR . 'includes/class-mersal-notif-wizard.php';
mersal_suite_register_sdk( '1.5.0', MNOTIF_DIR . 'includes/suite/class-mersal-suite.php' );
add_action( 'plugins_loaded', 'mnotif_register_suite', 6 );

/**
 * Register Mersal Notifications into the Mersal Suite shell.
 */
function mnotif_register_suite() {
	if ( ! class_exists( 'Mersal_Suite' ) ) {
		return;
	}
	Mersal_Notif_Suite_Pages::init();
	Mersal_Notif_Wizard::init();
	Mersal_Suite::register(
		array(
			'id'            => 'nt',
			'name'          => array( 'ar' => 'مرسال للإشعارات', 'en' => 'Mersal Notifications' ),
			'sub'           => array( 'ar' => 'إشعارات تلقائية', 'en' => 'Auto notifications' ),
			'icon'          => 'notifications',
			'accent'        => '#2f86c9',
			'version'       => MNOTIF_VERSION,
			'order'         => 20,
			'default_route' => 'nt.dash',
			'routes'        => array_merge( Mersal_Notif_Suite_Pages::routes(), Mersal_Suite_Wizard::route_map( 'nt' ) ),
			'nav'           => array(
				array( array( 'ar' => 'نظرة عامة', 'en' => 'Overview' ), array(
					array( 'nt.wizard', array( 'ar' => 'معالج الإعداد', 'en' => 'Setup wizard' ), 'auto_fix_high', Mersal_Suite_Wizard::is_done( 'nt' ) ? array() : array( 'dot' => true ) ),
					array( 'nt.dash', array( 'ar' => 'لوحة التحكم', 'en' => 'Dashboard' ), 'monitoring' ),
				) ),
				array( array( 'ar' => 'القواعد والأتمتة', 'en' => 'Rules & Automation' ), array(
					array( 'nt.rules', array( 'ar' => 'كل القواعد', 'en' => 'All rules' ), 'rule' ),
					// The rule wizard now also hosts order triggers, custom events,
					// the message editor and the email builder (merged screens).
					array( 'nt.edit', array( 'ar' => 'قاعدة جديدة', 'en' => 'New rule' ), 'add_circle', array( 'dot' => true ) ),
				) ),
				array( array( 'ar' => 'أدوات النمو', 'en' => 'Growth tools' ), array(
					array( 'nt.cart', array( 'ar' => 'السلات المتروكة', 'en' => 'Abandoned carts' ), 'shopping_cart', array( 'dot' => true ) ),
					array( 'nt.widget', array( 'ar' => 'ودجت الواتساب', 'en' => 'Chat widget' ), 'chat' ),
				) ),
				array( array( 'ar' => 'القنوات والمحتوى', 'en' => 'Channels & Content' ), array(
					array( 'nt.sending', array( 'ar' => 'إعدادات الإرسال', 'en' => 'Sender settings' ), 'tune' ),
					array( 'nt.connect', array( 'ar' => 'ربط مرسال', 'en' => 'Mersal account' ), 'link' ),
				) ),
				array( array( 'ar' => 'الجمهور', 'en' => 'Audience' ), array(
					array( 'nt.segments', array( 'ar' => 'الشرائح', 'en' => 'Segments' ), 'groups' ),
				) ),
				array( array( 'ar' => 'النشاط والبيانات', 'en' => 'Activity & Data' ), array(
					array( 'nt.log', array( 'ar' => 'سجل التسليم', 'en' => 'Delivery Log' ), 'fact_check', array( 'badge' => 'Live' ) ),
					array( 'nt.logs', array( 'ar' => 'سجل النشاط', 'en' => 'Activity log' ), 'receipt_long' ),
					array( 'nt.updates', array( 'ar' => 'التحديثات', 'en' => 'Updates' ), 'system_update_alt' ),
				) ),
			),
		)
	);
}

/**
 * Boot the plugin once all plugins are loaded.
 */
function mnotif_boot() {
	load_plugin_textdomain( 'mersal-notifications', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );

	// Mersal account connection (SSO + WhatsApp/SMS/Email sending gateway).
	$connect = new Mersal_Notif_Connect();
	$connect->init();

	// Notification engine: trigger hooks, rule matching, sender, scheduled delays.
	$core = new Mersal_Notif_Core( $connect );
	$core->init();

	// Native self-hosted updates for Mersal plugins.
	Mersal_Notif_Updater::instance()->init();

	// Email templates builder.
	$email_templates = new Mersal_Notif_Email_Templates();
	$email_templates->init();

	// Order actions: manual resend from WooCommerce order screen.
	$order_actions = new Mersal_Notif_Order_Actions( $core );
	$order_actions->init();

	// WhatsApp Chat Widget (front-end floating button).
	$chat_widget = new Mersal_Notif_Chat_Widget();
	$chat_widget->init();

	// Abandoned Cart Recovery.
	$abandoned_cart = new Mersal_Notif_Abandoned_Cart( $core );
	$abandoned_cart->init();

	// Page Builder Integrations (Elementor, Bricks, Gutenberg).
	$integrations = new Mersal_Notif_Integrations();
	$integrations->init();

	// Email Open Tracking.
	$email_tracking = new Mersal_Notif_Email_Tracking();
	$email_tracking->init();

	// Cache Plugin Compatibility.
	$cache_compat = new Mersal_Notif_Cache_Compat();
	$cache_compat->init();

	// Custom WooCommerce Order Statuses.
	$order_statuses = new Mersal_Notif_Order_Statuses();
	$order_statuses->init();

	if ( is_admin() ) {
		$admin = new Mersal_Notif_Admin( $core, $connect );
		$admin->init();

		// Feed account notifications (managed at mersal.it/admndash/notifications/create)
		// into the shared Suite bell. The bell de-dupes by id, so several Mersal
		// plugins fetching the same broadcast list only show each item once.
		add_filter(
			'mersal_suite_notifications',
			static function ( $items ) use ( $connect ) {
				return array_merge( is_array( $items ) ? $items : array(), $connect->suite_bell_items() );
			}
		);
	}
}
add_action( 'plugins_loaded', 'mnotif_boot' );

/**
 * Apply the custom SMTP override to wp_mail when an SMTP host is configured.
 *
 * @param PHPMailer\PHPMailer\PHPMailer|object $phpmailer Mailer instance.
 */
add_action(
	'phpmailer_init',
	function ( $phpmailer ) {
		$host = Mersal_Notif_Settings::get( 'smtp_host' );
		if ( ! $host ) {
			return;
		}
		$phpmailer->isSMTP();
		$phpmailer->Host       = $host;
		$phpmailer->Port       = (int) Mersal_Notif_Settings::get( 'smtp_port', 587 );
		$enc                   = Mersal_Notif_Settings::get( 'smtp_enc', 'tls' );
		$phpmailer->SMTPSecure = ( 'none' === $enc ) ? '' : $enc;
		$user                  = Mersal_Notif_Settings::get( 'smtp_user' );
		$pass                  = Mersal_Notif_Settings::get( 'smtp_pass' );
		if ( $user ) {
			$phpmailer->SMTPAuth = true;
			$phpmailer->Username = $user;
			$phpmailer->Password = $pass;
		}
		$from = Mersal_Notif_Settings::get( 'email_from' );
		if ( $from && is_email( $from ) ) {
			$name = Mersal_Notif_Settings::get( 'email_from_name' );
			$phpmailer->setFrom( $from, $name ? $name : get_bloginfo( 'name' ), false );
		}
	}
);

/**
 * Activation: seed defaults.
 */
register_activation_hook(
	__FILE__,
	function () {
		Mersal_Notif_Settings::seed_defaults();
		add_option( 'mnotif_activated_at', time() );
		Mersal_Notif_Abandoned_Cart::install_tables();
		if ( class_exists( 'Mersal_Suite_Wizard' ) ) {
			Mersal_Suite_Wizard::arm_first_run( 'nt' );
		} else {
			// The SDK loads on plugins_loaded, which has already fired by the
			// time an activation hook runs on a fresh install — set the flag by
			// hand so the first admin page load still opens the wizard.
			update_option( 'mersal_suite_wizard_launch', 'nt', false );
		}
	}
);
