<?php
session_start();
if (!isset($_SESSION['unohs'])) {
    header("Location: index.php");
    exit();
}
include "conn.php";

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['agent_id'])) {
    header("Location: manage_agents.php?msg=invalid");
    exit();
}

$agentId = intval($_POST['agent_id']);
$nagadNumber = trim($_POST['nagad_number'] ?? '');
$bkashNumber = trim($_POST['bkash_number'] ?? '');
$commissionRate = isset($_POST['commission_rate']) ? floatval($_POST['commission_rate']) : null;
$commissionType = (isset($_POST['commission_type']) && $_POST['commission_type'] === 'deposit') ? 'deposit' : 'ggr';

if ($agentId <= 0) {
    header("Location: manage_agents.php?msg=invalid");
    exit();
}

if ($commissionRate !== null) {
    if ($commissionRate < 0) { $commissionRate = 0; }
    if ($commissionRate > 100) { $commissionRate = 100; }
    $stmt = $conn->prepare("UPDATE tb_agent SET nagad_number = ?, bkash_number = ?, commission_rate = ?, commission_type = ? WHERE id = ?");
    $stmt->bind_param("ssdsi", $nagadNumber, $bkashNumber, $commissionRate, $commissionType, $agentId);
} else {
    $stmt = $conn->prepare("UPDATE tb_agent SET nagad_number = ?, bkash_number = ?, commission_type = ? WHERE id = ?");
    $stmt->bind_param("sssi", $nagadNumber, $bkashNumber, $commissionType, $agentId);
}
$success = $stmt->execute();
$stmt->close();
$conn->close();

header("Location: manage_agents.php?msg=" . ($success ? 'wallet_saved' : 'error'));
exit();
