<?php
/** Payroll (payroll add-on). Access: admin / accountant / headteacher / director. */
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }

require_once '../config.php';
requireModule('payroll');
require_once __DIR__ . '/../includes/payroll_lib.php';

$role = $_SESSION['role'] ?? '';
if (!payroll_can_manage($role)) { header('Location: ../dashboard.php?error=no_access'); exit; }

$conn = getDBConnection();
payroll_ensure_tables($conn);
$base = defined('BASE_URL') ? rtrim(BASE_URL, '/') : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payroll — EduTrack</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/style.css">
</head>
<body>
<div class="wrapper">
    <nav id="sidebar" class="sidebar"><?php echo buildSidebar('payroll/index.php'); ?></nav>
    <div class="main-content">
        <header class="header">
            <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
            <div class="header-right"><span class="text-muted"><i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string)($_SESSION['full_name'] ?? '')); ?></span></div>
        </header>
        <main class="content">
            <div class="content-header d-flex align-items-center gap-3">
                <div style="background:linear-gradient(135deg,#0f766e,#115e59);border-radius:12px;width:44px;height:44px;display:flex;align-items:center;justify-content:center;">
                    <i class="fas fa-money-check-dollar text-white fa-lg"></i>
                </div>
                <div><h2 class="mb-0">Payroll</h2><p class="text-muted mb-0 small">Salaries, SSNIT &amp; PAYE, payslips</p></div>
            </div>

            <ul class="nav nav-tabs mb-3">
                <li class="nav-item"><a class="nav-link active" id="tabRunsBtn" href="#" onclick="showTab('runs');return false;">Payroll Runs</a></li>
                <li class="nav-item"><a class="nav-link" id="tabPayBtn" href="#" onclick="showTab('pay');return false;">Staff Pay Setup</a></li>
            </ul>

            <!-- Runs tab -->
            <div id="tabRuns">
                <div class="d-flex justify-content-between mb-2">
                    <h5>Runs</h5>
                    <div class="input-group input-group-sm" style="max-width:360px">
                        <input type="month" id="runPeriod" class="form-control">
                        <button class="btn btn-success" onclick="createRun()"><i class="fas fa-plus me-1"></i>Create Run</button>
                    </div>
                </div>
                <div class="card"><div class="table-responsive">
                    <table class="table table-hover mb-0"><thead class="table-light">
                        <tr><th>Period</th><th>Staff</th><th>Net Total</th><th>Status</th><th></th></tr></thead>
                        <tbody id="runsBody"><tr><td colspan="5" class="text-center text-muted py-3">Loading…</td></tr></tbody>
                    </table>
                </div></div>
            </div>

            <!-- Staff pay tab -->
            <div id="tabPay" style="display:none">
                <div class="card"><div class="table-responsive">
                    <table class="table table-sm table-hover mb-0"><thead class="table-light">
                        <tr><th>Staff</th><th>Basic</th><th>Allowances</th><th>SSNIT (5.5%)</th><th>PAYE</th><th>Net</th><th></th></tr></thead>
                        <tbody id="payBody"><tr><td colspan="7" class="text-center text-muted py-3">Loading…</td></tr></tbody>
                    </table>
                </div></div>
            </div>
        </main>
    </div>
</div>

<!-- Pay edit modal -->
<div class="modal fade" id="payModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <form id="payForm"><div class="modal-header"><h5 class="modal-title" id="payTitle">Edit Pay</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body"><input type="hidden" id="pay_staff_id">
        <div class="row g-2">
            <div class="col-6"><label class="form-label small">Basic salary</label><input type="number" step="0.01" id="pay_basic" class="form-control"></div>
            <div class="col-6"><label class="form-label small">Transport allowance</label><input type="number" step="0.01" id="pay_tr" class="form-control"></div>
            <div class="col-6"><label class="form-label small">Housing allowance</label><input type="number" step="0.01" id="pay_ho" class="form-control"></div>
            <div class="col-6"><label class="form-label small">Other allowance</label><input type="number" step="0.01" id="pay_oa" class="form-control"></div>
            <div class="col-6"><label class="form-label small">Other deductions</label><input type="number" step="0.01" id="pay_od" class="form-control"></div>
            <div class="col-6"><label class="form-label small">Tax relief</label><input type="number" step="0.01" id="pay_relief" class="form-control"></div>
            <div class="col-12"><div class="form-check"><input class="form-check-input" type="checkbox" id="pay_exempt"><label class="form-check-label small" for="pay_exempt">SSNIT exempt</label></div></div>
        </div>
        <div class="alert alert-light border mt-2 small mb-0" id="payPreview"></div>
    </div>
    <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-success" type="submit">Save</button></div></form>
