<?php
/**
 * agent_ggr_commission.php
 * ✅ আলাদা, স্বতন্ত্র ফাইল — commission_api.php বা অন্য কোনো
 *    Existing ফাইল স্পর্শ করা হয়নি।
 *
 * GGR = SUM(bet_amount) - SUM(win_amount)   [downline user-দের]
 * Agent Commission = GGR × MY_COMMISSION_RATE%
 *
 * ✅ FIX — Agent আর নিজে Commission-কে সরাসরি নিজের Balance-এ
 *    Claim করতে পারবে না। এখন শুধু Admin-এর কাছে "Sell" (Cash-out
 *    Request) করতে পারবে — নিজের bKash/Nagad Number দিয়ে।
 *    Admin Approve করলে তবেই টাকা যাবে (Adminxxx78/commission_sell_requests.php)।
 *    Agent-এর এখানে আর কোনো অন্য Action নেই — শুধু Request পাঠানো।
 */

session_start();
if (!isset($_SESSION['agent_uid']) || $_SESSION['agent_uid'] == "") {
    header("location:index.php");
    exit;
}
include("conn.php");

$agent_uid = $_SESSION['agent_uid'];
$agent_mobile = $_SESSION['agent_mobile'];

// Agent এখনো Active কিনা যাচাই
$agent_verify = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT userid FROM tb_agent WHERE userid='$agent_uid' AND status='1'"
));
if (!$agent_verify) {
    session_destroy();
    header("location:index.php?err=kicked");
    exit;
}

$agent_wallet = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT motta FROM shonu_kaichila WHERE balakedara='$agent_uid'"
));
$agent_balance = $agent_wallet['motta'] ?? 0;

$agent_code_row = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT owncode FROM shonu_subjects WHERE id='$agent_uid'"
));
$agent_owncode = $agent_code_row['owncode'] ?? '';

/* ══════════════════════════════════════════════════════════
   কমিশন রেট আর টাইপ — প্রতিটা Agent-এর জন্য আলাদা
   commission_type: 'ggr' (Bet-Win ভিত্তিক) বা 'deposit' (Deposit Amount ভিত্তিক)
   ══════════════════════════════════════════════════════════ */
$rateRow = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT commission_rate, commission_type FROM tb_agent WHERE userid = '".$agent_uid."'"
));
$MY_COMMISSION_RATE = $rateRow && $rateRow['commission_rate'] !== null ? floatval($rateRow['commission_rate']) : 30.0;
$MY_COMMISSION_TYPE = ($rateRow && $rateRow['commission_type'] === 'deposit') ? 'deposit' : 'ggr';

/* ══════════════════════════════════════════════════════════
   Sell Request টেবিল — না থাকলে নিজে থেকে তৈরি হবে
   status: pending → Admin এখনো দেখেনি
           approved → Admin টাকা পাঠিয়ে দিয়েছে
           rejected → Admin বাতিল করেছে, Amount আবার Available হবে
   ══════════════════════════════════════════════════════════ */
