<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class WOSR_Activator {

    /**
     * Database version
     * Increment this number whenever schema changes are made.
     */
    private static $db_version = '1.3.0';

    /**
     * Runs on plugin activation.
     */
    public static function install() {
        global $wpdb;

        $installed_version = get_option('wosr_db_version');

        // Run DB update only if version is new
        if ($installed_version !== self::$db_version) {
            self::update_database();
            update_option('wosr_db_version', self::$db_version);
        }
    }

    /**
     * Handles creating or updating plugin database tables.
     */
    private static function update_database() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();

        // Define schema for each table
        $tables = [
            'order_status' => "(
                id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                payment_method VARCHAR(255) NOT NULL,
                user_role VARCHAR(255) NOT NULL,
                statuses TEXT NOT NULL,
                status VARCHAR(20) NOT NULL DEFAULT 'enabled',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )",
            'order_status_overview' => "(
                id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                user_role TEXT NOT NULL,
                statuses TEXT NOT NULL,
                status VARCHAR(20) NOT NULL DEFAULT 'enabled',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )"
        ];

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

        // Loop and create/update tables
        foreach ($tables as $table => $schema) {
            $table_name = $wpdb->prefix . "wosr_{$table}";
            $sql = "CREATE TABLE {$table_name} {$schema} {$charset_collate};";
            dbDelta($sql);
        }
    }
}