<?php
/**
 * Auto-migration: frame/boost/plus sütunlarını otomatik oluşturur.
 * index.php'den çağrılır — her istekte kontrol eder, yoksa ekler.
 * Ekledikten sonra tekrar kontrol etmez (flag dosyası kullanır).
 */

namespace App\Utils;

use App\Config\Database;

class AutoMigrate {
    
    public static function run(): void {
        self::migrateFrameBoost();
        self::migratePlusSubscription();
        self::migrateLegalTracking();
        self::migrateProfileFields();
    }

    private static function migrateFrameBoost(): void {
        $flagFile = __DIR__ . '/../../.migration_frame_boost_done';
        if (file_exists($flagFile)) {
            return;
        }

        try {
            $db = Database::getInstance()->getConnection();
            $dbName = $db->query("SELECT DATABASE()")->fetchColumn();

            $columns = [
                'active_frame'       => "ALTER TABLE users ADD COLUMN active_frame VARCHAR(50) NULL DEFAULT NULL",
                'boosted_until'      => "ALTER TABLE users ADD COLUMN boosted_until TIMESTAMP NULL DEFAULT NULL",
                'is_plus_subscriber' => "ALTER TABLE users ADD COLUMN is_plus_subscriber TINYINT(1) NOT NULL DEFAULT 0",
            ];

            foreach ($columns as $col => $alter) {
                $stmt = $db->prepare(
                    "SELECT COUNT(*) FROM information_schema.COLUMNS 
                     WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'users' AND COLUMN_NAME = ?"
                );
                $stmt->execute([$dbName, $col]);
                if ((int)$stmt->fetchColumn() === 0) {
                    $db->exec($alter);
                }
            }

            // Index ekle
            $stmt = $db->prepare(
                "SELECT COUNT(*) FROM information_schema.STATISTICS 
                 WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'users' AND INDEX_NAME = 'idx_users_boosted_until'"
            );
            $stmt->execute([$dbName]);
            if ((int)$stmt->fetchColumn() === 0) {
                $db->exec("ALTER TABLE users ADD INDEX idx_users_boosted_until (boosted_until)");
            }

            file_put_contents($flagFile, date('Y-m-d H:i:s'));
        } catch (\Exception $e) {
            error_log('[AutoMigrate] Frame/Boost Error: ' . $e->getMessage());
        }
    }

    private static function migratePlusSubscription(): void {
        $flagFile = __DIR__ . '/../../.migration_plus_subscription_done';
        if (file_exists($flagFile)) {
            return;
        }

        try {
            $db = Database::getInstance()->getConnection();
            $dbName = $db->query("SELECT DATABASE()")->fetchColumn();

            // users tablosuna plus sütunları ekle
            $columns = [
                'subscription_tier'  => "ALTER TABLE users ADD COLUMN subscription_tier VARCHAR(20) NULL DEFAULT NULL",
                'plus_expires_at'    => "ALTER TABLE users ADD COLUMN plus_expires_at TIMESTAMP NULL DEFAULT NULL",
            ];

            foreach ($columns as $col => $alter) {
                $stmt = $db->prepare(
                    "SELECT COUNT(*) FROM information_schema.COLUMNS 
                     WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'users' AND COLUMN_NAME = ?"
                );
                $stmt->execute([$dbName, $col]);
                if ((int)$stmt->fetchColumn() === 0) {
                    $db->exec($alter);
                }
            }

            // subscriptions tablosu yoksa oluştur
            $db->exec("CREATE TABLE IF NOT EXISTS subscriptions (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                platform VARCHAR(20) NOT NULL DEFAULT 'android',
                product_id VARCHAR(100) NOT NULL,
                status VARCHAR(20) NOT NULL DEFAULT 'active',
                started_at TIMESTAMP NULL,
                expires_at TIMESTAMP NULL,
                original_transaction_id VARCHAR(255) NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_sub_user (user_id),
                INDEX idx_sub_status (status)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

            file_put_contents($flagFile, date('Y-m-d H:i:s'));
        } catch (\Exception $e) {
            error_log('[AutoMigrate] Plus Subscription Error: ' . $e->getMessage());
        }
    }

    private static function migrateLegalTracking(): void {
        $flagFile = __DIR__ . '/../../.migration_legal_tracking_done';
        if (file_exists($flagFile)) {
            return;
        }

        try {
            $db = Database::getInstance()->getConnection();
            $dbName = $db->query("SELECT DATABASE()")->fetchColumn();

            $columns = [
                'registration_ip' => "ALTER TABLE users ADD COLUMN registration_ip VARCHAR(45) NULL AFTER link_slug",
                'last_ip'         => "ALTER TABLE users ADD COLUMN last_ip VARCHAR(45) NULL AFTER registration_ip",
                'device_info'     => "ALTER TABLE users ADD COLUMN device_info JSON NULL AFTER last_ip",
            ];

            foreach ($columns as $col => $alter) {
                $stmt = $db->prepare(
                    "SELECT COUNT(*) FROM information_schema.COLUMNS 
                     WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'users' AND COLUMN_NAME = ?"
                );
                $stmt->execute([$dbName, $col]);
                if ((int)$stmt->fetchColumn() === 0) {
                    $db->exec($alter);
                }
            }

            file_put_contents($flagFile, date('Y-m-d H:i:s'));
        } catch (\Exception $e) {
            error_log('[AutoMigrate] Legal Tracking Error: ' . $e->getMessage());
        }
    }

    private static function migrateProfileFields(): void {
        $flagFile = __DIR__ . '/../../.migration_profile_fields_done';
        if (file_exists($flagFile)) {
            return;
        }

        try {
            $db = Database::getInstance()->getConnection();
            $dbName = $db->query("SELECT DATABASE()")->fetchColumn();

            $columns = [
                'full_name' => "ALTER TABLE users ADD COLUMN full_name VARCHAR(100) NULL AFTER device_info",
                'city'      => "ALTER TABLE users ADD COLUMN city VARCHAR(100) NULL AFTER full_name",
                'country'   => "ALTER TABLE users ADD COLUMN country VARCHAR(100) NULL AFTER city",
            ];

            foreach ($columns as $col => $alter) {
                $stmt = $db->prepare(
                    "SELECT COUNT(*) FROM information_schema.COLUMNS 
                     WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'users' AND COLUMN_NAME = ?"
                );
                $stmt->execute([$dbName, $col]);
                if ((int)$stmt->fetchColumn() === 0) {
                    $db->exec($alter);
                }
            }

            file_put_contents($flagFile, date('Y-m-d H:i:s'));
        } catch (\Exception $e) {
            error_log('[AutoMigrate] Profile Fields Error: ' . $e->getMessage());
        }
    }
}