mysqli_query($conn, "
    CREATE TABLE IF NOT EXISTS commission_sell_requests (
        id INT AUTO_INCREMENT PRIMARY KEY,
        agent_userid VARCHAR(50) NOT NULL,
        ggr_amount DECIMAL(15,2) NOT NULL,
        commission_amount DECIMAL(15,2) NOT NULL,
        commission_rate DECIMAL(5,2) NOT NULL,
        payment_method VARCHAR(20) NOT NULL,
        payment_number VARCHAR(20) NOT NULL,
        status VARCHAR(20) NOT NULL DEFAULT 'pending',
        requested_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        processed_at DATETIME NULL,
        commission_type VARCHAR(20) NOT NULL DEFAULT 'ggr'
    )
");
$colCheckType = mysqli_query($conn, "SHOW COLUMNS FROM commission_sell_requests LIKE 'commission_type'");
if ($colCheckType && mysqli_num_rows($colCheckType) === 0) {
    mysqli_query($conn, "ALTER TABLE commission_sell_requests ADD COLUMN commission_type VARCHAR(20) NOT NULL DEFAULT 'ggr'");
}

$message = '';
$message_type = '';

/* ══════════════════════════════════════════════════════════
   Downline user-দের ID খুঁজে বের করা
   ══════════════════════════════════════════════════════════ */
function get_downline_ids($conn, $agent_owncode) {
    $ids = [];
    if ($agent_owncode !== '') {
        $q = mysqli_query($conn, "SELECT id FROM shonu_subjects WHERE code = '".mysqli_real_escape_string($conn, $agent_owncode)."'");
        while ($r = mysqli_fetch_assoc($q)) {
            $ids[] = $r['id'];
        }
    }
    return $ids;
}

/* ══════════════════════════════════════════════════════════
   GGR (Bet - Win) থেকে Available (এখনো Sell করা হয়নি এমন) Commission
   ══════════════════════════════════════════════════════════ */
function calculate_ggr_commission($conn, $agent_uid, $downlineIds, $rate) {
    if (empty($downlineIds)) {
        return ['base_amount' => 0, 'total_bet' => 0, 'total_win' => 0, 'total_earned' => 0, 'total_locked' => 0, 'available_to_sell' => 0, 'downline_count' => 0];
    }

    $placeholders = implode(',', array_fill(0, count($downlineIds), '?'));
    $types = str_repeat('s', count($downlineIds));

    $stmt = $conn->prepare("SELECT SUM(bet_amount) as total_bet, SUM(win_amount) as total_win FROM game_bet_logs WHERE user_id IN ($placeholders)");
    $stmt->bind_param($types, ...$downlineIds);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();

    $totalBet = (float)($row['total_bet'] ?? 0);
    $totalWin = (float)($row['total_win'] ?? 0);
    $ggr = max(0, $totalBet - $totalWin);

    $totalEarned = round($ggr * ($rate / 100), 2);

    $lockedStmt = $conn->prepare("SELECT SUM(commission_amount) as total FROM commission_sell_requests WHERE agent_userid = ? AND status IN ('pending','approved') AND commission_type = 'ggr'");
    $lockedStmt->bind_param("s", $agent_uid);
    $lockedStmt->execute();
    $totalLocked = (float)($lockedStmt->get_result()->fetch_assoc()['total'] ?? 0);

    $availableToSell = max(0, round($totalEarned - $totalLocked, 2));

    return [
        'base_amount' => round($ggr, 2),
        'total_bet' => round($totalBet, 2),
        'total_win' => round($totalWin, 2),
        'total_earned' => $totalEarned,
        'total_locked' => round($totalLocked, 2),
        'available_to_sell' => $availableToSell,
        'downline_count' => count($downlineIds)
    ];
}

/* ══════════════════════════════════════════════════════════
   Downline-দের মোট Approved Deposit (thevani.sthiti='1') থেকে
   Available (এখনো Sell করা হয়নি এমন) Commission
   ══════════════════════════════════════════════════════════ */
function calculate_deposit_commission($conn, $agent_uid, $downlineIds, $rate) {
    if (empty($downlineIds)) {
        return ['base_amount' => 0, 'total_deposit' => 0, 'total_earned' => 0, 'total_locked' => 0, 'available_to_sell' => 0, 'downline_count' => 0];
    }

    $idList = implode(',', array_map('intval', $downlineIds));
    $depRow = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT COALESCE(SUM(motta),0) as total FROM thevani WHERE balakedara IN ($idList) AND sthiti = '1'"
    ));
    $totalDeposit = floatval($depRow['total']);

    $totalEarned = round($totalDeposit * ($rate / 100), 2);

    $lockedStmt = $conn->prepare("SELECT SUM(commission_amount) as total FROM commission_sell_requests WHERE agent_userid = ? AND status IN ('pending','approved') AND commission_type = 'deposit'");
    $lockedStmt->bind_param("s", $agent_uid);
    $lockedStmt->execute();
    $totalLocked = (float)($lockedStmt->get_result()->fetch_assoc()['total'] ?? 0);

    $availableToSell = max(0, round($totalEarned - $totalLocked, 2));

    return [
        'base_amount' => round($totalDeposit, 2),
        'total_deposit' => round($totalDeposit, 2),
        'total_earned' => $totalEarned,
        'total_locked' => round($totalLocked, 2),
        'available_to_sell' => $availableToSell,
        'downline_count' => count($downlineIds)
    ];
}

$downlineIds = get_downline_ids($conn, $agent_owncode);
$summary = ($MY_COMMISSION_TYPE === 'deposit')
    ? calculate_deposit_commission($conn, $agent_uid, $downlineIds, MY_COMMISSION_RATE)
    : calculate_ggr_commission($conn, $agent_uid, $downlineIds, MY_COMMISSION_RATE);

