<?php
/**
 * Installation: database schema, cron scheduling, defaults.
 *
 * @package Defog
 */

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

class Defog_Install {

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

		if ( false === get_option( 'defog_settings' ) ) {
			add_option( 'defog_settings', defog_default_settings() );
		}
		add_option( 'defog_db_version', DEFOG_VERSION );

		// Schedule the rollup worker (hourly: rolls up completed days, prunes raw).
		if ( ! wp_next_scheduled( 'defog_rollup_event' ) ) {
			wp_schedule_event( time() + 300, 'hourly', 'defog_rollup_event' );
		}
	}

	/**
	 * Run on deactivation. Data is preserved; only schedules are cleared.
	 */
	public static function deactivate() {
		$ts = wp_next_scheduled( 'defog_rollup_event' );
		if ( $ts ) {
			wp_unschedule_event( $ts, 'defog_rollup_event' );
		}
	}

	/**
	 * Create / upgrade tables via dbDelta.
	 */
	public static function create_tables() {
		global $wpdb;
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		$charset = $wpdb->get_charset_collate();

		// dbDelta() cannot take prepared statements, so table names are built
		// inline from the core-controlled prefix + fixed literals only.
		$events  = $wpdb->prefix . 'defog_events';
		$daily   = $wpdb->prefix . 'defog_stats_daily';
		$dim     = $wpdb->prefix . 'defog_dim_daily';
		$orders  = $wpdb->prefix . 'defog_orders';
		$items   = $wpdb->prefix . 'defog_order_items';
		$funnel  = $wpdb->prefix . 'defog_funnel';
		$actions = $wpdb->prefix . 'defog_actions';

		// Raw events. No IP is ever stored — only a daily-rotating salted hash.
		$sql_events = "CREATE TABLE {$events} (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			occurred_at DATETIME NOT NULL,
			visitor_hash CHAR(64) NOT NULL,
			is_new_visitor TINYINT(1) NOT NULL DEFAULT 0,
			is_new_session TINYINT(1) NOT NULL DEFAULT 0,
			path VARCHAR(190) NOT NULL DEFAULT '/',
			source VARCHAR(20) NOT NULL DEFAULT 'direct',
			referrer_host VARCHAR(190) NULL,
			country CHAR(2) NOT NULL DEFAULT 'XX',
			device VARCHAR(10) NOT NULL DEFAULT 'desktop',
			browser VARCHAR(30) NULL,
			os VARCHAR(30) NULL,
			engaged INT(10) UNSIGNED NOT NULL DEFAULT 0,
			is_exit TINYINT(1) NOT NULL DEFAULT 1,
			PRIMARY KEY  (id),
			KEY occurred_at (occurred_at),
			KEY visitor_hash (visitor_hash),
			KEY path (path)
		) {$charset};";

		// Daily KPI rollup.
		$sql_daily = "CREATE TABLE {$daily} (
			stat_date DATE NOT NULL,
			visitors INT(10) UNSIGNED NOT NULL DEFAULT 0,
			pageviews INT(10) UNSIGNED NOT NULL DEFAULT 0,
			sessions INT(10) UNSIGNED NOT NULL DEFAULT 0,
			bounces INT(10) UNSIGNED NOT NULL DEFAULT 0,
			PRIMARY KEY  (stat_date)
		) {$charset};";

		// Daily dimension rollup (source|country|device|page).
		$sql_dim = "CREATE TABLE {$dim} (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			stat_date DATE NOT NULL,
			dimension VARCHAR(10) NOT NULL,
			label VARCHAR(190) NOT NULL,
			label_hash CHAR(40) NOT NULL,
			visitors INT(10) UNSIGNED NOT NULL DEFAULT 0,
			pageviews INT(10) UNSIGNED NOT NULL DEFAULT 0,
			PRIMARY KEY  (id),
			UNIQUE KEY uniq (stat_date,dimension,label_hash),
			KEY dim_date (stat_date,dimension)
		) {$charset};";

		// WooCommerce orders (raw; queried directly — order volume is low).
		$sql_orders = "CREATE TABLE {$orders} (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			order_id BIGINT(20) UNSIGNED NOT NULL,
			occurred_at DATETIME NOT NULL,
			total DECIMAL(12,2) NOT NULL DEFAULT 0,
			currency CHAR(3) NOT NULL DEFAULT '',
			items INT(10) UNSIGNED NOT NULL DEFAULT 0,
			source VARCHAR(20) NOT NULL DEFAULT 'direct',
			country CHAR(2) NOT NULL DEFAULT 'XX',
			device VARCHAR(10) NOT NULL DEFAULT 'desktop',
			status VARCHAR(20) NOT NULL DEFAULT '',
			PRIMARY KEY  (id),
			UNIQUE KEY order_id (order_id),
			KEY occurred_at (occurred_at),
			KEY source (source)
		) {$charset};";

		// WooCommerce order line items (for top-products).
		$sql_items = "CREATE TABLE {$items} (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			order_id BIGINT(20) UNSIGNED NOT NULL,
			product_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			name VARCHAR(190) NOT NULL DEFAULT '',
			qty INT(10) UNSIGNED NOT NULL DEFAULT 0,
			total DECIMAL(12,2) NOT NULL DEFAULT 0,
			occurred_at DATETIME NOT NULL,
			PRIMARY KEY  (id),
			KEY occurred_at (occurred_at),
			KEY product_id (product_id)
		) {$charset};";

		// User actions / events (outbound clicks; downloads & forms are future-ready
		// via the `category` column). Queried directly; pruned by retention.
		$sql_actions = "CREATE TABLE {$actions} (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			occurred_at DATETIME NOT NULL,
			day DATE NOT NULL,
			visitor_hash CHAR(64) NOT NULL,
			category VARCHAR(12) NOT NULL DEFAULT 'outbound',
			label VARCHAR(190) NOT NULL DEFAULT '',
			path VARCHAR(190) NOT NULL DEFAULT '/',
			PRIMARY KEY  (id),
			KEY day_cat (day,category),
			KEY occurred_at (occurred_at)
		) {$charset};";

		// Conversion-funnel signals (one row per visitor / stage / day).
		$sql_funnel = "CREATE TABLE {$funnel} (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			day DATE NOT NULL,
			occurred_at DATETIME NOT NULL,
			visitor_hash CHAR(64) NOT NULL,
			stage VARCHAR(12) NOT NULL,
			PRIMARY KEY  (id),
			UNIQUE KEY vsd (visitor_hash,stage,day),
			KEY day_stage (day,stage)
		) {$charset};";

		dbDelta( $sql_events );
		dbDelta( $sql_daily );
		dbDelta( $sql_dim );
		dbDelta( $sql_orders );
		dbDelta( $sql_items );
		dbDelta( $sql_actions );
		dbDelta( $sql_funnel );
	}
}
