<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
include_once __DIR__ . "/../config.php";

$input = json_decode(file_get_contents("php://input"), true);
$days = isset($input['days_threshold']) ? (int)$input['days_threshold'] : null;
$percent = isset($input['commission_percent']) ? (float)$input['commission_percent'] : null;

if ($days === null || $percent === null) {
    echo json_encode(["success" => false, "message" => "days_threshold and commission_percent required"]);
    exit;
}

try {
    // Use a single-row table; update existing row or insert if not exists
    $stmt = $conn->prepare("UPDATE deposit_unused_commission_settings SET days_threshold = ?, commission_percent = ? LIMIT 1");
    $stmt->bind_param("id", $days, $percent);
    $stmt->execute();

    if ($stmt->affected_rows === 0) {
        // no row updated — try insert
        $stmt->close();
        $stmt = $conn->prepare("INSERT INTO deposit_unused_commission_settings (days_threshold, commission_percent) VALUES (?, ?)");
        $stmt->bind_param("id", $days, $percent);
        $stmt->execute();
    }

    $stmt->close();
    echo json_encode(["success" => true, "message" => "Settings updated"]);
} catch (Throwable $e) {
    error_log("admin_update_deposit_unused_com error: " . $e->getMessage());
    echo json_encode(["success" => false, "message" => "Server error"]);
}