/* ══════════════════════════════════════════════════════════
   Sell Request পাঠানো — শুধু Request তৈরি হবে, কোনো Balance
   সরাসরি বাড়বে না। Admin Approve করলে তবেই টাকা যাবে।
   ══════════════════════════════════════════════════════════ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'sell') {
    $sellAmount = round((float)($_POST['sell_amount'] ?? 0), 2);
    $paymentMethod = ($_POST['payment_method'] ?? '') === 'nagad' ? 'nagad' : 'bkash';
    $paymentNumberRaw = trim($_POST['payment_number'] ?? '');
    $paymentNumber = preg_replace('/[^0-9]/', '', $paymentNumberRaw);

    if (!preg_match('/^01[0-9]{9}$/', $paymentNumber)) {
        $message = '❌ সঠিক ১১-সংখ্যার bKash/Nagad Number দাও (01XXXXXXXXX)।';
        $message_type = 'danger';
    } elseif ($sellAmount <= 0 || $sellAmount > $summary['available_to_sell']) {
        $message = '❌ Amount ঠিক নেই — Available Commission-এর বেশি Sell করা যাবে না।';
        $message_type = 'danger';
    } else {
        $insertStmt = $conn->prepare("
            INSERT INTO commission_sell_requests
            (agent_userid, ggr_amount, commission_amount, commission_rate, payment_method, payment_number, status, commission_type)
            VALUES (?, ?, ?, ?, ?, ?, 'pending', ?)
        ");
        $insertStmt->bind_param("sdddsss", $agent_uid, $summary['base_amount'], $sellAmount, $MY_COMMISSION_RATE, $paymentMethod, $paymentNumber, $MY_COMMISSION_TYPE);
        $insertStmt->execute();
        $insertStmt->close();

        $message = "✅ ৳".number_format($sellAmount, 2)." Sell Request পাঠানো হয়েছে। Admin Approve করলে তোমার $paymentMethod ($paymentNumber) নাম্বারে টাকা পাঠাবে।";
        $message_type = 'success';

        $summary = ($MY_COMMISSION_TYPE === 'deposit')
            ? calculate_deposit_commission($conn, $agent_uid, $downlineIds, MY_COMMISSION_RATE)
            : calculate_ggr_commission($conn, $agent_uid, $downlineIds, MY_COMMISSION_RATE);
    }
}

/* ══════════════════════════════════════════════════════════
   Sell Request History
   ══════════════════════════════════════════════════════════ */
$history = [];
$histStmt = $conn->prepare("SELECT ggr_amount, commission_amount, commission_rate, payment_method, payment_number, status, requested_at, processed_at FROM commission_sell_requests WHERE agent_userid = ? AND commission_type = ? ORDER BY requested_at DESC LIMIT 50");
$histStmt->bind_param("ss", $agent_uid, $MY_COMMISSION_TYPE);
$histStmt->execute();
$histResult = $histStmt->get_result();
while ($r = $histResult->fetch_assoc()) { $history[] = $r; }

$pageTitle = $MY_COMMISSION_TYPE === 'deposit' ? 'Deposit Commission' : 'GGR Commission';
$baseLabel = $MY_COMMISSION_TYPE === 'deposit' ? 'মোট Deposit' : 'GGR (Bet - Win)';

include("header.php");
?>

