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

// Yalnızca admin girişliyken işlem yapılmasına izin ver
if (!isset($_SESSION['admin_logged_in'])) {
    http_response_code(401);
    echo 'Unauthorized';
    exit;
}

// DB kimlik bilgilerini al
include '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: ' . htmlspecialchars($e->getMessage());
    exit;
}

// Girdi doğrulama
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$rate = isset($_POST['commission_rate']) ? trim($_POST['commission_rate']) : '';

if ($id <= 0 || $rate === '' || !is_numeric($rate)) {
    http_response_code(400);
    echo 'Bad request';
    exit;
}

$num = (float)$rate;
if ($num < 0 || $num > 1) {
    http_response_code(400);
    echo 'Rate must be between 0 and 1 (e.g., 0.10)';
    exit;
}

try {
    // Ensure column exists and default is 0.10
    $check = $pdo->prepare("SHOW COLUMNS FROM kullanici2 LIKE 'commission_rate'");
    $check->execute();
    if (!$check->fetch(PDO::FETCH_ASSOC)) {
        $pdo->exec("ALTER TABLE kullanici2 ADD COLUMN commission_rate DECIMAL(5,4) NULL DEFAULT 0.10");
    } else {
        $pdo->exec("ALTER TABLE kullanici2 MODIFY commission_rate DECIMAL(5,4) NULL DEFAULT 0.10");
    }
    $stmt = $pdo->prepare('UPDATE kullanici2 SET commission_rate = :rate, updated_at = NOW() WHERE id = :id');
    $stmt->execute([':rate' => $num, ':id' => $id]);
    http_response_code(200);
    echo 'OK';
} catch (PDOException $e) {
    http_response_code(500);
    echo 'DB error: ' . htmlspecialchars($e->getMessage());
}