<?php
/**
 * agent_coin_report.php
 * Admin-only — সব Agent-এর সব Coin Movement-এর সম্পূর্ণ History
 * (agent_motta_log টেবিল থেকে) — কোন Agent কবে কাকে কত Coin
 * দিলো/কাটলো, সব একসাথে, Filter সহ।
 *
 * ✅ শুধু দেখার জন্য — কোনো Action/Edit এখানে নেই।
 */
session_start();
if (!isset($_SESSION['unohs'])) {
    header("location:index.php?msg=unauthorized");
    exit;
}
include("conn.php");

/* ══════════════════════════════════════════════════════════
   Filter — Agent এবং Date Range অনুযায়ী
   ══════════════════════════════════════════════════════════ */
$filterAgent = isset($_GET['agent_id']) ? trim($_GET['agent_id']) : '';
$filterFrom  = isset($_GET['from_date']) ? trim($_GET['from_date']) : '';
$filterTo    = isset($_GET['to_date']) ? trim($_GET['to_date']) : '';

$where = "1=1";
if ($filterAgent !== '') {
    $where .= " AND l.agent_userid = '" . mysqli_real_escape_string($conn, $filterAgent) . "'";
}
if ($filterFrom !== '') {
    $where .= " AND DATE(l.created_at) >= '" . mysqli_real_escape_string($conn, $filterFrom) . "'";
}
if ($filterTo !== '') {
    $where .= " AND DATE(l.created_at) <= '" . mysqli_real_escape_string($conn, $filterTo) . "'";
}

/* ══════════════════════════════════════════════════════════
   Agent Dropdown-এর জন্য সব Agent-এর তালিকা
   ══════════════════════════════════════════════════════════ */
