<?php

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

function aieo_carts_table() {
	global $wpdb;
	return $wpdb->prefix . 'aieo_carts';
}

function aieo_cart_items_table() {
	global $wpdb;
	return $wpdb->prefix . 'aieo_cart_items';
}

function aieo_carts_create_tables() {
	global $wpdb;

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

	$carts = aieo_carts_table();
	$items = aieo_cart_items_table();

	$sql_carts = "CREATE TABLE IF NOT EXISTS `{$carts}` (
		`id` bigint unsigned NOT NULL AUTO_INCREMENT,
		`token` varchar(20) DEFAULT NULL,
		`kind` varchar(12) NOT NULL DEFAULT 'saved',
		`source` varchar(24) NOT NULL DEFAULT '',
		`wc_order_id` bigint unsigned DEFAULT NULL,
		`user_id` bigint unsigned NOT NULL DEFAULT 0,
		`customer_email` varchar(190) DEFAULT NULL,
		`session_id` varchar(64) DEFAULT NULL,
		`name` varchar(190) DEFAULT NULL,
		`items` longtext,
		`coupons` text,
		`currency` varchar(8) DEFAULT NULL,
		`item_count` int unsigned NOT NULL DEFAULT 0,
		`subtotal` decimal(16,2) NOT NULL DEFAULT 0,
		`total` decimal(16,2) NOT NULL DEFAULT 0,
		`status` varchar(16) NOT NULL DEFAULT 'active',
		`outcome` varchar(16) DEFAULT NULL,
		`converted_order_id` bigint unsigned DEFAULT NULL,
		`contains_restocked` tinyint(1) NOT NULL DEFAULT 0,
		`view_count` int unsigned NOT NULL DEFAULT 0,
		`resume_count` int unsigned NOT NULL DEFAULT 0,
		`created_at` datetime DEFAULT NULL,
		`updated_at` datetime DEFAULT NULL,
		`last_seen_at` datetime DEFAULT NULL,
		`converted_at` datetime DEFAULT NULL,
		`expires_at` datetime DEFAULT NULL,
		PRIMARY KEY (`id`),
		UNIQUE KEY `token` (`token`),
		UNIQUE KEY `wc_order_id` (`wc_order_id`),
		KEY `kind_status` (`kind`,`status`),
		KEY `user_id` (`user_id`),
		KEY `created_at` (`created_at`),
		KEY `contains_restocked` (`contains_restocked`)
	) {$charset_collate};";

	$sql_items = "CREATE TABLE IF NOT EXISTS `{$items}` (
		`id` bigint unsigned NOT NULL AUTO_INCREMENT,
		`cart_id` bigint unsigned NOT NULL,
		`product_id` bigint unsigned NOT NULL DEFAULT 0,
		`variation_id` bigint unsigned NOT NULL DEFAULT 0,
		`sku` varchar(100) DEFAULT NULL,
		`name` varchar(255) DEFAULT NULL,
		`quantity` int unsigned NOT NULL DEFAULT 0,
		`line_total` decimal(16,2) NOT NULL DEFAULT 0,
		`is_restocked` tinyint(1) NOT NULL DEFAULT 0,
		PRIMARY KEY (`id`),
		KEY `cart_id` (`cart_id`),
		KEY `product_id` (`product_id`)
	) {$charset_collate};";

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