<?php
/**
 * Create Analytics Table Migration.
 *
 * Stores per-event view and click analytics for UGC widgets.
 * Each row represents a single view or click event recorded by a visitor.
 *
 * @package Ugcify
 */

namespace Ugcify\Database\Migrations;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * CreateAnalyticsTable migration class.
 */
class CreateAnalyticsTable {

	/**
	 * WordPress database instance.
	 *
	 * @var \wpdb
	 */
	private $wpdb;

	/**
	 * Constructor.
	 *
	 * @param \wpdb $wpdb WordPress database instance.
	 */
	public function __construct( $wpdb ) {
		$this->wpdb = $wpdb;
	}

	/**
	 * Run migration — returns the SQL for dbDelta.
	 *
	 * Columns:
	 *  event_type    VARCHAR(20)  — 'view' | 'click'
	 *  product_id    BIGINT       — WooCommerce product, 0 if unknown
	 *  session_hash  VARCHAR(64)  — SHA-256 of IP + UA + date, prevents repeated daily counts
	 *  event_date    DATE         — local date of the event (for daily aggregation)
	 *  created_at    DATETIME     — exact server time
	 *
	 * @return string SQL statement.
	 */
	public function run() {
		$table_name      = $this->wpdb->prefix . 'ugcify_analytics';
		$charset_collate = $this->wpdb->get_charset_collate();

		return "CREATE TABLE $table_name (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			event_type VARCHAR(20) NOT NULL,
			product_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			session_hash VARCHAR(64) NOT NULL DEFAULT '',
			event_date DATE NOT NULL,
			created_at DATETIME NOT NULL,
			PRIMARY KEY (id),
			KEY idx_event_date (event_date),
			KEY idx_type_date (event_type, event_date),
			KEY idx_product_date (product_id, event_date)
		) $charset_collate;";
	}
}