$agentList = [];
$agentRes = mysqli_query($conn, "
    SELECT a.userid, s.mobile
    FROM tb_agent a
    LEFT JOIN shonu_subjects s ON s.id = a.userid
    ORDER BY a.userid DESC
");
while ($row = mysqli_fetch_assoc($agentRes)) { $agentList[] = $row; }

/* ══════════════════════════════════════════════════════════
   মূল Report Query — Agent Mobile + User Mobile জোড়া লাগিয়ে
   ══════════════════════════════════════════════════════════ */
$logs = [];
$result = mysqli_query($conn, "
    SELECT l.id, l.agent_userid, l.to_user, l.amount, l.type, l.remark, l.created_at,
           ag.mobile AS agent_mobile,
           us.mobile AS user_mobile
    FROM agent_motta_log l
    LEFT JOIN shonu_subjects ag ON ag.id = l.agent_userid
    LEFT JOIN shonu_subjects us ON us.id = l.to_user
    WHERE $where
    ORDER BY l.created_at DESC
    LIMIT 5000
");
while ($row = mysqli_fetch_assoc($result)) { $logs[] = $row; }

/* ══════════════════════════════════════════════════════════
   উপরের Summary Card-এর জন্য — মোট কত Coin দেওয়া/কাটা হয়েছে
   ══════════════════════════════════════════════════════════ */
$totalGiven = 0; $totalDeducted = 0; $totalAdminTopup = 0;
foreach ($logs as $l) {
    $amt = floatval($l['amount']);
    if (in_array($l['type'], ['give', 'deposit_deduct'])) {
        $totalGiven += $amt;
    } elseif ($l['type'] === 'admin_coin_add') {
        $totalAdminTopup += $amt;
    }
}

// Type-কে সহজ বাংলা লেবেলে দেখানো
function typeLabel($type) {
    switch ($type) {
        case 'deposit_deduct': return ['User Deposit Approve → Agent Coin কাটলো', '#E8544A'];
        case 'deposit_blocked': return ['Deposit Blocked (Agent Balance কম ছিলো)', '#9691B8'];
        case 'admin_coin_add': return ['Admin → Agent-কে Coin দিলো', '#1FB979'];
        case 'give': return ['Agent → User-কে Coin দিলো', '#22D3EE'];
        default: return [$type, '#F5C542'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin - Agent Coin Report</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');
.rp-card { background:#1B1633; border:1px solid #322A5C; border-radius:14px; padding:20px; margin-bottom:20px; font-family:'Inter',sans-serif; }
.rp-summary { display:flex; gap:16px; flex-wrap:wrap; margin-bottom:20px; }
.rp-stat { background:#1B1633; border:1px solid #322A5C; border-radius:12px; padding:16px 20px; flex:1; min-width:180px; }
.rp-stat .lab { color:#9691B8; font-size:11px; text-transform:uppercase; letter-spacing:.5px; }
.rp-stat .val { color:#F5C542; font-size:20px; font-weight:800; font-family:'IBM Plex Mono',monospace; margin-top:4px; }
.rp-card .form-group label { color:#9691B8; font-size:11px; text-transform:uppercase; letter-spacing:.5px; font-weight:600; }
.rp-card .form-control, .rp-card select { background:#0E0B1A; border:1.5px solid #322A5C; color:#F3F0FF; border-radius:10px; }
.rp-card .btn-filter { background:#7C3AED; border:none; font-weight:700; color:#fff; border-radius:10px; }
table.dataTable { color:#F3F0FF; font-family:'Inter',sans-serif; font-size:13px; }
table.dataTable thead th { background:#0E0B1A; color:#9691B8; font-size:10.5px; text-transform:uppercase; border-color:#322A5C; }
table.dataTable tbody td { border-color:#322A5C; vertical-align:middle; }
.rp-mono { font-family:'IBM Plex Mono',monospace; }
.rp-amt { font-weight:700; color:#F5C542; }
.rp-badge { font-size:11px; font-weight:700; padding:3px 10px; border-radius:20px; display:inline-block; }
.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 Coin — সম্পূর্ণ Report</h4>

        <div class="rp-summary">
          <div class="rp-stat">
            <div class="lab">মোট Agent → User Coin দিয়েছে</div>
            <div class="val">৳<?= number_format($totalGiven, 2) ?></div>
          </div>
          <div class="rp-stat">
            <div class="lab">মোট Admin → Agent Coin দিয়েছে</div>
            <div class="val">৳<?= number_format($totalAdminTopup, 2) ?></div>
          </div>
          <div class="rp-stat">
            <div class="lab">মোট Entry সংখ্যা</div>
            <div class="val"><?= count($logs) ?></div>
          </div>
        </div>

        <div class="rp-card">
          <form method="GET" class="row" style="align-items:end;">
            <div class="col-md-4">
              <div class="form-group">
                <label>Agent বেছে নাও</label>
                <select name="agent_id" class="form-control">
                  <option value="">সব Agent</option>
                  <?php foreach ($agentList as $a): ?>
                  <option value="<?= htmlspecialchars($a['userid']) ?>" <?= $filterAgent == $a['userid'] ? 'selected' : '' ?>>
                    #<?= htmlspecialchars($a['userid']) ?> — <?= htmlspecialchars($a['mobile'] ?: 'N/A') ?>
                  </option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label>শুরুর তারিখ</label>
                <input type="date" name="from_date" class="form-control" value="<?= htmlspecialchars($filterFrom) ?>">
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label>শেষ তারিখ</label>
                <input type="date" name="to_date" class="form-control" value="<?= htmlspecialchars($filterTo) ?>">
              </div>
            </div>
            <div class="col-md-2">
              <button type="submit" class="btn btn-filter w-100">🔍 Filter করো</button>
            </div>
          </form>
        </div>

        <div class="rp-card">
          <div class="table-responsive">
            <table id="coinReportTable" class="table table-bordered table-hover" style="width:100%">
              <thead>
                <tr>
                  <th>Date/Time</th>
                  <th>Agent ID</th>
                  <th>Agent Mobile</th>
                  <th>User ID</th>
                  <th>User Mobile</th>
                  <th>Amount</th>
                  <th>Type</th>
                  <th>Remark</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($logs as $l): [$label, $color] = typeLabel($l['type']); ?>
                <tr>
                  <td class="rp-mono"><?= htmlspecialchars($l['created_at']) ?></td>
                  <td>#<?= htmlspecialchars($l['agent_userid']) ?></td>
                  <td class="rp-mono"><?= htmlspecialchars($l['agent_mobile'] ?: 'N/A') ?></td>
                  <td>#<?= htmlspecialchars($l['to_user']) ?></td>
                  <td class="rp-mono"><?= htmlspecialchars($l['user_mobile'] ?: ($l['to_user'] === 'admin_topup' ? '(Admin)' : 'N/A')) ?></td>
                  <td class="rp-amt">৳<?= number_format($l['amount'], 2) ?></td>
                  <td><span class="rp-badge" style="background:<?= $color ?>22;color:<?= $color ?>;"><?= htmlspecialchars($label) ?></span></td>
                  <td style="font-size:12px;color:#9691B8;"><?= htmlspecialchars($l['remark'] ?: '') ?></td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>

      </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_coin_report.js"></script>
</body>
</html>
