<?php
/**
 * commission_sell_requests.php
 * Admin এখান থেকে Agent-দের Commission Sell Request Approve/Reject করবে।
 * Approve করলে বোঝায় Admin নিজে bKash/Nagad-এ ম্যানুয়ালি টাকা পাঠিয়েছে —
 * এই ফাইল শুধু Request-এর Status আপডেট করে, কোনো Automatic Payment করে না।
 */
session_start();
if (!isset($_SESSION['unohs'])) {
    header("location:index.php?msg=unauthorized");
    exit;
}
include("conn.php");

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['request_id'])) {
    $requestId = (int)$_POST['request_id'];
    $action = $_POST['action'];

    $reqRow = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT * FROM commission_sell_requests WHERE id = '".$requestId."'"
    ));

    if (!$reqRow) {
        $message = 'Request পাওয়া যায়নি।';
        $message_type = 'danger';
    } elseif ($reqRow['status'] !== 'pending') {
        $message = 'এই Request আগেই process হয়ে গেছে।';
        $message_type = 'danger';
    } elseif ($action === 'approve') {
        mysqli_query($conn, "UPDATE commission_sell_requests SET status = 'approved', processed_at = NOW() WHERE id = '".$requestId."'");
        $message = "✅ Request #$requestId Approve করা হয়েছে — এখন Agent-এর {$reqRow['payment_method']} নম্বরে (".$reqRow['payment_number'].") ৳".number_format($reqRow['commission_amount'],2)." পাঠিয়ে দাও।";
        $message_type = 'success';
    } elseif ($action === 'reject') {
        mysqli_query($conn, "UPDATE commission_sell_requests SET status = 'rejected', processed_at = NOW() WHERE id = '".$requestId."'");
        $message = "Request #$requestId Reject করা হয়েছে — এই Amount আবার Agent-এর জন্য Available হয়ে যাবে।";
        $message_type = 'success';
    }
}

