<?php

namespace Dobare\Abandoned_Cart;

class Dobare_Abandoned_Cart_Migrator
{
	private const OPTION_KEY = 'dobare_abandoned_cart_schema_version';
	private const SCHEMA_VERSION = '1.0.0';

	public static function maybe_migrate(): void
	{
		$current_version = get_option(self::OPTION_KEY);

		if ($current_version === self::SCHEMA_VERSION && self::table_exists()) {
			return;
		}

		self::run_migration();
		update_option(self::OPTION_KEY, self::SCHEMA_VERSION);
	}

	private static function run_migration(): void
	{
		global $wpdb;

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		$table_name = $wpdb->prefix . 'dobare_abandoned_carts';
		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE {$table_name} (
			cart_hash CHAR(40) NOT NULL,
			user_phone TEXT NOT NULL,
			extra_details LONGTEXT NOT NULL,
			status ENUM('active','abandoned') NOT NULL DEFAULT 'active',
			last_active_at DATETIME NOT NULL,
			abandoned_at DATETIME NULL,
			last_error TEXT NULL,
			PRIMARY KEY  (cart_hash),
			KEY user_phone_idx (user_phone(20)),
			KEY status_idx (status)
		) {$charset_collate};";

		dbDelta($sql);
	}

	private static function table_exists(): bool
	{
		global $wpdb;

		$table_name = $wpdb->prefix . 'dobare_abandoned_carts';
		$table = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name));

		return $table === $table_name;
	}

	public static function drop_table(): void
	{
		global $wpdb;

		$table_name = $wpdb->prefix . 'dobare_abandoned_carts';
		$wpdb->query("DROP TABLE IF EXISTS {$table_name}");
		delete_option(self::OPTION_KEY);
	}
}


