<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

$conn = new mysqli("localhost", "kdsmf_eppd", "8DL!AesMeEt(%mgc", "kdsmf_epd");
if ($conn->connect_error) { echo json_encode(['status'=>'error','message'=>'DB: '.$conn->connect_error]); exit; }
$conn->set_charset("utf8mb4");

// Create table without UNIQUE constraint first
$conn->query("CREATE TABLE IF NOT EXISTS balance_overrides (
    id INT AUTO_INCREMENT PRIMARY KEY,
    wallet VARCHAR(255) NOT NULL,
    direct_balance DECIMAL(18,4) DEFAULT NULL,
    reason TEXT,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$method = $_SERVER['REQUEST_METHOD'];

// ── GET: list ────────────────────────────────────────────────
if ($method === 'GET') {
    $users = [];
    $q = $conn->query("SELECT id, name, wallet, account_id, status FROM users ORDER BY id DESC");
    if (!$q) { echo json_encode(['status'=>'error','message'=>$conn->error]); exit; }
    while ($r = $q->fetch_assoc()) $users[] = $r;
    if (empty($users)) { echo json_encode(['status'=>'success','users'=>[],'count'=>0]); exit; }

    $inW = implode(',', array_map(fn($u) => "'".$conn->real_escape_string($u['wallet'])."'", $users));
    $inA = implode(',', array_map(fn($u) => "'".$conn->real_escape_string($u['account_id'])."'", $users));

    $invMap=$roiMap=$levelMap=$wdMap=$overrideMap=$directMap=$udMap=[];

    $r=$conn->query("SELECT wallet,SUM(amount) amt FROM deposits WHERE wallet IN ($inW) AND status='success' GROUP BY wallet");
    while($r&&$row=$r->fetch_assoc()) $invMap[$row['wallet']]=(float)$row['amt'];

    $r=$conn->query("SELECT wallet,SUM(pnl_amount) total FROM trade_logs WHERE wallet IN ($inW) GROUP BY wallet");
    while($r&&$row=$r->fetch_assoc()) $roiMap[$row['wallet']]=(float)$row['total'];

    $r=$conn->query("SELECT wallet,SUM(amount) total FROM level_logs WHERE wallet IN ($inW) GROUP BY wallet");
    while($r&&$row=$r->fetch_assoc()) $levelMap[$row['wallet']]=(float)$row['total'];

    $r=$conn->query("SELECT u.referral_id parent,SUM(d.amount) total FROM users u JOIN deposits d ON u.wallet=d.wallet AND d.status='success' WHERE u.referral_id IN ($inA) GROUP BY u.referral_id");
    $tmp=[];
    while($r&&$row=$r->fetch_assoc()) $tmp[$row['parent']]=(float)$row['total']*0.03;
    foreach($users as $u) $directMap[$u['wallet']]=$tmp[$u['account_id']]??0;

    $r=$conn->query("SELECT wallet,type,status,SUM(amount) amt FROM withdrawals WHERE wallet IN ($inW) GROUP BY wallet,type,status");
    while($r&&$row=$r->fetch_assoc()) $wdMap[$row['wallet']][$row['type'].'_'.$row['status']]=(float)$row['amt'];

    $r=$conn->query("SELECT wallet,reward_tier_1,reward_tier_2,reward_tier_3 FROM users WHERE wallet IN ($inW)");
    while($r&&$row=$r->fetch_assoc()) $udMap[$row['wallet']]=$row;

    $r=$conn->query("SELECT * FROM balance_overrides WHERE wallet IN ($inW)");
    while($r&&$row=$r->fetch_assoc()) $overrideMap[$row['wallet']]=$row;

    $result=[];
    foreach($users as $u) {
        $w=$u['wallet']; $inv=$invMap[$w]??0; $wd=$wdMap[$w]??[]; $ov=$overrideMap[$w]??null; $ud=$udMap[$w]??[];
        $t1=$ud['reward_tier_1']??0; $t2=$ud['reward_tier_2']??0; $t3=$ud['reward_tier_3']??0;
        $rb=$t3?81:($t2?36:($t1?12:0));
        $pw=$wd['income_completed']??0; $pp=$wd['income_pending']??0;
        $tw=$wd['trading_completed']??0; $tp=$wd['trading_pending']??0;
        $prw=$wd['principal_completed']??0; $prp=$wd['principal_pending']??0;
        $hasOv=($ov&&$ov['direct_balance']!==null);
        if($hasOv) {
            $avail=(float)$ov['direct_balance'];
        } else {
            $roi=$roiMap[$w]??0; $dir=$directMap[$w]??0; $joi=$inv*0.05; $lvl=$levelMap[$w]??0;
            $tG=max(0,$roi); $oG=$dir+$joi+$rb+$lvl;
            $totW=$pw+$pp+$tw+$tp+$prw+$prp;
            $fT=min($totW,$tG); $fO=min(max(0,$totW-$fT),$oG);
            $avail=max(0,($tG-$fT)+($oG-$fO));
        }
        $result[]=['wallet'=>$w,'name'=>$u['name'],'account_id'=>$u['account_id'],
            'status'=>$u['status']??($inv>=60?'active':'inactive'),
            'invested'=>round($inv,2),'trading_pnl'=>round($roiMap[$w]??0,4),
            'withdrawn'=>round($pw+$tw+$prw,2),'available'=>round($avail,2),
            'has_override'=>$hasOv?1:0,
            'override_amount'=>$hasOv?(float)$ov['direct_balance']:null,
            'override_reason'=>$ov['reason']??null,
            'override_updated_at'=>$ov['updated_at']??null];
    }
    echo json_encode(['status'=>'success','users'=>$result,'count'=>count($result)]);
    exit;
}

// ── POST ─────────────────────────────────────────────────────
if ($method === 'POST') {
    $body = json_decode(file_get_contents('php://input'), true);
    if (!is_array($body)) { echo json_encode(['status'=>'error','message'=>'Invalid JSON']); exit; }
    $action = trim($body['action'] ?? '');

    // SET BALANCE
    if ($action === 'set_balance') {
        $wallet = trim($body['wallet'] ?? '');
        $amount = $body['amount'] ?? null;
        $reason = trim($body['reason'] ?? '');
        if (!$wallet) { echo json_encode(['status'=>'error','message'=>'Wallet required']); exit; }
        if ($amount===null||$amount==='') { echo json_encode(['status'=>'error','message'=>'Amount required']); exit; }
        $amount = round((float)$amount, 4);
        if ($amount < 0) { echo json_encode(['status'=>'error','message'=>'Amount negative']); exit; }

        $sw  = $conn->real_escape_string($wallet);
        $rsn = $conn->real_escape_string($reason);

        // Check user exists
        $chk = $conn->query("SELECT id FROM users WHERE wallet='$sw' LIMIT 1");
        if (!$chk || $chk->num_rows === 0) { echo json_encode(['status'=>'error','message'=>'User not found']); exit; }

        // Check if override row exists
        $ex = $conn->query("SELECT id FROM balance_overrides WHERE wallet='$sw' LIMIT 1");
        if (!$ex) { echo json_encode(['status'=>'error','message'=>'Check failed: '.$conn->error]); exit; }

        if ($ex->num_rows > 0) {
            $sql = "UPDATE balance_overrides SET direct_balance='$amount', reason='$rsn', updated_at=NOW() WHERE wallet='$sw'";
        } else {
            $sql = "INSERT INTO balance_overrides (wallet, direct_balance, reason, updated_at) VALUES ('$sw', '$amount', '$rsn', NOW())";
        }

        if ($conn->query($sql)) {
            echo json_encode(['status'=>'success','message'=>'Balance set to $'.number_format($amount,2),'amount'=>$amount]);
        } else {
            echo json_encode(['status'=>'error','message'=>'Save failed: '.$conn->error]);
        }
        exit;
    }

    // CLEAR OVERRIDE
    if ($action === 'clear_override') {
        $wallet = trim($body['wallet'] ?? '');
        if (!$wallet) { echo json_encode(['status'=>'error','message'=>'Wallet required']); exit; }
        $sw = $conn->real_escape_string($wallet);
        $conn->query("DELETE FROM balance_overrides WHERE wallet='$sw'");
        echo json_encode(['status'=>'success','message'=>'Override cleared.']);
        exit;
    }

    echo json_encode(['status'=>'error','message'=>'Unknown action: '.$action]);
    exit;
}

echo json_encode(['status'=>'error','message'=>'Bad request']);
?>