<?php
// ============================================================
//  MediCore — Recycle Bin
//  File: recycle/index.php
// ============================================================
$page  = 'recycle/index';
$title = 'Recycle Bin';
require_once '../includes/header.php';
$isSuperAdmin = ($_SESSION['user_role'] ?? '') === 'super_admin';
?>

<div class="page-header">
  <div class="ct" style="font-size:16px">🗑 Recycle Bin</div>
  <div style="display:flex;gap:8px;align-items:center">
    <input id="rb-search" placeholder="🔍 Search deleted records…"
           oninput="clearTimeout(_rbTimer);_rbTimer=setTimeout(()=>loadBin(),300)"
           style="padding:5px 10px;border:1px solid var(--border);
                  border-radius:var(--rsm);font-size:13px;
                  background:var(--surface);color:var(--text);width:220px">
    <select id="rb-module" onchange="loadBin()"
            style="padding:5px 10px;border:1px solid var(--border);
                   border-radius:var(--rsm);font-size:13px;
                   background:var(--surface);color:var(--text)">
      <option value="all">All Modules</option>
      <option value="products">Products</option>
      <option value="customers">Customers</option>
      <option value="suppliers">Suppliers</option>
      <option value="sales">Sales</option>
      <option value="purchases">Purchases</option>
      <option value="sale_returns">Sale Returns</option>
      <option value="purchase_returns">Purchase Returns</option>
    </select>
    <button class="btn btn-sm" onclick="loadBin()" style="flex-shrink:0">↺ Refresh</button>
  </div>
</div>

<div class="content">

  <!-- Info banner -->
  <div class="al al-i" style="margin-bottom:12px">
    ℹ Deleted records are kept here and never permanently removed until a
    <strong>Super Admin</strong> explicitly purges them. Click
    <strong>Restore</strong> to bring any record back with all its data intact.
    <?php if ($isSuperAdmin): ?>
    <span style="color:var(--danger);font-weight:700">
      · You are a Super Admin — permanent delete is available.
    </span>
    <?php endif; ?>
  </div>

  <!-- Summary stats row -->
  <div id="rb-stats" class="sgrid s4" style="margin-bottom:12px"></div>

  <!-- Table -->
  <div class="card" style="padding:0">
    <div id="rb-body">
      <div style="text-align:center;padding:40px;color:var(--text3)">
        Loading…
      </div>
    </div>
  </div>

</div><!-- /content -->

<script>
const API         = '../api/recycle.php';
const IS_SUPER    = <?= $isSuperAdmin ? 'true' : 'false' ?>;
let _rbTimer      = null;

const MODULE_ICONS = {
  products: '💊', customers: '👤', suppliers: '🏭',
  sales: '🧾', purchases: '📦', sale_returns: '↩', purchase_returns: '↩',
};
const MODULE_COLORS = {
  products: 'var(--accent)', customers: 'var(--brand)', suppliers: 'var(--teal)',
  sales: 'var(--warn)', purchases: 'var(--purple)', sale_returns: 'var(--danger)',
  purchase_returns: 'var(--danger)',
};

async function loadBin() {
  const q   = document.getElementById('rb-search').value;
  const mod = document.getElementById('rb-module').value;
  document.getElementById('rb-body').innerHTML =
    '<div style="text-align:center;padding:30px;color:var(--text3)">Loading…</div>';

  const r = await apiPost(API, { action: 'list', module: mod, q });
  if (!r.success) {
    document.getElementById('rb-body').innerHTML =
      `<div style="text-align:center;padding:30px;color:var(--danger)">${esc(r.error)}</div>`;
    return;
  }

  updateStats(r.data);
  renderTable(r.data);
  renderFailedBanner(r.failed || []);
}

// A module's query can fail independently (e.g. a table with a schema
// issue) without aborting the whole list — but that means its deleted
// records simply won't appear. Surface which module(s) failed instead
// of letting that look like "there's nothing here."
function renderFailedBanner(failed) {
  const existing = document.getElementById('rb-failed-banner');
  if (existing) existing.remove();
  if (!failed.length) return;

  const banner = document.createElement('div');
  banner.id = 'rb-failed-banner';
  banner.className = 'al al-w';
  banner.style.marginBottom = '12px';
  banner.innerHTML = `⚠ Could not load: ${failed.map(f => esc(f.label)).join(', ')}
    — their deleted records are not shown above. (Check server error log for details.)`;
  document.getElementById('rb-stats').insertAdjacentElement('afterend', banner);
}

function updateStats(rows) {
  const counts = {};
  rows.forEach(r => { counts[r.module] = (counts[r.module] || 0) + 1; });
  const total = rows.length;

  const statsEl = document.getElementById('rb-stats');
  if (!total) { statsEl.innerHTML = ''; return; }

  const cards = Object.entries(counts).map(([mod, cnt]) => `
    <div class="sc sc-secondary" style="border-top:3px solid ${MODULE_COLORS[mod]||'var(--brand)'}">
      <div class="slabel">${MODULE_ICONS[mod]||'📄'} ${mod.replace('_',' ')}</div>
      <div class="sval b" style="color:${MODULE_COLORS[mod]||'var(--brand)'}">${cnt}</div>
    </div>`).join('');

  statsEl.innerHTML = `
    <div class="sc sc-secondary" style="border-top:3px solid var(--danger)">
      <div class="slabel">🗑 Total Deleted</div>
      <div class="sval b" style="color:var(--danger)">${total}</div>
    </div>
    ${cards}`;
}

