<?php
// ============================================================
//  MediCore — Income / Expense
//  File: accounting/accounts.php
// ============================================================
$page  = 'accounting/accounts';
$title = 'Income / Expense';
require_once '../includes/header.php';

$cur   = $settings['currency'];
$today = today();

$totalExp  = (float) db_val("SELECT COALESCE(SUM(amount),0) FROM expenses");
$totalInc  = (float) db_val("SELECT COALESCE(SUM(amount),0) FROM incomes");
$netBal    = $totalInc - $totalExp;
$thisMonth = date('Y-m');
// Range comparison instead of DATE_FORMAT(date,'%Y-%m')=? so idx_date
// can actually be used (wrapping the column in a function disables it).
$mStart = date('Y-m-01');
$mNext  = date('Y-m-01', strtotime('+1 month'));
$monthExp  = (float) db_val("SELECT COALESCE(SUM(amount),0) FROM expenses WHERE date >= ? AND date < ?", [$mStart, $mNext]);
$monthInc  = (float) db_val("SELECT COALESCE(SUM(amount),0) FROM incomes  WHERE date >= ? AND date < ?", [$mStart, $mNext]);

$expCats = ['Rent'=>['🏠','var(--brand)'],'Salary'=>['👤','var(--purple)'],
            'Utilities'=>['⚡','var(--warn)'],'Marketing'=>['📢','var(--teal)'],
            'Transport'=>['🚗','var(--accent)'],'Maintenance'=>['🔧','var(--text2)'],
            'Misc'=>['📦','var(--text3)']];
$incCats = ['Sale Revenue'=>['💊','var(--accent)'],'Due Collected'=>['💰','var(--brand)'],
            'Investment'=>['🏦','var(--purple)'],'Refund'=>['↩️','var(--teal)'],
            'Other'=>['✨','var(--text2)']];
?>
<script>
document.getElementById('ph-actions').innerHTML=`
  <button class="btn btn-sm btn-danger" onclick="openAddExp()">➕ Add Expense</button>
  <button class="btn btn-sm btn-accent" onclick="openAddInc()">➕ Add Income</button>`;
</script>

<!-- Summary cards -->
<div style="display:grid;grid-template-columns:repeat(5,1fr);gap:10px;margin-bottom:12px">
  <div class="sc" style="border-top:3px solid var(--danger)">
    <div class="slabel">Total Expenses</div>
    <div class="sval b" style="color:var(--danger)"><?=$cur.number_format($totalExp,2)?></div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">All time</div>
  </div>
  <div class="sc" style="border-top:3px solid var(--accent)">
    <div class="slabel">Total Income</div>
    <div class="sval b" style="color:var(--accent)"><?=$cur.number_format($totalInc,2)?></div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">All time</div>
  </div>
  <div class="sc" style="border-top:3px solid <?=$netBal>=0?'var(--accent)':'var(--danger)'?>">
    <div class="slabel">Net Balance</div>
    <div class="sval b" style="color:<?=$netBal>=0?'var(--accent)':'var(--danger)'?>"><?=$cur.number_format($netBal,2)?></div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">Income − Expense</div>
  </div>
  <div class="sc" style="border-top:3px solid var(--warn)">
    <div class="slabel">This Month Exp.</div>
    <div class="sval b" style="color:var(--warn)"><?=$cur.number_format($monthExp,2)?></div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px"><?=date('M Y')?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--teal)">
    <div class="slabel">This Month Inc.</div>
    <div class="sval b" style="color:var(--teal)"><?=$cur.number_format($monthInc,2)?></div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px"><?=date('M Y')?></div>
  </div>
</div>

<!-- Tabs -->
<div style="display:flex;gap:0;margin-bottom:12px;border-bottom:2px solid var(--border)">
  <button id="tab-exp" onclick="switchTab('exp')"
    style="padding:9px 22px;font-size:13px;font-weight:600;border:none;cursor:pointer;
           border-bottom:2px solid var(--danger);color:var(--danger);
           background:transparent;margin-bottom:-2px">💸 Expenses</button>
  <button id="tab-inc" onclick="switchTab('inc')"
    style="padding:9px 22px;font-size:13px;font-weight:600;border:none;cursor:pointer;
           border-bottom:2px solid transparent;color:var(--text2);
           background:transparent;margin-bottom:-2px">💹 Income</button>
</div>

<!-- Filters -->
<div style="display:flex;gap:9px;align-items:center;flex-wrap:wrap;margin-bottom:10px">
  <select id="f-cat" onchange="loadActive()"
    style="padding:5px 9px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;outline:none"></select>
  <input type="date" id="f-from" onchange="loadActive()"
    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="loadActive()"
    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-q" placeholder="🔍 Search…" oninput="delayLoad()"
    style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;outline:none;width:160px">
  <button class="btn btn-sm" onclick="clearFilters()">✕ Clear</button>
