<?php
// Simple migration to add commission_rate to kullanici2 if missing
// Usage: open this file in browser once (e.g., /woohdd/migrate_affiliate_commission_rate.php)

session_start();
header('Content-Type: text/plain; charset=utf-8');

// Optional: require admin session if your panel uses it
// Allow running from CLI without session requirement
if (php_sapi_name() !== 'cli' && !isset($_SESSION['admin_logged_in'])) {
    http_response_code(401);
    echo "Unauthorized. Please login to admin panel.";
    exit;
}

include __DIR__ . '/dblive.php';

try {
    $pdo = new PDO("mysql:host=$user_db_servername;dbname=$user_db_name;charset=utf8", $user_db_username, $user_db_password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    http_response_code(500);
    echo 'DB connect error: ' . $e->getMessage();
    exit;
}

try {
    // Check if column exists
    $stmt = $pdo->prepare("SHOW COLUMNS FROM kullanici2 LIKE 'commission_rate'");
    $stmt->execute();
    $exists = (bool)$stmt->fetch(PDO::FETCH_ASSOC);

    if (!$exists) {
        // Add column: store ratio (e.g., 0.10 for 10%) with default
        $pdo->exec("ALTER TABLE kullanici2 ADD COLUMN commission_rate DECIMAL(5,4) NULL DEFAULT 0.10 AFTER email");
        echo "Added column commission_rate (DEFAULT 0.10) to kullanici2\n";
    } else {
        // Ensure default is 0.10 for existing column
        $pdo->exec("ALTER TABLE kullanici2 MODIFY commission_rate DECIMAL(5,4) NULL DEFAULT 0.10");
        echo "Ensured commission_rate DEFAULT is 0.10\n";
    }

    // Initialize null or zero values to default 0.10
    $affected = $pdo->exec("UPDATE kullanici2 SET commission_rate = 0.10 WHERE commission_rate IS NULL OR commission_rate = 0");
    echo "Initialized commission_rate to 0.10 where missing (rows: $affected)\n";

    echo "Migration completed successfully.";
} catch (PDOException $e) {
    http_response_code(500);
    echo 'Migration error: ' . $e->getMessage();
}