<?php
/**
 * agent_full_ledger.php
 * Admin-only — প্রতিটা Agent-এর জন্য এক জায়গায় সম্পূর্ণ হিসাব:
 *   - Admin কত Coin দিলো (admin_coin_add)
 *   - Deposit Approve-এ Agent-এর কত Coin কাটলো (deposit_deduct)
 *   - Agent User-দের কত Coin দিলো (give)
 *   - Commission কত Sell হয়ে গেছে (Approved) আর কত Pending
 *   - এখন Agent-এর হাতে কত Balance আছে (বর্তমান)
 *
 * ✅ শুধু দেখার জন্য — কোনো Action এখানে নেই।
 */
session_start();
if (!isset($_SESSION['unohs'])) {
    header("location:index.php?msg=unauthorized");
    exit;
}
include("conn.php");

/* ══════════════════════════════════════════════════════════
   প্রতিটা Agent-এর জন্য এক-এক করে হিসাব বের করা
   ══════════════════════════════════════════════════════════ */
$agents = [];
$agentRes = mysqli_query($conn, "
    SELECT a.userid, s.mobile, s.owncode,
           COALESCE(CAST(k.motta AS DECIMAL(15,2)), 0) AS current_balance
    FROM tb_agent a
    LEFT JOIN shonu_subjects s ON s.id = a.userid
    LEFT JOIN shonu_kaichila k ON k.balakedara = a.userid
    ORDER BY a.userid DESC
");
while ($row = mysqli_fetch_assoc($agentRes)) { $agents[] = $row; }

foreach ($agents as &$ag) {
    $uid = $ag['userid'];

    // Admin → Agent (কত Coin দেওয়া হয়েছে)
    $r1 = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT COALESCE(SUM(amount),0) as total FROM agent_motta_log WHERE agent_userid='$uid' AND type='admin_coin_add'"
    ));
    $ag['admin_gave'] = floatval($r1['total']);

    // Deposit Approve-এ Agent-এর Coin কাটা (Agent → User এর মাধ্যমে চলে যাওয়া)
    $r2 = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT COALESCE(SUM(amount),0) as total FROM agent_motta_log WHERE agent_userid='$uid' AND type='deposit_deduct'"
    ));
    $ag['deposit_deducted'] = floatval($r2['total']);

    // Agent সরাসরি User-কে Coin দিলো (Give Coin ফিচার দিয়ে)
    $r3 = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT COALESCE(SUM(amount),0) as total FROM agent_motta_log WHERE agent_userid='$uid' AND type='give'"
    ));
    $ag['given_to_users'] = floatval($r3['total']);

    // Commission Sell — Approved (সত্যিই টাকা পেয়ে গেছে)
    $r4 = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT COALESCE(SUM(commission_amount),0) as total FROM commission_sell_requests WHERE agent_userid='$uid' AND status='approved'"
    ));
    $ag['commission_sold'] = floatval($r4['total']);

    // Commission Sell — Pending (এখনো Admin Approve করেনি)
    $r5 = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT COALESCE(SUM(commission_amount),0) as total FROM commission_sell_requests WHERE agent_userid='$uid' AND status='pending'"
    ));
    $ag['commission_pending'] = floatval($r5['total']);
}
unset($ag);

/* ══════════════════════════════════════════════════════════
   সামগ্রিক Summary (সব Agent মিলিয়ে)
   ══════════════════════════════════════════════════════════ */
