<?php
// ============================================================
//  MediCore — Cash Balance
//  File: accounting/cash.php
// ============================================================
$page  = 'accounting/cash';
$title = 'Cash Balance';
require_once '../includes/header.php';

$cur = $settings['currency'];
$today = date('Y-m-d');

// ── Per-account summaries ─────────────────────────────────────
function acct_summary(string $acct): array {
    $in  = (float) db_val(
        "SELECT COALESCE(SUM(amount),0) FROM cash_ledger
          WHERE account = ? AND type = 'in'", [$acct]);
    $out = (float) db_val(
        "SELECT COALESCE(SUM(amount),0) FROM cash_ledger
          WHERE account = ? AND type = 'out'", [$acct]);
    return ['in' => $in, 'out' => $out, 'balance' => $in - $out];
}

$accounts = ['Cash','Card','Bank','MFS'];
$acctIcons = ['Cash'=>'💵','Card'=>'💳','Bank'=>'🏦','MFS'=>'📱'];
$acctColor = [
    'Cash' => 'var(--accent)',
    'Card' => 'var(--brand)',
    'Bank' => 'var(--warn)',
    'MFS'  => 'var(--purple)',
];

$summaries = [];
$grandBal  = 0;
foreach ($accounts as $a) {
    $summaries[$a] = acct_summary($a);
    $grandBal     += $summaries[$a]['balance'];
}
?>

<!-- ── Page actions ───────────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML =
  `<button class="btn btn-primary btn-sm" onclick="openAdd()">
     ➕ Add Manual Entry
   </button>`;
</script>

<!-- ── Grand total banner ─────────────────────────── -->
<div class="card" style="padding:12px 18px;margin-bottom:12px;
     background:var(--brand);border:none;color:#fff;
     display:flex;justify-content:space-between;align-items:center">
  <div style="font-size:13px;font-weight:600;opacity:.9">
    💰 Total Cash Balance (All Accounts)
  </div>
  <div class="mono" style="font-size:22px;font-weight:800">
    <?= $cur . number_format($grandBal, 2) ?>
  </div>
</div>

<!-- ── 4 Account cards ────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);
            gap:10px;margin-bottom:14px">
  <?php foreach ($accounts as $a):
    $s   = $summaries[$a];
    $cl  = $acctColor[$a];
    $ico = $acctIcons[$a];
    $bal = $s['balance'];
  ?>
  <div class="sc" style="border-top:3px solid <?= $cl ?>;cursor:pointer"
       onclick="filterAccount('<?= $a ?>')" title="Click to filter by <?= $a ?>">
    <div style="display:flex;justify-content:space-between;align-items:center;
                margin-bottom:6px">
      <span style="font-size:18px"><?= $ico ?></span>
      <span style="font-size:11px;font-weight:700;color:<?= $cl ?>"><?= $a ?></span>
    </div>
    <div class="sval b" style="color:<?= $cl ?>;font-size:16px">
      <?= $cur . number_format($bal, 2) ?>
    </div>
    <div style="display:flex;justify-content:space-between;
                margin-top:8px;padding-top:6px;
                border-top:1px solid var(--border);font-size:10.5px">
      <span style="color:var(--accent)">
        ▲ In: <?= $cur . number_format($s['in'], 2) ?>
      </span>
      <span style="color:var(--danger)">
        ▼ Out: <?= $cur . number_format($s['out'], 2) ?>
      </span>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- ── Filter bar ─────────────────────────────────── -->
<div class="card" style="padding:10px 14px;margin-bottom:10px;
     display:flex;gap:10px;align-items:center;flex-wrap:wrap">
  <span style="font-size:12px;color:var(--text2);font-weight:600">Filter:</span>

  <select id="f-account" onchange="load()"
    style="padding:5px 9px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
    <option value="">All Accounts</option>
    <?php foreach ($accounts as $a): ?>
    <option value="<?= $a ?>"><?= $acctIcons[$a] ?> <?= $a ?></option>
    <?php endforeach; ?>
  </select>

  <select id="f-type" onchange="load()"
    style="padding:5px 9px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
    <option value="">All Types</option>
    <option value="in">▲ Cash In</option>
    <option value="out">▼ Cash Out</option>
  </select>

  <input type="date" id="f-from" onchange="load()" title="From date"
    style="padding:5px 8px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
  <span style="font-size:11px;color:var(--text3)">to</span>
  <input type="date" id="f-to" onchange="load()" title="To date"
    style="padding:5px 8px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">

  <input type="text" id="f-search" placeholder="🔍 Search description or ref…"
         oninput="delayLoad()"
    style="padding:5px 10px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none;flex:1;min-width:180px">

  <button class="btn btn-sm" onclick="clearFilters()">✕ Clear</button>
</div>

<!-- ── Ledger table ───────────────────────────────── -->
<div class="card" style="padding:0">
  <div class="tw">
    <table id="ledger-table">
      <thead>
        <tr>
          <th style="width:38px">#</th>
          <th>Date</th>
          <th>Description</th>
          <th style="text-align:center">Account</th>
          <th style="text-align:right">Cash In ▲</th>
          <th style="text-align:right">Cash Out ▼</th>
          <th>Reference</th>
          <th style="text-align:center;width:60px">Action</th>
        </tr>
      </thead>
      <tbody id="ledger-body">
        <tr><td colspan="8" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="ledger-footer"
       style="padding:8px 14px;font-size:11px;color:var(--text3);
              border-top:1px solid var(--border)"></div>
</div>

<script>
const API = '../api/cash.php';
const CUR = '<?= addslashes($cur) ?>';
const ACCOUNTS = <?= json_encode($accounts) ?>;
const IS_ADMIN = <?= is_admin() ? 'true' : 'false' ?>;
let srchTimer = null;

// ── Load ledger ───────────────────────────────────────────────
async function load() {
  const tbody = document.getElementById('ledger-body');
  tbody.innerHTML =
    '<tr><td colspan="8" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>';

  let r;
  try {
    r = await apiPost(API, {
      action:  'list',
      account: document.getElementById('f-account').value,
      type:    document.getElementById('f-type').value,
      from:    document.getElementById('f-from').value,
      to:      document.getElementById('f-to').value,
      q:       document.getElementById('f-search').value.trim(),
    });
  } catch (err) {
    tbody.innerHTML = `<tr><td colspan="8" class="empty-state"
      style="color:var(--danger)">⚠ Request failed: ${esc(String(err))}</td></tr>`;
    return;
  }

  if (!r || !r.success) {
    tbody.innerHTML = `<tr><td colspan="8" class="empty-state"
      style="color:var(--danger)">⚠ ${esc(r?.error || 'Unknown error')}</td></tr>`;
    return;
  }

  try {
    renderLedger(Array.isArray(r.data) ? r.data : []);
  } catch (err) {
    tbody.innerHTML = `<tr><td colspan="8" class="empty-state"
      style="color:var(--danger)">⚠ Render error: ${esc(String(err))}</td></tr>`;
    console.error('renderLedger error:', err);
  }
}

function delayLoad() {
  clearTimeout(srchTimer);
  srchTimer = setTimeout(load, 280);
}

function renderLedger(rows) {
  const tbody  = document.getElementById('ledger-body');
  const footer = document.getElementById('ledger-footer');

  if (!rows.length) {
    tbody.innerHTML =
      '<tr><td colspan="8" class="empty-state">No transactions found.</td></tr>';
    footer.textContent = ''; return;
  }

  const acctColor = {
    Cash:'var(--accent)', Card:'var(--brand)',
    Bank:'var(--warn)',   MFS:'var(--purple)'
  };
  const acctIcon  = { Cash:'💵', Card:'💳', Bank:'🏦', MFS:'📱' };

  let totIn = 0, totOut = 0;

  tbody.innerHTML = rows.map((r, i) => {
    const isIn  = r.type === 'in';
    const amt   = parseFloat(r.amount || 0);
    if (isIn) totIn += amt; else totOut += amt;
    const cl    = acctColor[r.account] || 'var(--text2)';
    const ico   = acctIcon[r.account]  || '';
    const isMan = (r.ref || '').startsWith('MAN-');

    return `<tr>
      <td style="color:var(--text3)">${i + 1}</td>
      <td style="color:var(--text2)">${r.date}</td>
      <td>
        <div style="font-size:12px">${esc(r.description)}</div>
        ${isMan
          ? `<span style="font-size:10px;background:var(--surface2);
                          color:var(--text3);padding:1px 5px;
                          border-radius:3px">manual</span>`
          : ''}
      </td>
      <td style="text-align:center">
        <span class="badge"
              style="background:${cl}22;color:${cl};font-weight:600">
          ${ico} ${esc(r.account)}
        </span>
      </td>
      <td class="mono"
          style="text-align:right;color:var(--accent);font-weight:${isIn?'700':'400'}">
        ${isIn ? CUR + amt.toFixed(2) : '—'}
      </td>
      <td class="mono"
          style="text-align:right;color:var(--danger);font-weight:${!isIn?'700':'400'}">
        ${!isIn ? CUR + amt.toFixed(2) : '—'}
      </td>
      <td class="mono" style="font-size:11px;color:var(--text3)">
        ${esc(r.ref || '—')}
      </td>
      <td style="text-align:center">
        ${IS_ADMIN && isMan
          ? `<button class="btn btn-sm btn-danger"
                     style="padding:2px 7px"
                     onclick="delEntry(${r.id})">🗑</button>`
          : ''}
      </td>
    </tr>`;
  }).join('');

  const net = totIn - totOut;
  footer.innerHTML =
    `<strong>${rows.length}</strong> transaction(s) &nbsp;·&nbsp;
     In: <strong style="color:var(--accent)">${CUR}${totIn.toFixed(2)}</strong>
     &nbsp;·&nbsp;
     Out: <strong style="color:var(--danger)">${CUR}${totOut.toFixed(2)}</strong>
     &nbsp;·&nbsp;
     Net: <strong style="color:${net>=0?'var(--accent)':'var(--danger)'}">
            ${CUR}${net.toFixed(2)}
          </strong>`;
}

// ── Filter helpers ────────────────────────────────────────────
function filterAccount(a) {
  document.getElementById('f-account').value = a;
  load();
  document.getElementById('ledger-table')
    .scrollIntoView({ behavior:'smooth', block:'start' });
}

function clearFilters() {
  document.getElementById('f-account').value = '';
  document.getElementById('f-type').value    = '';
  document.getElementById('f-from').value    = '';
  document.getElementById('f-to').value      = '';
  document.getElementById('f-search').value  = '';
  load();
}

// ── Add Manual Entry modal ────────────────────────────────────
function openAdd() {
  showModal(`
  <div style="margin-bottom:10px;padding:8px 12px;
              background:var(--brand-xlight);border-radius:var(--rsm);
              font-size:11px;color:var(--text2)">
    💡 Use manual entries for opening balances,
    petty cash, adjustments, or any transaction
    not captured by sales or purchases.
  </div>

  <div style="display:flex;flex-direction:column;gap:9px">
    <div class="fg">
      <label>Description *</label>
      <input id="m-desc" placeholder="e.g. Opening Balance — Cash">
    </div>

    <div class="fg2">
      <div class="fg">
        <label>Account *</label>
        <select id="m-account" style="width:100%">
          <option value="Cash">💵 Cash</option>
          <option value="Bank">🏦 Bank</option>
          <option value="MFS">📱 MFS</option>
          <option value="Card">💳 Card</option>
        </select>
      </div>
      <div class="fg">
        <label>Type *</label>
        <select id="m-type" style="width:100%">
          <option value="in">▲ Cash In</option>
          <option value="out">▼ Cash Out</option>
        </select>
      </div>
    </div>

    <div class="fg2">
      <div class="fg">
        <label>Amount (<?= $cur ?>) *</label>
        <input id="m-amount" type="number" step="0.01" min="0.01"
               placeholder="0.00">
      </div>
      <div class="fg">
        <label>Date</label>
        <input id="m-date" type="date"
               value="<?= $today ?>">
      </div>
    </div>

    <div class="fg">
      <label>Reference / Note</label>
      <input id="m-ref" placeholder="Optional reference">
    </div>

    <div id="m-err"
         style="color:var(--danger);font-size:11px;display:none"></div>
  </div>

  <div style="display:flex;gap:8px;justify-content:flex-end;
              margin-top:14px;padding-top:12px;
              border-top:1px solid var(--border)">
    <button class="btn" onclick="closeModal()">Cancel</button>
    <button class="btn btn-primary" onclick="saveEntry()">
      ➕ Add Entry
    </button>
  </div>`, '➕ Add Manual Entry');

  setTimeout(() => document.getElementById('m-desc')?.focus(), 50);
}

// ── Save manual entry ─────────────────────────────────────────
async function saveEntry() {
  const desc   = document.getElementById('m-desc').value.trim();
  const acct   = document.getElementById('m-account').value;
  const type   = document.getElementById('m-type').value;
  const amount = parseFloat(document.getElementById('m-amount').value) || 0;
  const date   = document.getElementById('m-date').value;
  const ref    = document.getElementById('m-ref').value.trim();
  const errEl  = document.getElementById('m-err');

  if (!desc) {
    errEl.textContent = '⚠ Description is required.';
    errEl.style.display = 'block';
    document.getElementById('m-desc').focus(); return;
  }
  if (amount <= 0) {
    errEl.textContent = '⚠ Enter a valid amount greater than zero.';
    errEl.style.display = 'block';
    document.getElementById('m-amount').focus(); return;
  }

  const r = await apiPost(API, {
    action: 'add', desc, account: acct,
    type, amount, date, ref
  });

  if (r.success) {
    closeModal();
    load();
    // Refresh page to update account cards
    setTimeout(() => location.reload(), 300);
  } else {
    errEl.textContent = '⚠ ' + (r.error || 'Save failed.');
    errEl.style.display = 'block';
  }
}

// ── Delete manual entry ───────────────────────────────────────
async function delEntry(id) {
  if (!confirm('Delete this manual entry?\nThis cannot be undone.')) return;
  const r = await apiPost(API, { action: 'delete', id });
  if (r.success) {
    load();
    setTimeout(() => location.reload(), 300);
  } else {
    alert('⚠ ' + (r.error || 'Delete failed.'));
  }
}

// ── Init ──────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', load);

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

<?php require_once '../includes/footer.php'; ?>
