<?php
@session_start();
session_start();
error_reporting(0);
include('config.php');
require_once ('auth_guard.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Wallet Deposit History</title>

  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">

  <!-- DataTables -->
  <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.tailwindcss.min.css">

  <style>
    .badge{display:inline-block;padding:.35em .65em;font-size:.75em;font-weight:700;line-height:1;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25rem}
    .badge-success{color:#fff;background:#28a745}
    .badge-danger{color:#fff;background:#dc3545}
    .badge-primary{color:#fff;background:#007bff}
    .card{box-shadow:0 4px 6px -1px rgba(0,0,0,.1),0 2px 4px -1px rgba(0,0,0,.06);border-radius:.5rem}
    .btn{transition:all .3s ease}
    .btn:hover{transform:translateY(-1px);box-shadow:0 4px 6px rgba(0,0,0,.1)}
    @media (max-width:768px){
      .table-responsive{overflow-x:auto;-webkit-overflow-scrolling:touch}
      .dashboard-summery-one{flex-direction:column}
      .col-6{width:100%;margin-bottom:1rem}
    }
  </style>
</head>
<body class="bg-gray-100">
<?php include('header.php');?>

<div class="flex flex-col md:flex-row min-h-screen">
  <!-- Sidebar -->
  <?php include "side_bar.php";?>

  <main class="flex-1 p-4 md:p-6 md:ml-64">
    <div class="container mx-auto">
      <!-- Header -->
      <div class="flex flex-col md:flex-row justify-between items-center mb-6 gap-3">
        <h1 class="text-2xl font-bold text-gray-800">Wallet Deposit History</h1>
        <a href="dashboard.php" class="bg-[#FF6B00] hover:bg-[#E55F00] text-white font-medium py-2 px-6 rounded-full transition duration-300 shadow-md">
          <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
        </a>
      </div>

      <!-- Filters toolbar -->
      <div class="bg-white rounded-xl shadow-sm p-4 mb-4">
        <div class="flex flex-col md:flex-row gap-3 md:items-end md:justify-between">
          <div class="flex flex-wrap items-end gap-3">
            <div>
              <label for="fromDate" class="block text-sm font-medium text-gray-700 mb-1">From date</label>
              <input id="fromDate" type="date" class="border rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
            </div>
            <div>
              <label for="toDate" class="block text-sm font-medium text-gray-700 mb-1">To date</label>
              <input id="toDate" type="date" class="border rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
            </div>
            <button id="resetFilters" type="button"
              class="inline-flex items-center gap-2 bg-gray-100 hover:bg-gray-200 text-gray-800 px-4 py-2 rounded-md text-sm">
              <i class="fa-solid fa-arrow-rotate-left"></i> Reset
            </button>
          </div>

          <div class="relative w-full md:w-80">
            <label for="quickSearch" class="block text-sm font-medium text-gray-700 mb-1">Live search</label>
            <div class="relative">
              <input id="quickSearch" type="text" placeholder="Search email, amount, mode, date..."
                class="w-full border rounded-md pl-10 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" />
              <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
            </div>
          </div>
        </div>
      </div>

      <!-- Table -->
      <div class="bg-white rounded-xl shadow-md overflow-hidden">
        <div class="p-4 table-responsive">
          <table id="depositTable" class="w-full min-w-max">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Email</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Payment Mode</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Deposit Date</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Action</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <?php
              $status = "0";
              $sql = "SELECT * FROM wallet_deposit WHERE status='$status' ORDER BY deposted_date DESC";
              $query = $conn->prepare($sql);
              $query->execute();
              $results = $query->fetchAll(PDO::FETCH_OBJ);
              if ($query->rowCount() > 0) {
                foreach ($results as $result) { ?>
                  <tr class="hover:bg-gray-50">
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      <?= htmlentities($result->email); ?>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-green-600">
                      $<?= htmlentities($result->deposit_amount); ?>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      <?= htmlentities($result->deposit_type); ?>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      <?= htmlentities($result->deposted_date); ?>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                      <a href="view_wallet_deposit.php?id=<?= htmlentities($result->id); ?>&email=<?= htmlentities($result->email); ?>&deposit=<?= htmlentities($result->deposit_amount); ?>"
                         class="text-white bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-md text-sm transition duration-300">View</a>
                    </td>
                  </tr>
              <?php } } ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </main>
</div>

<?php include('footer.php');?>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- dayjs for robust date parsing -->
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/customParseFormat.js"></script>
<script>dayjs.extend(dayjs_plugin_customParseFormat);</script>

<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.tailwindcss.min.js"></script>

<script>
  // Try multiple common date formats (adjust if your DB format differs)
  const DATE_FORMATS = [
    'YYYY-MM-DD HH:mm:ss',
    'YYYY-MM-DD',
    'DD-MM-YYYY HH:mm:ss',
    'DD-MM-YYYY',
    'MM/DD/YYYY HH:mm:ss',
    'MM/DD/YYYY'
  ];

  function parseDepositDate(txt){
    if (!txt) return null;
    // Try as-is first
    let d = dayjs(txt);
    if (d.isValid()) return d;
    // Try known formats
    for (const f of DATE_FORMATS){
      d = dayjs(txt, f, true);
      if (d.isValid()) return d;
    }
    return null; // fallback: cannot parse
  }

  $(function(){
    const table = $('#depositTable').DataTable({
      responsive: true,
      dom: 'lrtip', // hide the built-in search box; we'll use our own
      order: [[3, 'desc']],
      language: {
        search: '_INPUT_',
        searchPlaceholder: 'Search records...',
        lengthMenu: 'Show _MENU_ entries',
        info: 'Showing _START_ to _END_ of _TOTAL_ entries',
        infoEmpty: 'Showing 0 to 0 of 0 entries',
        infoFiltered: '(filtered from _MAX_ total entries)',
        paginate: { first:'First', last:'Last', next:'Next', previous:'Previous' }
      }
    });

    // Custom date-range filter
    $.fn.dataTable.ext.search.push(function(settings, data) {
      if (settings.nTable !== document.getElementById('depositTable')) return true;

      const fromStr = $('#fromDate').val();
      const toStr   = $('#toDate').val();

      if (!fromStr && !toStr) return true; // no filter

      const cellText = data[3] || ''; // "Deposit Date" column text
      const rowDate  = parseDepositDate(cellText);
      if (!rowDate) return true;      // if can't parse, don't exclude

      const from = fromStr ? dayjs(fromStr, 'YYYY-MM-DD', true).startOf('day') : null;
      const to   = toStr   ? dayjs(toStr,   'YYYY-MM-DD', true).endOf('day')   : null;

      if (from && rowDate.isBefore(from)) return false;
      if (to   && rowDate.isAfter(to))   return false;

      return true;
    });

    // Live search
    $('#quickSearch').on('input', function(){
      table.search(this.value).draw();
    });

    // Date inputs trigger redraw
    $('#fromDate, #toDate').on('change', function(){
      table.draw();
    });

    // Reset
    $('#resetFilters').on('click', function(){
      $('#fromDate').val('');
      $('#toDate').val('');
      $('#quickSearch').val('');
      table.search('').draw();
    });
  });
</script>
</body>
</html>
