<?php
/**
 * Plugin activation handler.
 *
 * Creates database tables, sets default options, and schedules cron events.
 *
 * @package Waitlytics
 */

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

/**
 * Class WTLY_Activator
 *
 * Handles all activation tasks for Waitlytics.
 */
class WTLY_Activator {

	/**
	 * Run activation tasks.
	 */
	public static function activate() {
		self::create_tables();
		self::set_defaults();
		self::schedule_events();

		update_option( 'wtly_db_version', '1.0.0' );
		update_option( 'wtly_version', WTLY_VERSION );

		if ( false === get_option( 'wtly_activation_time' ) ) {
			update_option( 'wtly_activation_time', time() );
		}

		flush_rewrite_rules();
	}

	/**
	 * Create custom database tables using dbDelta.
	 */
	private static function create_tables() {
		global $wpdb;

		$charset_collate = $wpdb->get_charset_collate();

		// Table: wtly_subscribers.
		$table_subscribers = $wpdb->prefix . 'wtly_subscribers';
		$sql_subscribers   = "CREATE TABLE $table_subscribers (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			product_id bigint(20) unsigned NOT NULL,
			variation_id bigint(20) unsigned NOT NULL DEFAULT 0,
			email varchar(255) NOT NULL,
			user_id bigint(20) unsigned NOT NULL DEFAULT 0,
			status varchar(20) NOT NULL DEFAULT 'active',
			double_optin_confirmed tinyint(1) NOT NULL DEFAULT 0,
			double_optin_token varchar(64) DEFAULT NULL,
			source varchar(20) NOT NULL DEFAULT 'inline',
			ip_address varchar(45) DEFAULT NULL,
			subscribed_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			notified_at datetime DEFAULT NULL,
			unsubscribed_at datetime DEFAULT NULL,
			PRIMARY KEY  (id),
			KEY product_id (product_id),
			KEY variation_id (variation_id),
			KEY email (email),
			KEY status (status),
			KEY user_id (user_id),
			UNIQUE KEY unique_sub (product_id, variation_id, email, status)
		) $charset_collate;";

		// Table: wtly_notifications_log.
		$table_notifications = $wpdb->prefix . 'wtly_notifications_log';
		$sql_notifications   = "CREATE TABLE $table_notifications (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			subscriber_id bigint(20) unsigned NOT NULL,
			product_id bigint(20) unsigned NOT NULL,
			variation_id bigint(20) unsigned NOT NULL DEFAULT 0,
			email varchar(255) NOT NULL,
			sent_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			email_opened tinyint(1) NOT NULL DEFAULT 0,
			link_clicked tinyint(1) NOT NULL DEFAULT 0,
			purchased tinyint(1) NOT NULL DEFAULT 0,
			PRIMARY KEY  (id),
			KEY subscriber_id (subscriber_id),
			KEY product_id (product_id),
			KEY sent_at (sent_at)
		) $charset_collate;";

		// Table: wtly_forecasts (PRO only, but create table for schema consistency).
		$table_forecasts = $wpdb->prefix . 'wtly_forecasts';
		$sql_forecasts   = "CREATE TABLE $table_forecasts (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			product_id bigint(20) unsigned NOT NULL,
			forecast_date date NOT NULL,
			days_until_stockout int(11) DEFAULT NULL,
			recommended_reorder_qty int(11) DEFAULT NULL,
			sales_velocity_daily decimal(10,2) DEFAULT NULL,
			sales_velocity_weekly decimal(10,2) DEFAULT NULL,
			estimated_lost_revenue decimal(10,2) DEFAULT NULL,
			ai_provider varchar(20) DEFAULT NULL,
			ai_summary text DEFAULT NULL,
			raw_response longtext DEFAULT NULL,
			created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY  (id),
			KEY product_id (product_id),
			KEY forecast_date (forecast_date),
			UNIQUE KEY unique_forecast (product_id, forecast_date)
		) $charset_collate;";

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

		dbDelta( $sql_subscribers );
		dbDelta( $sql_notifications );
		dbDelta( $sql_forecasts );
	}

	/**
	 * Set default plugin options.
	 */
	private static function set_defaults() {
		if ( false === get_option( 'wtly_settings' ) ) {
			$defaults = array(
				'enable_notifications'        => true,
				'notification_position'       => 'after_add_to_cart',
				'show_subscriber_count'       => false,
				'guest_subscriptions'         => true,
				'email_from_name'             => '',
				'email_from_address'          => '',
				'email_subject'               => '',
				'email_heading'               => '',
				'email_body'                  => '',
				'email_include_product_image' => true,
				'email_include_price'         => true,
				'email_include_cta_button'    => true,
				'admin_notify_new_subscriber' => true,
				'admin_notify_email'          => '',
				'low_stock_threshold'         => 5,
				'admin_low_stock_email'       => true,
				'form_button_text'            => '',
				'form_success_message'        => '',
				'form_placeholder_text'       => '',
				'ai_provider'                 => 'openai',
				'ai_api_key'                  => '',
				'ai_model'                    => 'gpt-4o-mini',
				'ai_forecast_frequency'       => 'weekly',
				'ai_auto_forecast'            => false,
				'mailchimp_api_key'           => '',
				'mailchimp_list_id'           => '',
				'klaviyo_api_key'             => '',
				'klaviyo_list_id'             => '',
				'twilio_sid'                  => '',
				'twilio_token'                => '',
				'twilio_from_number'          => '',
				'whatsapp_enabled'            => false,
				'popup_enabled'               => false,
				'popup_delay_seconds'         => 3,
				'popup_show_on'               => 'out_of_stock',
				'custom_form_css'             => '',
				'recaptcha_enabled'           => false,
				'recaptcha_site_key'          => '',
				'recaptcha_secret_key'        => '',
				'double_optin_enabled'        => false,
				'banned_emails'               => '',
				'banned_domains'              => '',
			);

			update_option( 'wtly_settings', $defaults );
		}
	}

	/**
	 * Schedule cron events.
	 */
	private static function schedule_events() {
		if ( ! wp_next_scheduled( 'wtly_check_stock_changes' ) ) {
			wp_schedule_event( time(), 'wtly_six_hours', 'wtly_check_stock_changes' );
		}
		if ( ! wp_next_scheduled( 'wtly_cleanup_expired_subscriptions' ) ) {
			wp_schedule_event( time(), 'daily', 'wtly_cleanup_expired_subscriptions' );
		}
	}
}
