<?php
/**
 * Fired during plugin activation.
 *
 * @package Lucrativeit_Subscription_Recurring_Billing
 */

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

/**
 * Creates database tables and seeds default data.
 */
class LUCRSURE_Activator {

	/**
	 * Run activation routines.
	 */
	public static function activate() {
		require_once LUCRSURE_PLUGIN_DIR . 'includes/helpers.php';
		self::maybe_migrate_legacy_prefix();
		self::create_tables();
		self::seed_roles();
		self::seed_settings();

		require_once LUCRSURE_PLUGIN_DIR . 'includes/class-lucrsure-dependencies.php';
		LUCRSURE_Dependencies::verify();

		update_option( 'lucrsure_db_version', LUCRSURE_VERSION );
		update_option( 'lucrsure_activated_at', current_time( 'mysql' ) );

		global $wpdb;
		$plan_count = (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter
			$wpdb->prepare( 'SELECT COUNT(*) FROM %i', lucrsure_table( 'plans' ) )
		);
		$cust_count = (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter
			$wpdb->prepare( 'SELECT COUNT(*) FROM %i', lucrsure_table( 'customers' ) )
		);
		if ( 0 === $plan_count && 0 === $cust_count ) {
			delete_option( 'lucrsure_onboarding_dismissed' );
			delete_option( 'lucrsure_demo_data_imported' );
			delete_option( 'lucrsure_demo_import_state' );
			update_option( 'lucrsure_activation_redirect', true );
		}

		flush_rewrite_rules();
	}

	/**
	 * Migrate options, cron, and DB tables from legacy prefixes (lsr_, lsp_).
	 *
	 * Canonical prefix is lucrsure_ (4+ chars for WordPress.org Plugin Check).
	 * Safe to call repeatedly; no-ops when migration is already complete.
	 */
	public static function maybe_migrate_legacy_prefix() {
		if ( get_option( 'lucrsure_prefix_migrated' ) ) {
			return;
		}

		global $wpdb;

		$option_suffixes = array(
			'settings',
			'email_templates',
			'email_layout',
			'db_version',
			'activated_at',
			'onboarding_dismissed',
			'demo_data_imported',
			'demo_import_state',
			'activation_redirect',
			'dependency_status',
			'plan_schema_version',
			'branch_schema_version',
			'category_repair_version',
			'category_plan_pages',
			'prefix_migrated',
		);

		// Older prefixes — lucrsure_ is the canonical/modern prefix.
		$legacy_option_prefixes = array( 'lsp_', 'lsr_' );

		foreach ( $option_suffixes as $suffix ) {
			$modern = 'lucrsure_' . $suffix;
			if ( false !== get_option( $modern, false ) ) {
				continue;
			}
			foreach ( $legacy_option_prefixes as $legacy_prefix ) {
				$legacy       = $legacy_prefix . $suffix;
				$legacy_value = get_option( $legacy, null );
				if ( null === $legacy_value ) {
					continue;
				}
				update_option( $modern, $legacy_value );
				delete_option( $legacy );
				break;
			}
		}

		foreach ( $option_suffixes as $suffix ) {
			foreach ( $legacy_option_prefixes as $legacy_prefix ) {
				delete_option( $legacy_prefix . $suffix );
			}
		}
		delete_option( 'lsr_prefix_migrated' );
		delete_option( 'lsp_prefix_migrated' );

		$legacy_crons = array( 'lsp_daily_billing_cron', 'lsr_daily_billing_cron' );
		foreach ( $legacy_crons as $legacy_cron ) {
			if ( wp_next_scheduled( $legacy_cron ) && ! wp_next_scheduled( 'lucrsure_daily_billing_cron' ) ) {
				$timestamp = wp_next_scheduled( $legacy_cron );
				wp_schedule_event( $timestamp ? $timestamp : time(), 'daily', 'lucrsure_daily_billing_cron' );
			}
			wp_clear_scheduled_hook( $legacy_cron );
		}

		$tables          = array( 'branches', 'customers', 'plan_categories', 'plans', 'subscriptions', 'invoices', 'roles', 'staff' );
		$modern_prefix   = $wpdb->prefix . 'lucrsure_';
		$legacy_prefixes = array( $wpdb->prefix . 'lsp_', $wpdb->prefix . 'lsr_' );

		foreach ( $tables as $table ) {
			$modern_table = $modern_prefix . $table;
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter
			$modern_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $modern_table ) );