</div></div></div>

<!-- Run detail modal -->
<div class="modal fade" id="runModal" tabindex="-1"><div class="modal-dialog modal-xl"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title" id="runTitle">Payroll Run</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body" id="runBody">Loading…</div>
</div></div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="../js/main.js"></script>
<script>
const BASE="<?php echo $base; ?>";
function esc(s){const d=document.createElement('div');d.textContent=s==null?'':s;return d.innerHTML;}
function money(n){return Number(n||0).toLocaleString(undefined,{minimumFractionDigits:2});}
function showTab(t){
  document.getElementById('tabRuns').style.display=t==='runs'?'':'none';
  document.getElementById('tabPay').style.display=t==='pay'?'':'none';
  document.getElementById('tabRunsBtn').classList.toggle('active',t==='runs');
  document.getElementById('tabPayBtn').classList.toggle('active',t==='pay');
  if(t==='pay')loadPay(); else loadRuns();
}

function loadRuns(){
  fetch('ajax/api.php?action=runs_list').then(r=>r.json()).then(d=>{
    const b=document.getElementById('runsBody');
    if(!d.data.length){b.innerHTML='<tr><td colspan="5" class="text-center text-muted py-3">No runs yet.</td></tr>';return;}
    b.innerHTML=d.data.map(r=>`<tr>
      <td class="fw-semibold">${esc(r.period)}</td><td>${r.staff_count}</td><td>GHS ${money(r.net_total)}</td>
      <td>${r.status==='finalized'?'<span class="badge bg-primary">finalized</span>':'<span class="badge bg-warning text-dark">draft</span>'}</td>
      <td><button class="btn btn-sm btn-outline-secondary" onclick="viewRun(${r.id})">Open</button></td>
    </tr>`).join('');
  });
}
function createRun(){
  const period=document.getElementById('runPeriod').value;
  if(!period){alert('Pick a month.');return;}
  const fd=new FormData();fd.append('action','create_run');fd.append('period',period);
  fetch('ajax/api.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{alert(d.message);if(d.success){loadRuns();viewRun(d.run_id);}});
}
function viewRun(id){
  new bootstrap.Modal(document.getElementById('runModal')).show();
  document.getElementById('runBody').innerHTML='Loading…';
  fetch(`ajax/api.php?action=get_run&id=${id}`).then(r=>r.json()).then(d=>{
    if(!d.success){document.getElementById('runBody').innerHTML='<div class="text-danger">'+esc(d.message)+'</div>';return;}
    document.getElementById('runTitle').textContent='Payroll — '+d.run.period+' ('+d.run.status+')';
    const rows=d.items.map(i=>`<tr>
      <td>${esc(i.staff_name)}</td><td>${money(i.basic)}</td><td>${money(i.allowances)}</td><td>${money(i.gross)}</td>
      <td>${money(i.ssnit_employee)}</td><td>${money(i.paye)}</td><td>${money(i.other_deductions)}</td>
      <td class="fw-semibold">${money(i.net)}</td>
      <td><a class="btn btn-xs btn-outline-primary btn-sm py-0" target="_blank" href="payslip.php?item_id=${i.id}"><i class="fas fa-file-invoice"></i></a></td>
    </tr>`).join('');
    const t=d.totals;
    document.getElementById('runBody').innerHTML=`
      <div class="table-responsive"><table class="table table-sm">
        <thead class="table-light"><tr><th>Staff</th><th>Basic</th><th>Allow.</th><th>Gross</th><th>SSNIT</th><th>PAYE</th><th>Other</th><th>Net</th><th>Payslip</th></tr></thead>
        <tbody>${rows||'<tr><td colspan="9" class="text-center text-muted">No staff. Set up staff pay first.</td></tr>'}</tbody>
        <tfoot class="table-light fw-semibold"><tr><td>Totals</td><td></td><td></td><td>${money(t.gross)}</td><td>${money(t.ssnit_employee)}</td><td>${money(t.paye)}</td><td></td><td>${money(t.net)}</td><td></td></tr></tfoot>
      </table></div>
      <div class="d-flex gap-2">
        ${d.run.status==='draft'?`<button class="btn btn-primary btn-sm" onclick="finalizeRun(${d.run.id})"><i class="fas fa-lock me-1"></i>Finalize</button>
         <button class="btn btn-outline-danger btn-sm" onclick="deleteRun(${d.run.id})">Delete draft</button>`:'<span class="text-muted small">This run is finalized and locked.</span>'}
        <span class="ms-auto small text-muted">Employer SSNIT (13%): GHS ${money(t.ssnit_employer)}</span>
      </div>`;
  });
}
function finalizeRun(id){ if(!confirm('Finalize and lock this run?'))return;
  const fd=new FormData();fd.append('action','finalize_run');fd.append('id',id);
  fetch('ajax/api.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{alert(d.message);if(d.success){viewRun(id);loadRuns();}}); }
function deleteRun(id){ if(!confirm('Delete this draft run?'))return;
  const fd=new FormData();fd.append('action','delete_run');fd.append('id',id);
  fetch('ajax/api.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{alert(d.message);if(d.success){bootstrap.Modal.getInstance(document.getElementById('runModal')).hide();loadRuns();}}); }

function loadPay(){
  fetch('ajax/api.php?action=staff_pay_list').then(r=>r.json()).then(d=>{
    const b=document.getElementById('payBody');
    if(!d.data.length){b.innerHTML='<tr><td colspan="7" class="text-center text-muted py-3">No staff found.</td></tr>';return;}
    b.innerHTML=d.data.map(s=>{const c=s.computed;return `<tr>
      <td>${esc(s.full_name)}</td><td>${money(c.basic)}</td><td>${money(c.allowances)}</td>
      <td>${money(c.ssnit_employee)}</td><td>${money(c.paye)}</td><td class="fw-semibold">${money(c.net)}</td>
      <td><button class="btn btn-sm btn-outline-primary" onclick='editPay(${JSON.stringify(s)})'><i class="fas fa-pen"></i></button></td>
    </tr>`;}).join('');
  });
}
function editPay(s){
  document.getElementById('pay_staff_id').value=s.id;
  document.getElementById('payTitle').textContent='Pay — '+s.full_name;
  pay_basic.value=s.basic_salary||0; pay_tr.value=s.transport_allowance||0; pay_ho.value=s.housing_allowance||0;
  pay_oa.value=s.other_allowance||0; pay_od.value=s.other_deductions||0; pay_relief.value=s.tax_relief||0;
  pay_exempt.checked=(s.ssnit_exempt==1);
  updatePreview();
  new bootstrap.Modal(document.getElementById('payModal')).show();
}
['pay_basic','pay_tr','pay_ho','pay_oa','pay_od','pay_relief','pay_exempt'].forEach(id=>{
  document.addEventListener('input',e=>{if(e.target.id===id)updatePreview();});
});
function updatePreview(){
  // client-side mirror of the server formula for instant feedback
  const basic=+pay_basic.value||0, allow=(+pay_tr.value||0)+(+pay_ho.value||0)+(+pay_oa.value||0);
  const gross=basic+allow, ssnit=pay_exempt.checked?0:+(basic*0.055).toFixed(2);
  const taxable=Math.max(0,gross-ssnit-(+pay_relief.value||0));
  const bands=[[490,0],[110,.05],[130,.10],[3166.67,.175],[16000,.25],[30520,.30],[null,.35]];
  let left=taxable,paye=0; for(const[w,r]of bands){if(left<=0)break;const s=(w===null)?left:Math.min(left,w);paye+=s*r;left-=s;}
  paye=+paye.toFixed(2);
  const net=+(gross-ssnit-paye-(+pay_od.value||0)).toFixed(2);
  document.getElementById('payPreview').innerHTML=`Gross <b>${money(gross)}</b> · SSNIT <b>${money(ssnit)}</b> · PAYE <b>${money(paye)}</b> · Net <b>${money(net)}</b>`;
}
document.getElementById('payForm').addEventListener('submit',function(e){
  e.preventDefault();
  const fd=new FormData();fd.append('action','save_pay');
  fd.append('staff_id',pay_staff_id.value);fd.append('basic_salary',pay_basic.value);
  fd.append('transport_allowance',pay_tr.value);fd.append('housing_allowance',pay_ho.value);
  fd.append('other_allowance',pay_oa.value);fd.append('other_deductions',pay_od.value);
  fd.append('tax_relief',pay_relief.value);if(pay_exempt.checked)fd.append('ssnit_exempt','1');
  fetch('ajax/api.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    if(d.success){bootstrap.Modal.getInstance(document.getElementById('payModal')).hide();loadPay();}else alert(d.message);
  });
});
loadRuns();
</script>
</body>
</html>
