<?php
// bonus_list.php — Approved Bonus (deposit_amount) listing

/* Debug (disable in prod) */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/session_boot.php';   // starts session, handles idle expiry
require_once __DIR__ . '/config.php';         // must define $conn (PDO)
if (!isset($conn) || !($conn instanceof PDO)) {
  die('Database connection not established. Check config.php (PDO).');
}

// Back-compat: some apps used 'alogin'. Bridge to 'clogin' if needed.
if (empty($_SESSION['clogin']) && !empty($_SESSION['alogin'])) {
  $_SESSION['clogin'] = $_SESSION['alogin'];
}

require_once __DIR__ . '/auth_guard.php';     // ensures $_SESSION['clogin']; sets $me, etc.

// ---------- CSRF ----------
if (empty($_SESSION['csrf_bonus'])) {
  $_SESSION['csrf_bonus'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_bonus'];

// ---------- Actions: soft delete (mark status=deleted) ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_bonus') {
  $posted_csrf = $_POST['csrf'] ?? '';
  if (!hash_equals($_SESSION['csrf_bonus'] ?? '', $posted_csrf)) {
    http_response_code(403);
    die('Invalid CSRF token.');
  }
  $rowId = (int)($_POST['id'] ?? 0);
  if ($rowId > 0) {
    // Only delete rows that are currently approved+bonus to avoid accidents
    $sql = "UPDATE total_balance 
            SET status = 'deleted'
            WHERE id = :id AND LOWER(status) = 'approved' AND LOWER(deposit_type) = 'bonus'";
    $st = $conn->prepare($sql);
    $st->execute([':id' => $rowId]);
  }
  header("Location: " . strtok($_SERVER['REQUEST_URI'], '?'));
  exit;
}

// ---------- Data: Approved Bonus (deposit_amount), join equity if available ----------
/*
  total_balance schema (MyISAM):
  - deposit_amount (varchar) — treat as numeric for display
  - trade_id (varchar) — we’ll join to liveaccount.trade_id to fetch equity (if table exists)
*/
$rows = [];
try {
  // Try join to liveaccount for equity; if table missing, query will fail—catch below and fallback
  $sql = "
    SELECT 
      tb.id,
      tb.trade_id,
      tb.email,
      tb.deposit_amount,
      tb.reg_date,
      tb.status,
      tb.deposit_type,
      la.equity AS equity
    FROM total_balance tb
    LEFT JOIN liveaccount la ON la.trade_id = tb.trade_id
    WHERE LOWER(tb.deposit_type) = 'bonus'
      AND LOWER(tb.status) = 'approved'
    ORDER BY tb.id DESC
  ";
  $st = $conn->query($sql);
  $rows = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
  // Fallback without JOIN if liveaccount table is not present
  $sql2 = "
    SELECT 
      tb.id,
      tb.trade_id,
      tb.email,
      tb.deposit_amount,
      tb.reg_date,
      tb.status,
      tb.deposit_type
    FROM total_balance tb
    WHERE LOWER(tb.deposit_type) = 'bonus'
      AND LOWER(tb.status) = 'approved'
    ORDER BY tb.id DESC
  ";
  $st2 = $conn->query($sql2);
  $tmp  = $st2->fetchAll(PDO::FETCH_ASSOC);
  foreach ($tmp as $r) {
    $r['equity'] = null;
    $rows[] = $r;
  }
}

// Helper: money formatting
function money_usd($val) {
  // deposit_amount is varchar; coerce to float safely
  $num = is_numeric($val) ? (float)$val : 0.0;
  return '$' . number_format($num, 2);
}

// Helper: escape
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Bonus List</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    :root{
      --brand: #CD7F32;  /* Bronze/Orange */
      --brand-600: #b86f2b;
      --brand-700: #9f5f24;
      --paper: #ffffff;
      --bg: #f8fafc;
      --ink: #111827;
    }
    .brand-btn{
      background: var(--brand);
      color: #fff;
    }
    .brand-btn:hover{
      background: var(--brand-700);
    }
    .brand-head{
      background: var(--brand);
      color:#fff;
    }
    .brand-soft{
      background: #F8E6D1;
    }
  </style>
</head>

<body class="bg-gray-50">
  <?php include "header.php"; ?>
  <div class="flex flex-col md:flex-row min-h-screen">
    <?php include "side_bar.php"; ?>

    <main class="flex-1 p-4 md:p-6 md:ml-64">
      <div class="container mx-auto space-y-4 md:space-y-6">
        <!-- Page Title -->
        <div class="flex items-center justify-between">
          <h2 class="text-2xl md:text-3xl font-semibold text-[var(--brand)]">Bonus List</h2>
          <!-- Simple legend -->
          <div class="hidden md:flex items-center gap-3 text-sm">
            <span class="inline-flex items-center gap-2">
              <span class="w-3 h-3 rounded-sm" style="background:#fff;border:1px solid #e5e7eb;"></span>
              Table
            </span>
            <span class="inline-flex items-center gap-2">
              <span class="w-3 h-3 rounded-sm brand-soft"></span>
              Hover
            </span>
          </div>
        </div>

        <!-- Card -->
        <div class="bg-white rounded-lg shadow-md overflow-hidden">
          <!-- Head -->
          <div class="brand-head px-4 md:px-6 py-3 flex items-center justify-between">
            <div class="font-medium text-sm md:text-base uppercase tracking-wide">
              Approved Bonus Payouts (deposit_amount)
            </div>
            <div class="text-xs opacity-90">
              <?= date('Y-m-d H:i'); ?>
            </div>
          </div>

          <!-- Table -->
          <div class="overflow-x-auto">
            <table class="w-full border-collapse min-w-[780px]">
              <thead>
                <tr class="bg-[var(--brand)] text-white uppercase text-xs md:text-sm">
                  <th class="py-2 md:py-3 px-4 md:px-6 text-left">ID</th>
                  <th class="py-2 md:py-3 px-4 md:px-6 text-left">MT5 ID</th>
                  <th class="py-2 md:py-3 px-4 md:px-6 text-left">Amount ($)</th>
                  
                  <th class="py-2 md:py-3 px-4 md:px-6 text-left">Type</th>
                  
                  <th class="py-2 md:py-3 px-4 md:px-6 text-left">Date</th>
                  <!--<th class="py-2 md:py-3 px-4 md:px-6 text-center">Actions</th>-->
                </tr>
              </thead>
              <tbody class="text-gray-700 text-xs md:text-sm">
                <?php if (empty($rows)): ?>
                  <tr>
                    <td colspan="8" class="px-4 md:px-6 py-6 text-center text-gray-500">
                      No approved bonus records found.
                    </td>
                  </tr>
                <?php else: ?>
                  <?php foreach ($rows as $r): ?>
                    <?php
                      $id        = (int)$r['id'];
                      $mt5       = $r['trade_id'] ?? '';
                      $amount    = money_usd($r['deposit_amount'] ?? '0');
                      $equity    = isset($r['equity']) && $r['equity'] !== null && $r['equity'] !== '' 
                                   ? money_usd($r['equity']) 
                                   : '—';
                      $dtype     = $r['deposit_type'] ?? 'bonus';
                      $comment   = 'Bonus'; // You can replace with a real comment field if you have one
                      $date      = $r['reg_date'] ?? '';
                    ?>
                    <tr class="border-b border-gray-200 hover:brand-soft transition">
                      <td class="py-2 px-4 md:px-6"><?= $id ?></td>
                      <td class="py-2 px-4 md:px-6"><?= h($mt5) ?></td>
                      <td class="py-2 px-4 md:px-6"><?= $amount ?></td>
                     
                      <td class="py-2 px-4 md:px-6"><?= h(ucfirst(strtolower($dtype))) ?></td>
                      
                      <td class="py-2 px-4 md:px-6"><?= h($date) ?></td>
                      <!--<td class="py-2 px-4 md:px-6 text-center">-->
                      <!--  <form method="post" class="inline" onsubmit="return confirm('Delete this bonus row?');">-->
                      <!--    <input type="hidden" name="csrf" value="<?= h($csrf) ?>">-->
                      <!--    <input type="hidden" name="action" value="delete_bonus">-->
                      <!--    <input type="hidden" name="id" value="<?= $id ?>">-->
                      <!--    <button type="submit" class="px-2 py-1 md:px-3 md:py-1 rounded-md bg-red-500 text-white hover:bg-red-700">-->
                      <!--      Delete-->
                      <!--    </button>-->
                      <!--  </form>-->
                      <!--</td>-->
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

          <!-- Footer strip -->
          <div class="px-4 md:px-6 py-3 bg-gray-50 border-t border-gray-100 flex items-center justify-between">
            <div class="text-xs text-gray-500">Showing <?= count($rows) ?> record(s)</div>
            <a href="#top" class="text-xs text-[var(--brand)] hover:underline">Back to top</a>
          </div>
        </div>
      </div>
    </main>
  </div>
  <?php include "footer.php"; ?>
</body>
</html>
