<?php

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

if ( ! defined( 'AIEO_REMOTE_EXPORT_SCHEMA_VERSION' ) ) {
	define( 'AIEO_REMOTE_EXPORT_SCHEMA_VERSION', 1 );
}

if ( ! function_exists( 'aieo_remote_export_state_table' ) ) {
	function aieo_remote_export_state_table() {
		global $wpdb;
		return $wpdb->prefix . 'aieo_remote_export_state';
	}
}

if ( ! function_exists( 'maybe_install_remote_export_schema' ) ) {
	function maybe_install_remote_export_schema() {
		$installed = (int) get_option( 'aieo_remote_export_schema_version', 0 );
		if ( $installed >= AIEO_REMOTE_EXPORT_SCHEMA_VERSION ) {
			return;
		}

		global $wpdb;
		$charset = $wpdb->get_charset_collate();
		$table   = aieo_remote_export_state_table();

		if ( ! function_exists( 'dbDelta' ) ) {
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		}

		$sql = "CREATE TABLE {$table} (
			connection_id BIGINT UNSIGNED NOT NULL,
			table_name VARCHAR(64) NOT NULL,
			last_exported_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
			last_exported_ts DATETIME NULL DEFAULT NULL,
			last_run_ts DATETIME NULL DEFAULT NULL,
			last_status VARCHAR(32) NOT NULL DEFAULT '',
			last_error TEXT NULL,
			PRIMARY KEY  (connection_id, table_name),
			KEY table_name (table_name)
		) {$charset};";

		dbDelta( $sql );

		update_option( 'aieo_remote_export_schema_version', AIEO_REMOTE_EXPORT_SCHEMA_VERSION, false );
	}
}
