<?php
require 'config/db.php';

try {
    // Drop if exists to be sure
    $pdo->exec("DROP TABLE IF EXISTS site_config");
    
    // Create site_config
    $sql_config = "
    CREATE TABLE site_config (
        id INT AUTO_INCREMENT PRIMARY KEY,
        setting_key VARCHAR(50) NOT NULL UNIQUE,
        setting_value TEXT,
        description TEXT,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";
    $pdo->exec($sql_config);

    // Insert default economy settings
    $sql_defaults = "
    INSERT IGNORE INTO site_config (setting_key, setting_value, description) VALUES 
    ('diamond_exchange_rate', '0.01', 'Value of 1 Diamond in USD'),
    ('min_withdrawal_diamonds', '100', 'Minimum diamonds required to withdraw'),
    ('withdrawal_fee_percent', '0', 'Percentage fee for withdrawals'),
    ('sales_fee_percent', '10', 'Percentage fee for marketplace sales'),
    ('chat_unlock_fee_percent', '20', 'Fee for pay-to-view messages'),
    ('subscription_fee_percent', '25', 'Fee for creator subscriptions'),
    ('chest_item_fee_percent', '15', 'Comisión por venta de ítems del cofre (%)');
    ";
    $pdo->exec($sql_defaults);

    // Create chest_items if missing
    $sql_chest = "CREATE TABLE IF NOT EXISTS chest_items (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT,
        name VARCHAR(255),
        type ENUM('image', 'video', 'audio', 'pdf', 'documento', 'otro'),
        file_url VARCHAR(255),
        price INT DEFAULT 0,
        is_public BOOLEAN DEFAULT FALSE,
        description TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";
    $pdo->exec($sql_chest);

    echo json_encode(['success' => true, 'message' => 'FRESH database setup finished.']);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Fresh setup failed: ' . $e->getMessage()]);
}
?>