function renderTable(rows) {
  const el = document.getElementById('rb-body');

  if (!rows.length) {
    el.innerHTML = `
      <div style="text-align:center;padding:50px;color:var(--text3)">
        <div style="font-size:40px;margin-bottom:10px">✅</div>
        <div style="font-size:14px">Recycle Bin is empty</div>
      </div>`;
    return;
  }

  el.innerHTML = `
    <div class="tw" style="overflow-x:auto">
      <table style="min-width:700px">
        <thead>
          <tr>
            <th>Module</th>
            <th>Record</th>
            <th>Deleted At</th>
            <th>Deleted By</th>
            <th style="width:180px">Actions</th>
          </tr>
        </thead>
        <tbody>
          ${rows.map(r => `
          <tr id="rb-row-${r.module}-${r.id}">
            <td>
              <span style="font-size:11px;font-weight:700;padding:2px 8px;
                           border-radius:10px;background:var(--danger-light);
                           color:var(--danger)">
                ${MODULE_ICONS[r.module]||'📄'} ${r.module_label}
              </span>
            </td>
            <td>
              <div style="font-weight:700">${esc(r.record_name)}</div>
              <div style="font-size:11px;color:var(--text3)">ID: ${r.id}</div>
            </td>
            <td class="mono" style="font-size:12px;color:var(--text3)">
              ${r.deleted_at ? new Date(r.deleted_at).toLocaleString() : '—'}
            </td>
            <td style="font-size:12px;color:var(--text3)">
              ${r.deleted_by ? 'User #' + r.deleted_by : '—'}
            </td>
            <td>
              <div style="display:flex;gap:5px;flex-wrap:wrap">
                <button class="btn btn-sm btn-accent"
                        onclick="doRestore('${r.module}', ${r.id})">
                  ↩ Restore
                </button>
                ${IS_SUPER ? `
                <button class="btn btn-sm btn-danger"
                        onclick="doPermDelete('${r.module}', ${r.id}, '${esc(r.record_name)}')">
                  🗑 Delete Forever
                </button>` : ''}
              </div>
            </td>
          </tr>`).join('')}
        </tbody>
      </table>
    </div>`;
}

async function doRestore(module, id) {
  if (!confirm('Restore this record? Stock, ledger, and balances will be corrected.')) return;
  const r = await apiPost(API, { action: 'restore', module, id });
  if (!r.success) { alert('⚠ ' + r.error); return; }
  const row = document.getElementById(`rb-row-${module}-${id}`);
  if (row) {
    row.style.transition = 'opacity .3s';
    row.style.opacity = '0';
    setTimeout(() => { row.remove(); loadBin(); }, 350);
  }
  showToast('✅ ' + r.msg, 'success');
}

async function doPermDelete(module, id, name) {
  if (!confirm(`PERMANENTLY DELETE "${name}"?\n\nThis CANNOT be undone. The record will be gone forever.`)) return;
  if (!confirm('Are you absolutely sure? Type OK to confirm.') ) return;
  const r = await apiPost(API, { action: 'permanent_delete', module, id });
  if (!r.success) { alert('⚠ ' + r.error); return; }
  document.getElementById(`rb-row-${module}-${id}`)?.remove();
  showToast('🗑 ' + r.msg, 'warn');
}

function showToast(msg, type = 'info') {
  const colors = {
    success: { bg:'#d4f0e6', cl:'#065f46', bd:'#6ee7b7' },
    error:   { bg:'#fde8e8', cl:'#991b1b', bd:'#f5a0a0' },
    warn:    { bg:'#fff3dc', cl:'#78350f', bd:'#f59e0b' },
    info:    { bg:'#e0f2ff', cl:'#0369a1', bd:'#7dd3fc' },
  };
  const { bg, cl, bd } = colors[type] || colors.info;
  const t = document.createElement('div');
  t.style.cssText = `position:fixed;bottom:24px;right:20px;z-index:9999;padding:10px 16px;
    border-radius:8px;font-size:13px;font-weight:600;background:${bg};color:${cl};
    border:1px solid ${bd};box-shadow:0 4px 20px rgba(0,0,0,.18);max-width:320px;
    transition:opacity .4s;cursor:pointer`;
  t.textContent = msg;
  t.onclick = () => t.remove();
  document.body.appendChild(t);
  setTimeout(() => { t.style.opacity='0'; setTimeout(()=>t.remove(),400); }, 5000);
}

function esc(s) {
  return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;')
    .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

// Load on ready
document.addEventListener('DOMContentLoaded', loadBin);
</script>
<?php require_once '../includes/footer.php'; ?>