$grandAdminGave = array_sum(array_column($agents, 'admin_gave'));
$grandCommissionSold = array_sum(array_column($agents, 'commission_sold'));
$grandCommissionPending = array_sum(array_column($agents, 'commission_pending'));
$grandCurrentBalance = array_sum(array_column($agents, 'current_balance'));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin - Agent Full Ledger</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">
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.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');
.lg-card { background:#1B1633; border:1px solid #322A5C; border-radius:14px; padding:20px; margin-bottom:20px; font-family:'Inter',sans-serif; }
.lg-summary { display:flex; gap:16px; flex-wrap:wrap; margin-bottom:20px; }
.lg-stat { background:#1B1633; border:1px solid #322A5C; border-radius:12px; padding:16px 20px; flex:1; min-width:170px; }
.lg-stat .lab { color:#9691B8; font-size:10.5px; text-transform:uppercase; letter-spacing:.5px; }
.lg-stat .val { font-size:19px; font-weight:800; font-family:'IBM Plex Mono',monospace; margin-top:4px; }
.c-green { color:#1FB979; } .c-gold { color:#F5C542; } .c-cyan { color:#22D3EE; } .c-amber { color:#F0A93A; }
table.dataTable { color:#F3F0FF; font-family:'Inter',sans-serif; font-size:12.5px; }
table.dataTable thead th { background:#0E0B1A; color:#9691B8; font-size:10px; text-transform:uppercase; border-color:#322A5C; white-space:nowrap; }
table.dataTable tbody td { border-color:#322A5C; vertical-align:middle; }
.lg-mono { font-family:'IBM Plex Mono',monospace; }
.dataTables_wrapper .dataTables_filter input,
.dataTables_wrapper .dataTables_length select { background:#0E0B1A; border:1px solid #322A5C; color:#F3F0FF; border-radius:6px; }
.dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_paginate { color:#9691B8; }
</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 Full Ledger — সম্পূর্ণ হিসাব</h4>

        <div class="lg-summary">
          <div class="lg-stat">
            <div class="lab">মোট Admin → Agent দিয়েছে</div>
            <div class="val c-green">৳<?= number_format($grandAdminGave, 2) ?></div>
          </div>
          <div class="lg-stat">
            <div class="lab">মোট Commission Sold (Approved)</div>
            <div class="val c-gold">৳<?= number_format($grandCommissionSold, 2) ?></div>
          </div>
          <div class="lg-stat">
            <div class="lab">Commission Pending (Approve বাকি)</div>
            <div class="val c-amber">৳<?= number_format($grandCommissionPending, 2) ?></div>
          </div>
          <div class="lg-stat">
            <div class="lab">সব Agent-এর মোট বর্তমান Balance</div>
            <div class="val c-cyan">৳<?= number_format($grandCurrentBalance, 2) ?></div>
          </div>
        </div>

        <div class="lg-card">
          <div class="table-responsive">
            <table id="ledgerTable" class="table table-bordered table-hover" style="width:100%">
              <thead>
                <tr>
                  <th>Agent ID</th>
                  <th>Mobile</th>
                  <th>Admin দিলো</th>
                  <th>Deposit-এ কাটলো</th>
                  <th>User-কে দিলো</th>
                  <th>Commission Sold</th>
                  <th>Commission Pending</th>
                  <th>বর্তমান Balance</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($agents as $ag): ?>
                <tr>
                  <td>#<?= htmlspecialchars($ag['userid']) ?></td>
                  <td class="lg-mono"><?= htmlspecialchars($ag['mobile'] ?: 'N/A') ?></td>
                  <td class="lg-mono c-green">৳<?= number_format($ag['admin_gave'], 2) ?></td>
                  <td class="lg-mono">৳<?= number_format($ag['deposit_deducted'], 2) ?></td>
                  <td class="lg-mono">৳<?= number_format($ag['given_to_users'], 2) ?></td>
                  <td class="lg-mono c-gold">৳<?= number_format($ag['commission_sold'], 2) ?></td>
                  <td class="lg-mono c-amber">৳<?= number_format($ag['commission_pending'], 2) ?></td>
                  <td class="lg-mono c-cyan"><b>৳<?= number_format($ag['current_balance'], 2) ?></b></td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>

        <p class="text-muted" style="font-size:12px;">
          বিস্তারিত প্রতিটা Transaction দেখতে <a href="agent_coin_report.php">Agent Coin Report (A to Z)</a> এবং
          Commission Sell-এর Request Approve/Reject করতে <a href="commission_sell_requests.php">Commission Sell Requests</a> পেজ দেখুন।
        </p>

      </div>
    </div>
  </div>
</div>
<script src="vendors/base/vendor.bundle.base.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<script src="agent_full_ledger.js"></script>
</body>
</html>