</div>

<!-- Table -->
<div class="card" style="padding:0">
  <div class="tw">
    <table id="acct-table">
      <thead><tr id="acct-head"></tr></thead>
      <tbody id="acct-body">
        <tr><td colspan="7" class="empty-state">Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="acct-footer"
       style="padding:8px 14px;font-size:11px;color:var(--text3);
              border-top:1px solid var(--border)"></div>
</div>

<script>
const API      = '../api/accounts.php';
const CUR      = '<?=addslashes($cur)?>';
const IS_ADMIN = <?=is_admin()?'true':'false'?>;
const TODAY    = '<?=$today?>';
const EXP_CATS = <?=json_encode(array_keys($expCats))?>;
const INC_CATS = <?=json_encode(array_keys($incCats))?>;
const CAT_META = <?=json_encode(array_merge(
  array_map(fn($v)=>['icon'=>$v[0],'color'=>$v[1]],$expCats),
  array_map(fn($v)=>['icon'=>$v[0],'color'=>$v[1]],$incCats)
))?>;

let activeTab='exp', srchTimer=null;

function switchTab(tab) {
  activeTab = tab;
  const isExp = tab==='exp';
  document.getElementById('tab-exp').style.borderBottomColor = isExp?'var(--danger)':'transparent';
  document.getElementById('tab-exp').style.color = isExp?'var(--danger)':'var(--text2)';
  document.getElementById('tab-inc').style.borderBottomColor = !isExp?'var(--accent)':'transparent';
  document.getElementById('tab-inc').style.color = !isExp?'var(--accent)':'var(--text2)';
  const cats = isExp?EXP_CATS:INC_CATS;
  document.getElementById('f-cat').innerHTML =
    `<option value="">All Categories</option>` +
    cats.map(c=>`<option>${c}</option>`).join('');
  loadActive();
}

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

async function load(tab) {
  const tbody = document.getElementById('acct-body');
  tbody.innerHTML = '<tr><td colspan="7" class="empty-state">Loading…</td></tr>';
  setHead(tab);
  const r = await apiPost(API,{
    action:'list', type:tab,
    cat:  document.getElementById('f-cat').value,
    from: document.getElementById('f-from').value,
    to:   document.getElementById('f-to').value,
    q:    document.getElementById('f-q').value.trim(),
  });
  if(!r.success){
    tbody.innerHTML=`<tr><td colspan="7" class="empty-state" style="color:var(--danger)">Error: ${r.error}</td></tr>`;
    return;
  }
  renderRows(r.data,tab);
}

function setHead(tab){
  const isExp=tab==='exp';
  document.getElementById('acct-head').innerHTML=`
    <th style="width:38px">#</th>
    <th style="width:130px">Category</th>
    <th>Description</th>
    ${isExp?'<th style="text-align:center">Account</th>':''}
    <th>Date</th>
    <th style="text-align:right">Amount</th>
    <th style="text-align:center;width:60px">Action</th>`;
}

function renderRows(rows,tab){
  const tbody  = document.getElementById('acct-body');
  const footer = document.getElementById('acct-footer');
  const isExp  = tab==='exp';
  const cl     = isExp?'var(--danger)':'var(--accent)';
  const acctIcons={Cash:'💵',Card:'💳',Bank:'🏦',MFS:'📱'};

  if(!rows.length){
    tbody.innerHTML=`<tr><td colspan="7" class="empty-state">No ${isExp?'expenses':'income'} found.</td></tr>`;
    footer.textContent=''; return;
  }
  const total = rows.reduce((s,r)=>s+parseFloat(r.amount||0),0);
  footer.innerHTML=`<strong>${rows.length}</strong> record(s) &nbsp;·&nbsp;
    Total: <strong style="color:${cl}">${CUR}${total.toFixed(2)}</strong>`;

  tbody.innerHTML = rows.map((row,i)=>{
    const meta = CAT_META[row.category]||{icon:isExp?'📦':'✨',color:'var(--text2)'};
    return `<tr>
      <td style="color:var(--text3)">${i+1}</td>
      <td><span style="display:inline-flex;align-items:center;gap:5px;padding:3px 8px;
                       border-radius:10px;font-size:11px;font-weight:600;
                       background:${meta.color}22;color:${meta.color}">
        ${meta.icon} ${esc(row.category)}
      </span></td>
      <td style="font-size:12px">${esc(row.description)}</td>
      ${isExp?`<td style="text-align:center">
        <span class="badge" style="font-size:10px">
          ${acctIcons[row.account]||''} ${esc(row.account||'')}
        </span></td>`:''}
      <td style="color:var(--text2)">${row.date}</td>
      <td class="mono" style="text-align:right;font-weight:700;color:${cl}">
        ${CUR}${parseFloat(row.amount||0).toFixed(2)}
      </td>
      <td style="text-align:center">
        ${IS_ADMIN?`<button class="btn btn-sm btn-danger" style="padding:2px 7px"
          onclick="delRow(${row.id},'${tab}')">🗑</button>`:''}
      </td>
    </tr>`;
  }).join('');
}