<div class="al-wrap">
  <div class="al-page-title"><?php echo $pageTitle; ?></div>
  <div class="al-page-sub">তোমার Commission শুধু Admin-এর কাছে Sell করা যাবে — bKash/Nagad Number দিয়ে Request পাঠাও</div>

  <?php if ($message): ?>
  <div class="al-alert al-alert-<?php echo $message_type; ?>"><?php echo htmlspecialchars($message); ?></div>
  <?php endif; ?>

  <div class="al-card credit" style="text-align:center;">
    <div style="color:var(--text-faint);font-size:11px;text-transform:uppercase;margin-bottom:6px;">Sell করার মতো Commission</div>
    <div class="amt mono" style="font-size:28px;">৳<?php echo number_format($summary['available_to_sell'], 2); ?></div>
  </div>

  <form method="POST" class="al-table-wrap" style="padding:16px;">
    <input type="hidden" name="action" value="sell">
    <div style="margin-bottom:10px;">
      <label style="font-size:12px;color:var(--text-faint);display:block;margin-bottom:4px;">Sell করার Amount</label>
      <input type="number" name="sell_amount" min="1" step="0.01" max="<?php echo $summary['available_to_sell']; ?>"
             placeholder="যেমন: 500" required
             style="width:100%;padding:10px;border-radius:8px;border:1px solid var(--border);background:var(--bg);color:var(--text);">
    </div>
    <div style="margin-bottom:10px;">
      <label style="font-size:12px;color:var(--text-faint);display:block;margin-bottom:4px;">Payment Method</label>
      <select name="payment_method" required
              style="width:100%;padding:10px;border-radius:8px;border:1px solid var(--border);background:var(--bg);color:var(--text);">
        <option value="bkash">bKash</option>
        <option value="nagad">Nagad</option>
      </select>
    </div>
    <div style="margin-bottom:14px;">
      <label style="font-size:12px;color:var(--text-faint);display:block;margin-bottom:4px;">bKash/Nagad Number</label>
      <input type="text" name="payment_number" placeholder="01XXXXXXXXX" required maxlength="11"
             style="width:100%;padding:10px;border-radius:8px;border:1px solid var(--border);background:var(--bg);color:var(--text);">
    </div>
    <button type="submit" class="al-btn al-btn-cyan" style="width:100%;"
      onclick="return confirm('Commission Sell করার Request পাঠাবে?');"
      <?php echo $summary['available_to_sell'] <= 0 ? 'disabled' : ''; ?>>
      💰 Sell Request পাঠাও
    </button>
  </form>

  <div class="al-table-wrap" style="padding:16px;">
    <div class="row">Commission Rate: <b><?php echo MY_COMMISSION_RATE; ?>% of <?php echo $baseLabel; ?></b></div>
    <?php if ($MY_COMMISSION_TYPE === 'deposit'): ?>
    <div class="row">Downline-দের মোট Approved Deposit: <b class="mono">৳<?php echo number_format($summary['total_deposit'], 2); ?></b></div>
    <?php else: ?>
    <div class="row">মোট Bet (downline): <b class="mono">৳<?php echo number_format($summary['total_bet'], 2); ?></b></div>
    <div class="row">মোট Win (downline): <b class="mono">৳<?php echo number_format($summary['total_win'], 2); ?></b></div>
    <div class="row">GGR (Bet - Win): <b class="mono">৳<?php echo number_format($summary['base_amount'], 2); ?></b></div>
    <?php endif; ?>
    <div class="row">এ পর্যন্ত মোট আয় (<?php echo $baseLabel; ?> × Rate): <b class="mono">৳<?php echo number_format($summary['total_earned'], 2); ?></b></div>
    <div class="row">Pending/Approved Sell Request: <b class="mono">৳<?php echo number_format($summary['total_locked'], 2); ?></b></div>
    <div class="row">Downline সংখ্যা: <b><?php echo $summary['downline_count']; ?></b></div>
  </div>

  <div class="al-page-title" style="font-size:16px;margin-top:22px;">Sell Request History</div>
  <?php if (empty($history)): ?>
    <div class="al-table-wrap"><div class="al-empty"><div class="icon">📭</div><div class="msg">এখনো কোনো Sell Request পাঠানো হয়নি।</div></div></div>
  <?php else: ?>
    <?php foreach ($history as $h):
        $statusColor = $h['status'] === 'approved' ? '#1FB979' : ($h['status'] === 'rejected' ? '#E8544A' : '#F5C542');
        $statusLabel = $h['status'] === 'approved' ? 'Approved ✅' : ($h['status'] === 'rejected' ? 'Rejected ❌' : 'Pending ⏳');
    ?>
    <div class="al-card credit">
      <div class="row"><?php echo $baseLabel; ?>: <b class="mono">৳<?php echo number_format($h['ggr_amount'], 2); ?></b> · Rate: <b><?php echo $h['commission_rate']; ?>%</b></div>
      <div class="amt mono">৳<?php echo number_format($h['commission_amount'], 2); ?></div>
      <div class="row"><?php echo strtoupper($h['payment_method']); ?>: <b class="mono"><?php echo htmlspecialchars($h['payment_number']); ?></b></div>
      <div class="row">Status: <b style="color:<?php echo $statusColor; ?>;"><?php echo $statusLabel; ?></b></div>
      <div class="row" style="color:var(--text-faint);font-size:11.5px;"><?php echo htmlspecialchars($h['requested_at']); ?></div>
    </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>
</body>
</html>
