<?php

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

function aieo_checkout_timing_table() {
	global $wpdb;
	return $wpdb->prefix . 'aieo_checkout_timing';
}

function aieo_checkout_timing_create_table() {
	global $wpdb;

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

	$t = aieo_checkout_timing_table();

	$sql = "CREATE TABLE IF NOT EXISTS `{$t}` (
		`order_id` bigint unsigned NOT NULL,
		`session_id` varchar(64) DEFAULT NULL,
		`total_seconds` int unsigned NOT NULL DEFAULT 0,
		`active_seconds` int unsigned NOT NULL DEFAULT 0,
		`idle_seconds` int unsigned NOT NULL DEFAULT 0,
		`step_durations` text,
		`device_type` varchar(20) DEFAULT NULL,
		`has_coupon` tinyint(1) NOT NULL DEFAULT 0,
		`coupon_codes` varchar(255) DEFAULT NULL,
		`coupon_is_offer` tinyint(1) NOT NULL DEFAULT 0,
		`started_at` datetime DEFAULT NULL,
		`completed_at` datetime DEFAULT NULL,
		`created_at` datetime DEFAULT NULL,
		PRIMARY KEY (`order_id`),
		KEY `session_id` (`session_id`),
		KEY `has_coupon` (`has_coupon`),
		KEY `completed_at` (`completed_at`)
	) {$charset_collate};";

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