function openAddExp(){
  showModal(`
  <div style="display:flex;flex-direction:column;gap:9px">
    <div class="fg2">
      <div class="fg"><label>Category *</label>
        <select id="e-cat" style="width:100%">
          ${EXP_CATS.map(c=>`<option>${c}</option>`).join('')}
        </select></div>
      <div class="fg"><label>Account *</label>
        <select id="e-acct" style="width:100%">
          <option>Cash</option><option>Bank</option>
          <option>MFS</option><option>Card</option>
        </select></div>
    </div>
    <div class="fg"><label>Description *</label>
      <input id="e-desc" placeholder="e.g. Monthly shop rent"></div>
    <div class="fg2">
      <div class="fg"><label>Amount (${CUR}) *</label>
        <input id="e-amount" type="number" step="0.01" min="0.01" placeholder="0.00"></div>
      <div class="fg"><label>Date</label>
        <input id="e-date" type="date" value="${TODAY}"></div>
    </div>
    <div id="e-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-danger" onclick="saveRow('exp')">💸 Add Expense</button>
  </div>`,'💸 Add Expense');
  setTimeout(()=>document.getElementById('e-desc')?.focus(),50);
}

function openAddInc(){
  showModal(`
  <div style="display:flex;flex-direction:column;gap:9px">
    <div class="fg2">
      <div class="fg"><label>Category *</label>
        <select id="i-cat" style="width:100%">
          ${INC_CATS.map(c=>`<option>${c}</option>`).join('')}
        </select></div>
      <div class="fg"><label>Account *</label>
        <select id="i-acct" style="width:100%">
          <option>Cash</option><option>Bank</option>
          <option>MFS</option><option>Card</option>
        </select></div>
    </div>
    <div class="fg"><label>Description *</label>
      <input id="i-desc" placeholder="e.g. Other income source"></div>
    <div class="fg2">
      <div class="fg"><label>Amount (${CUR}) *</label>
        <input id="i-amount" type="number" step="0.01" min="0.01" placeholder="0.00"></div>
      <div class="fg"><label>Date</label>
        <input id="i-date" type="date" value="${TODAY}"></div>
    </div>
    <div id="i-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-accent" onclick="saveRow('inc')">💹 Add Income</button>
  </div>`,'💹 Add Income');
  setTimeout(()=>document.getElementById('i-desc')?.focus(),50);
}

async function saveRow(type){
  const p=type==='exp'?'e':'i';
  const cat  = document.getElementById(`${p}-cat`).value;
  const acct = document.getElementById(`${p}-acct`).value;
  const desc = document.getElementById(`${p}-desc`).value.trim();
  const amt  = parseFloat(document.getElementById(`${p}-amount`).value)||0;
  const date = document.getElementById(`${p}-date`).value;
  const errEl= document.getElementById(`${p}-err`);

  if(!desc){ errEl.textContent='⚠ Description is required.'; errEl.style.display='block';
    document.getElementById(`${p}-desc`).focus(); return; }
  if(amt<=0){ errEl.textContent='⚠ Enter a valid amount.'; errEl.style.display='block';
    document.getElementById(`${p}-amount`).focus(); return; }

  const r = await apiPost(API,{action:'add',type,cat,account:acct,desc,amount:amt,date});
  if(r.success){ closeModal(); switchTab(type); setTimeout(()=>location.reload(),300); }
  else{ errEl.textContent='⚠ '+(r.error||'Save failed.'); errEl.style.display='block'; }
}

async function delRow(id,type){
  if(!confirm('Delete this entry?\nCash ledger entry will also be removed.')) return;
  const r = await apiPost(API,{action:'delete',id,type});
  if(r.success){ loadActive(); setTimeout(()=>location.reload(),300); }
  else alert('⚠ '+(r.error||'Delete failed.'));
}

function clearFilters(){
  ['f-cat','f-from','f-to','f-q'].forEach(id=>document.getElementById(id).value='');
  loadActive();
}
function esc(s){
  return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
document.addEventListener('DOMContentLoaded',()=>switchTab('exp'));
</script>
<?php require_once '../includes/footer.php'; ?>
