<?php
// --- MANUAL OVERRIDE FACTORY RESET ---
$db_path = __DIR__ . '/app_feed.db';

try {
    // 1. Explicitly close any open connection
    $db = new PDO('sqlite:' . $db_path);
    
    // 2. Drop tables one by one to clear data without deleting the file
    $tables = ['users', 'user_registrations', 'user_settings', 'transactions', 'comments', 'settings', 'app_feed_settings'];
    foreach ($tables as $table) {
        $db->exec("DROP TABLE IF EXISTS $table");
    }

    // 3. Rebuild the schema
    // Added 'min_withdrawal REAL' and 'country_code TEXT' to users table to match your dashboard
    $db->exec("BEGIN TRANSACTION;
        CREATE TABLE user_registrations (
            id INTEGER PRIMARY KEY AUTOINCREMENT, 
            username TEXT, 
            email TEXT, 
            phone TEXT, 
            status TEXT DEFAULT 'Pending', 
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        );
        CREATE TABLE users (
            id TEXT PRIMARY KEY, 
            name TEXT, 
            phone TEXT, 
            balance REAL, 
            tier TEXT,
            min_withdrawal REAL DEFAULT 0.00,
            country_code TEXT
        );
        CREATE TABLE user_settings (
            user_id TEXT PRIMARY KEY, 
            withdrawal_locked INTEGER DEFAULT 0
        );
        CREATE TABLE transactions (
            id INTEGER PRIMARY KEY AUTOINCREMENT, 
            user_id TEXT, 
            amount_usd REAL, 
            status TEXT DEFAULT 'Pending', 
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        );
        CREATE TABLE comments (
            id INTEGER PRIMARY KEY AUTOINCREMENT, 
            username TEXT, 
            comment TEXT, 
            tier TEXT, 
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
        );
        CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT);
        INSERT INTO settings (key, value) VALUES ('min_withdrawal_tier', 'Gold Tier');
        CREATE TABLE app_feed_settings (setting_key TEXT PRIMARY KEY, setting_value TEXT);
        INSERT INTO app_feed_settings (setting_key, setting_value) VALUES ('system_status', 'Active');
    COMMIT;");

    echo "Factory reset successful. All tables have been cleared and rebuilt.";
    $db = null; // Close connection
    
    // Redirect back to admin panel after 2 seconds
    header("refresh:2;url=admin.php");
} catch (Exception $e) {
    echo "Reset failed: " . $e->getMessage();
}
?>