<?php
namespace OxygenApp\Models;

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

use OxygenApp\Models\User;

class SchemaManager {
    const SCHEMA_VERSION = '1.0';
    const SCHEMA_VERSION_OPTION = 'oxygen_app_schema_version';

    public static function createUsersTable() {
        global $wpdb;

        $table_name = $wpdb->prefix . User::TABLE_NAME;
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            creation_date DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
            name VARCHAR(100) DEFAULT '' NOT NULL,
            email VARCHAR(100) NOT NULL,
            password VARCHAR(255) NOT NULL,
            activation_code VARCHAR(255) NOT NULL,
            reset_token VARCHAR(255) DEFAULT NULL,
            is_active TINYINT(1) DEFAULT 0 NOT NULL,
            current_language VARCHAR(8) DEFAULT 'en' NOT NULL,
            block_user TINYINT(1) DEFAULT 0,
            last_login_time DATETIME DEFAULT NULL,
            terms VARCHAR(4) NOT NULL,
            meta TEXT,
            PRIMARY KEY  (id),
            UNIQUE KEY email (email),
            KEY name (name)
        ) $charset_collate;";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );

        // Update schema version
        $current_version = get_option( self::SCHEMA_VERSION_OPTION );
        if ( $current_version !== self::SCHEMA_VERSION ) {
            update_option( self::SCHEMA_VERSION_OPTION, self::SCHEMA_VERSION );
        }
    }

    public static function deleteUsersTable() {
        global $wpdb;

        $table_name = $wpdb->prefix . User::TABLE_NAME;
        $wpdb->query( "DROP TABLE IF EXISTS `$table_name`" );
    }
    
    public static function cleanupPluginOptions(): void {
        // Delete main plugin settings
        delete_option(\OxygenApp\Utils\OptionUtils::OPTION_GROUP_SLUG);
    }
}