$pending = [];
$result = mysqli_query($conn, "
    SELECT r.*, s.mobile
    FROM commission_sell_requests r
    LEFT JOIN shonu_subjects s ON s.id = r.agent_userid
    WHERE r.status = 'pending'
    ORDER BY r.requested_at ASC
");
while ($row = mysqli_fetch_assoc($result)) { $pending[] = $row; }

$recent = [];
$result2 = mysqli_query($conn, "
    SELECT r.*, s.mobile
    FROM commission_sell_requests r
    LEFT JOIN shonu_subjects s ON s.id = r.agent_userid
    WHERE r.status != 'pending'
    ORDER BY r.processed_at DESC
    LIMIT 30
");
while ($row = mysqli_fetch_assoc($result2)) { $recent[] = $row; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin - Commission Sell Requests</title>
<link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
<link rel="stylesheet" href="vendors/base/vendor.bundle.base.css">
<link rel="stylesheet" href="css/style.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@500;600;700&display=swap');
.cs-card { background:#1B1633; border:1px solid #322A5C; border-radius:14px; padding:20px; margin-bottom:16px; font-family:'Inter',sans-serif; }
.cs-amt { font-family:'IBM Plex Mono',monospace; font-size:20px; font-weight:700; color:#F5C542; }
.cs-meta { color:#9691B8; font-size:12.5px; margin:4px 0; }
.cs-num { font-family:'IBM Plex Mono',monospace; color:#22D3EE; font-weight:700; }
.cs-btn { padding:8px 18px; border-radius:8px; border:none; font-weight:700; font-size:12.5px; margin-right:8px; cursor:pointer; }
.cs-btn-approve { background:#1FB979; color:#032B1B; }
.cs-btn-reject { background:#E8544A; color:#2B0505; }
.cs-badge { font-size:11px; font-weight:700; padding:3px 10px; border-radius:20px; }
.cs-badge-approved { background:rgba(31,185,121,.15); color:#1FB979; }
.cs-badge-rejected { background:rgba(232,84,74,.15); color:#E8544A; }
</style>
</head>
<body>
<div class="container-scroller">
  <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
    <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
      <a class="navbar-brand brand-logo" href="dashboard.php"><img src="images/logo.png" alt="logo"/></a>
    </div>
    <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end">
      <ul class="navbar-nav navbar-nav-right">
        <li class="nav-item dropdown d-flex mr-4"><a class="nav-link" href="logout.php"><i class="icon-power"></i> Logout</a></li>
      </ul>
    </div>
  </nav>
  <div class="container-fluid page-body-wrapper">
    <nav class="sidebar sidebar-offcanvas" id="sidebar">
      <?php include 'compass.php'; ?>
    </nav>
    <div class="main-panel">
      <div class="content-wrapper">
        <h4 class="font-weight-bold text-dark mb-4">💰 Agent Commission Sell Requests</h4>

        <?php if ($message): ?>
        <div class="alert alert-<?= $message_type ?> alert-dismissible fade show">
          <?= htmlspecialchars($message) ?>
          <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
        </div>
        <?php endif; ?>

        <h5 style="color:#F5EFDC;margin-bottom:14px;">⏳ Pending Requests (<?= count($pending) ?>)</h5>
        <?php if (empty($pending)): ?>
          <p class="text-muted">এখন কোনো Pending Request নেই।</p>
        <?php else: ?>
          <?php foreach ($pending as $r): ?>
          <div class="cs-card">
            <div class="cs-amt">৳<?= number_format($r['commission_amount'], 2) ?></div>
            <div class="cs-meta">Agent ID: <b><?= htmlspecialchars($r['agent_userid']) ?></b> &nbsp;|&nbsp; Mobile: <?= htmlspecialchars($r['mobile'] ?? 'N/A') ?></div>
            <div class="cs-meta"><?= ($r['commission_type'] ?? 'ggr') === 'deposit' ? 'মোট Deposit' : 'GGR' ?>: ৳<?= number_format($r['ggr_amount'], 2) ?> · Rate: <?= $r['commission_rate'] ?>% · Type: <b><?= ($r['commission_type'] ?? 'ggr') === 'deposit' ? 'Deposit Commission' : 'GGR Commission' ?></b></div>
            <div class="cs-meta"><?= strtoupper($r['payment_method']) ?> Number: <span class="cs-num"><?= htmlspecialchars($r['payment_number']) ?></span></div>
            <div class="cs-meta">Requested: <?= htmlspecialchars($r['requested_at']) ?></div>
            <div style="margin-top:12px;">
              <form method="POST" style="display:inline;" onsubmit="return confirm('৳<?= number_format($r['commission_amount'],2) ?> Approve করছো? এর মানে তুমি নিজে <?= strtoupper($r['payment_method']) ?>-এ (<?= htmlspecialchars($r['payment_number']) ?>) টাকা পাঠিয়ে দিয়েছো।');">
                <input type="hidden" name="request_id" value="<?= $r['id'] ?>">
                <button type="submit" name="action" value="approve" class="cs-btn cs-btn-approve">✓ Approve (টাকা পাঠিয়েছি)</button>
              </form>
              <form method="POST" style="display:inline;" onsubmit="return confirm('এই Request Reject করছো?');">
                <input type="hidden" name="request_id" value="<?= $r['id'] ?>">
                <button type="submit" name="action" value="reject" class="cs-btn cs-btn-reject">✕ Reject</button>
              </form>
            </div>
          </div>
          <?php endforeach; ?>
        <?php endif; ?>

        <h5 style="color:#F5EFDC;margin:24px 0 14px;">📋 সাম্প্রতিক History</h5>
        <?php if (empty($recent)): ?>
          <p class="text-muted">এখনো কোনো History নেই।</p>
        <?php else: ?>
          <div class="table-responsive">
            <table class="table table-bordered table-hover" style="background:#1B1633;color:#F3F0FF;">
              <thead><tr><th>Agent ID</th><th>Mobile</th><th>Amount</th><th><?= '' ?>Payment Number</th><th>Status</th><th>Date</th></tr></thead>
              <tbody>
                <?php foreach ($recent as $r): ?>
                <tr>
                  <td>#<?= htmlspecialchars($r['agent_userid']) ?></td>
                  <td><?= htmlspecialchars($r['mobile'] ?? 'N/A') ?></td>
                  <td>৳<?= number_format($r['commission_amount'], 2) ?></td>
                  <td><?= strtoupper($r['payment_method']) ?>: <?= htmlspecialchars($r['payment_number']) ?></td>
                  <td>
                    <?php if ($r['status'] === 'approved'): ?>
                      <span class="cs-badge cs-badge-approved">Approved</span>
                    <?php else: ?>
                      <span class="cs-badge cs-badge-rejected">Rejected</span>
                    <?php endif; ?>
                  </td>
                  <td><?= htmlspecialchars($r['processed_at']) ?></td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>

      </div>
    </div>
  </div>
</div>
<script src="vendors/base/vendor.bundle.base.js"></script>
</body>
</html>
