<?php

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

function aieo_server_events_log_table() {
	global $wpdb;
	return $wpdb->prefix . 'aieo_server_events_log';
}

function aieo_server_events_log_create_table() {
	global $wpdb;

	$charset_collate = function_exists( 'aieo_get_charset_collate' )
		? aieo_get_charset_collate()
		: $wpdb->get_charset_collate();

	$t = aieo_server_events_log_table();

	$sql = "CREATE TABLE IF NOT EXISTS `{$t}` (
		`id` bigint unsigned NOT NULL AUTO_INCREMENT,
		`event_id` varchar(36) NOT NULL DEFAULT '',
		`platform` varchar(16) NOT NULL DEFAULT 'fb',
		`event_name` varchar(40) NOT NULL DEFAULT 'Purchase',
		`order_id` bigint unsigned NOT NULL DEFAULT 0,
		`session_id` varchar(64) DEFAULT NULL,
		`user_id` bigint unsigned NOT NULL DEFAULT 0,
		`status` varchar(16) NOT NULL DEFAULT 'pending',
		`http_code` smallint DEFAULT NULL,
		`fbtrace_id` varchar(64) DEFAULT NULL,
		`attempts` smallint unsigned NOT NULL DEFAULT 0,
		`request_payload` longtext,
		`response_body` text,
		`error_message` varchar(255) DEFAULT NULL,
		`value` decimal(16,4) DEFAULT NULL,
		`currency` varchar(8) DEFAULT NULL,
		`test_mode` tinyint(1) NOT NULL DEFAULT 0,
		`created_at` datetime DEFAULT NULL,
		`sent_at` datetime DEFAULT NULL,
		PRIMARY KEY (`id`),
		UNIQUE KEY `event_id_platform` (`event_id`,`platform`),
		KEY `order_id` (`order_id`),
		KEY `status` (`status`),
		KEY `session_id` (`session_id`)
	) {$charset_collate};";

	if ( function_exists( 'aieo_dbdelta' ) ) {
		aieo_dbdelta( $sql );
	} else {
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sql );
	}
}