			foreach ( $legacy_prefixes as $legacy_prefix ) {
				$legacy_table = $legacy_prefix . $table;
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter
				$legacy_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $legacy_table ) );

				if ( $legacy_exists && ! $modern_exists ) {
					// phpcs:ignore WordPress.DB.DirectDatabaseQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table names come from a fixed allowlist + $wpdb->prefix only.
					$wpdb->query( $wpdb->prepare( 'RENAME TABLE %i TO %i', $legacy_table, $modern_table ) );
					$modern_exists = true;
				}
			}
		}

		update_option( 'lucrsure_prefix_migrated', LUCRSURE_VERSION );
	}

	/**
	 * Create the plugin database tables using dbDelta.
	 */
	public static function create_tables() {
		global $wpdb;

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		$prefix          = lucrsure_table_prefix();
		$charset_collate = $wpdb->get_charset_collate();

		$tables = array();

		$tables[] = "CREATE TABLE {$prefix}branches (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			name VARCHAR(191) NOT NULL DEFAULT '',
			code VARCHAR(100) NOT NULL DEFAULT '',
			region VARCHAR(191) NOT NULL DEFAULT '',
			address TEXT NULL,
			phone VARCHAR(60) NOT NULL DEFAULT '',
			opening_time VARCHAR(10) NOT NULL DEFAULT '',
			closing_time VARCHAR(10) NOT NULL DEFAULT '',
			image_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			amenities TEXT NULL,
			description TEXT NULL,
			is_main TINYINT(1) NOT NULL DEFAULT 0,
			is_active TINYINT(1) NOT NULL DEFAULT 1,
			created_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			updated_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			PRIMARY KEY  (id),
			KEY code (code),
			KEY is_active (is_active)
		) {$charset_collate};";

		$tables[] = "CREATE TABLE {$prefix}customers (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			user_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			name VARCHAR(191) NOT NULL DEFAULT '',
			email VARCHAR(191) NOT NULL DEFAULT '',
			phone VARCHAR(60) NOT NULL DEFAULT '',
			company VARCHAR(191) NOT NULL DEFAULT '',
			billing_address_1 VARCHAR(191) NOT NULL DEFAULT '',
			billing_address_2 VARCHAR(191) NOT NULL DEFAULT '',
			billing_city VARCHAR(100) NOT NULL DEFAULT '',
			billing_state VARCHAR(100) NOT NULL DEFAULT '',
			billing_postcode VARCHAR(30) NOT NULL DEFAULT '',
			billing_country VARCHAR(100) NOT NULL DEFAULT '',
			branch_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			status VARCHAR(40) NOT NULL DEFAULT 'active',
			notes TEXT NULL,
			created_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			updated_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			PRIMARY KEY  (id),
			KEY email (email),
			KEY branch_id (branch_id),
			KEY status (status)
		) {$charset_collate};";

		$tables[] = "CREATE TABLE {$prefix}plan_categories (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			name VARCHAR(191) NOT NULL DEFAULT '',
			slug VARCHAR(191) NOT NULL DEFAULT '',
			description TEXT NULL,
			is_active TINYINT(1) NOT NULL DEFAULT 1,
			created_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			updated_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			PRIMARY KEY  (id),
			KEY slug (slug),
			KEY is_active (is_active)
		) {$charset_collate};";

		$tables[] = "CREATE TABLE {$prefix}plans (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			name VARCHAR(191) NOT NULL DEFAULT '',
			slug VARCHAR(191) NOT NULL DEFAULT '',
			description TEXT NULL,
			price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
			special_price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
			special_price_enabled TINYINT(1) NOT NULL DEFAULT 0,
			currency VARCHAR(10) NOT NULL DEFAULT 'USD',
			billing_interval VARCHAR(20) NOT NULL DEFAULT 'month',
			interval_count INT(11) NOT NULL DEFAULT 1,
			trial_days INT(11) NOT NULL DEFAULT 0,
			features LONGTEXT NULL,
			wc_product_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			category_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			branch_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			thumbnail_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			is_active TINYINT(1) NOT NULL DEFAULT 1,
			is_popular TINYINT(1) NOT NULL DEFAULT 0,
			created_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			updated_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			PRIMARY KEY  (id),
			KEY slug (slug),
			KEY category_id (category_id),
			KEY branch_id (branch_id),
			KEY is_active (is_active)
		) {$charset_collate};";

		$tables[] = "CREATE TABLE {$prefix}subscriptions (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			customer_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			plan_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			status VARCHAR(40) NOT NULL DEFAULT 'active',
			quantity INT(11) NOT NULL DEFAULT 1,
			mrr DECIMAL(12,2) NOT NULL DEFAULT 0.00,
			start_date DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			trial_ends DATETIME NULL,
			current_period_start DATETIME NULL,
			current_period_end DATETIME NULL,
			canceled_at DATETIME NULL,
			gateway VARCHAR(60) NOT NULL DEFAULT 'manual',
			gateway_subscription_id VARCHAR(191) NOT NULL DEFAULT '',
			auto_renew TINYINT(1) NOT NULL DEFAULT 1,
			wc_subscription_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			created_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			updated_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			PRIMARY KEY  (id),
			KEY customer_id (customer_id),
			KEY plan_id (plan_id),
			KEY status (status)
		) {$charset_collate};";

		$tables[] = "CREATE TABLE {$prefix}invoices (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			invoice_number VARCHAR(60) NOT NULL DEFAULT '',
			customer_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			subscription_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
			currency VARCHAR(10) NOT NULL DEFAULT 'USD',
			status VARCHAR(40) NOT NULL DEFAULT 'unpaid',
			due_date DATETIME NULL,
			paid_at DATETIME NULL,
			gateway VARCHAR(60) NOT NULL DEFAULT 'manual',
			gateway_payment_id VARCHAR(191) NOT NULL DEFAULT '',
			payment_url TEXT NULL,
			billing_address_1 VARCHAR(191) NOT NULL DEFAULT '',
			billing_address_2 VARCHAR(191) NOT NULL DEFAULT '',
			billing_city VARCHAR(100) NOT NULL DEFAULT '',
			billing_state VARCHAR(100) NOT NULL DEFAULT '',
			billing_postcode VARCHAR(30) NOT NULL DEFAULT '',
			billing_country VARCHAR(100) NOT NULL DEFAULT '',
			line_items LONGTEXT NULL,
			created_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			updated_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			PRIMARY KEY  (id),
			KEY invoice_number (invoice_number),
			KEY customer_id (customer_id),
			KEY subscription_id (subscription_id),
			KEY status (status)
		) {$charset_collate};";

		$tables[] = "CREATE TABLE {$prefix}roles (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			name VARCHAR(191) NOT NULL DEFAULT '',
			slug VARCHAR(191) NOT NULL DEFAULT '',
			description TEXT NULL,
			modules LONGTEXT NULL,
			is_active TINYINT(1) NOT NULL DEFAULT 1,
			is_system TINYINT(1) NOT NULL DEFAULT 0,
			created_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			updated_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			PRIMARY KEY  (id),
			KEY slug (slug)
		) {$charset_collate};";

		$tables[] = "CREATE TABLE {$prefix}staff (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			user_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			name VARCHAR(191) NOT NULL DEFAULT '',
			email VARCHAR(191) NOT NULL DEFAULT '',
			role_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			position VARCHAR(191) NOT NULL DEFAULT '',
			branch_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			status VARCHAR(40) NOT NULL DEFAULT 'active',
			created_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			updated_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
			PRIMARY KEY  (id),
			KEY email (email),
			KEY role_id (role_id),
			KEY status (status)
		) {$charset_collate};";

		foreach ( $tables as $sql ) {
			dbDelta( $sql );
		}
	}

	/**
	 * Seed the default roles (matching the design: Super Admin, Manager, Support Agent).
	 */
	public static function seed_roles() {
		global $wpdb;

		$table = lucrsure_table( 'roles' );

		$existing = (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter
			$wpdb->prepare( 'SELECT COUNT(*) FROM %i', $table )
		);
		if ( $existing > 0 ) {
			return;
		}

		$all_modules = array_keys( lucrsure_get_modules() );

		$defaults = array(
			array(
				'name'        => 'Super Admin',
				'slug'        => 'super-admin',
				'description' => 'Full, unrestricted access to every module.',
				'modules'     => $all_modules,
				'is_system'   => 1,
			),
			array(
				'name'        => 'Manager',
				'slug'        => 'manager',
				'description' => 'Manages customers, subscriptions, plans and billing.',
				'modules'     => array( 'dashboard', 'customers', 'branches', 'plan-categories', 'plans', 'subscriptions', 'billing' ),
				'is_system'   => 0,
			),
			array(
				'name'        => 'Support Agent',
				'slug'        => 'support-agent',
				'description' => 'Read-only access to customers, subscriptions and billing.',
				'modules'     => array( 'dashboard', 'customers', 'subscriptions', 'billing' ),
				'is_system'   => 0,
			),
		);

		$now = current_time( 'mysql' );

		foreach ( $defaults as $role ) {
			$wpdb->insert( // phpcs:ignore WordPress.DB
				$table,
				array(
					'name'        => $role['name'],
					'slug'        => $role['slug'],
					'description' => $role['description'],
					'modules'     => wp_json_encode( $role['modules'] ),
					'is_active'   => 1,
					'is_system'   => $role['is_system'],
					'created_at'  => $now,
					'updated_at'  => $now,
				),
				array( '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s' )
			);
		}
	}

	/**
	 * Seed default plugin settings.
	 */
	public static function seed_settings() {
		if ( get_option( 'lucrsure_settings' ) ) {
			return;
		}

		$frontend = lucrsure_default_frontend_settings();
		$frontend['plans_template'] = 'cards';
		$hero_image_id = lucrsure_import_plugin_attachment(
			'assets/images/banner.png',
			__( 'Hero Banner', 'lucrativeit-subscription-recurring-billing' )
		);
		if ( $hero_image_id > 0 ) {
			$frontend['hero_image_id'] = $hero_image_id;
		}

		$defaults = array(
			'subscription_engine' => 'custom',
			'company_name'        => get_bloginfo( 'name' ),
			'support_email'       => get_option( 'admin_email' ),
			'default_currency'    => 'USD',
			'timezone'            => 'UTC',
			'footer_text'         => lucrsure_default_footer_text(),
			'default_gateway'     => 'manual',
			'invoice_due_days'    => 7,
			'gateways'            => array(
				'stripe'     => array( 'enabled' => 0 ),
				'sslcommerz' => array(
					'enabled'        => 0,
					'store_id'       => '',
					'store_password' => '',
					'sandbox'        => 1,
				),
				'razorpay'   => array(
					'enabled'        => 0,
					'key_id'         => '',
					'key_secret'     => '',
					'webhook_secret' => '',
				),
				'paypal'     => array(
					'enabled'       => 0,
					'client_id'     => '',
					'client_secret' => '',
					'webhook_id'    => '',
					'sandbox'       => 1,
				),
				'manual'     => array( 'enabled' => 1 ),
			),
			'email'               => array(
				'mail_driver'  => 'wp_mail',
				'from_address' => get_option( 'admin_email' ),
				'from_name'    => get_bloginfo( 'name' ),
			),
			'notifications'       => array(
				'invoice_sent'        => 1,
				'payment_received'    => 1,
				'subscription_active' => 1,
			),
			'frontend'            => $frontend,
		);

		add_option( 'lucrsure_settings', $defaults );
		add_option( 'lucrsure_email_templates', lucrsure_default_email_templates() );
		update_option( 'lucrsure_plans_template_cards_split', 1 );
	}
}
