<?php
/** Approvals inbox — act on requests awaiting your role, then disburse. */
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }

require_once '../config.php';
requireModule('finance_suite');
require_once __DIR__ . '/inc/finance_lib.php';
require_once __DIR__ . '/inc/layout.php';

$conn = getDBConnection();
finance_ensure_tables($conn);
$base = defined('BASE_URL') ? rtrim(BASE_URL, '/') : '';

finance_page_header('Approvals Inbox', 'approvals');
?>
<div class="fin-card p-0 mb-4">
    <div class="p-3 border-bottom"><h6 class="mb-0"><i class="fas fa-hourglass-half text-warning me-2"></i>Awaiting your approval</h6></div>
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light"><tr><th>Request #</th><th>Requester</th><th>Category</th><th>Amount</th><th>Stage</th><th>Action</th></tr></thead>
            <tbody id="pendingBody"><tr><td colspan="6" class="text-center text-muted py-4">Loading…</td></tr></tbody>
        </table>
    </div>
</div>

<div class="fin-card p-0" id="readyCard" style="display:none">
    <div class="p-3 border-bottom"><h6 class="mb-0"><i class="fas fa-money-check-dollar text-primary me-2"></i>Approved — ready to disburse</h6></div>
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light"><tr><th>Request #</th><th>Requester</th><th>Category</th><th>Amount</th><th>Action</th></tr></thead>
            <tbody id="readyBody"></tbody>
        </table>
    </div>
</div>

<!-- Decision modal -->
<div class="modal fade" id="decideModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title" id="decideTitle">Review request</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <div id="decideInfo" class="mb-3"></div>
        <label class="form-label small">Comment (optional)</label>
        <textarea class="form-control" id="decideComment" rows="2"></textarea>
        <input type="hidden" id="decideId">
    </div>
    <div class="modal-footer">
        <button class="btn btn-outline-danger" onclick="decide('rejected')"><i class="fas fa-times me-1"></i>Reject</button>
        <button class="btn btn-success" onclick="decide('approved')"><i class="fas fa-check me-1"></i>Approve</button>
    </div>
</div></div></div>

<script>
const BASE="<?= $base ?>";
function esc(s){const d=document.createElement('div');d.textContent=s==null?'':s;return d.innerHTML;}
function money(n){return 'GHS '+Number(n).toLocaleString(undefined,{minimumFractionDigits:2});}

function loadInbox(){
  fetch('ajax/approvals.php?action=inbox').then(r=>r.json()).then(d=>{
    const pb=document.getElementById('pendingBody');
    pb.innerHTML=d.pending.length?d.pending.map(r=>`<tr>
      <td class="fw-semibold">${esc(r.request_no)}</td><td>${esc(r.requester_name)}</td>
      <td>${esc(r.category)}</td><td>${money(r.amount)}</td>
      <td class="small text-muted">${esc(r.step_label)}</td>
      <td><button class="btn btn-sm btn-success" onclick='openDecide(${JSON.stringify(r)})'>Review</button></td>
    </tr>`).join(''):'<tr><td colspan="6" class="text-center text-muted py-4">Nothing awaiting you. 🎉</td></tr>';

    if(d.ready && d.ready.length){
      document.getElementById('readyCard').style.display='';
      document.getElementById('readyBody').innerHTML=d.ready.map(r=>`<tr>
        <td class="fw-semibold">${esc(r.request_no)}</td><td>${esc(r.requester_name)}</td>
        <td>${esc(r.category)}</td><td>${money(r.amount)}</td>
        <td><button class="btn btn-sm btn-primary" onclick="disburse(${r.id})"><i class="fas fa-check me-1"></i>Disburse</button></td>
      </tr>`).join('');
    } else { document.getElementById('readyCard').style.display='none'; }
  });
}

function openDecide(r){
  document.getElementById('decideId').value=r.id;
  document.getElementById('decideComment').value='';
  document.getElementById('decideTitle').textContent='Review '+r.request_no;
  document.getElementById('decideInfo').innerHTML=`
    <table class="table table-sm mb-0"><tbody>
      <tr><th style="width:35%">Amount</th><td class="fw-bold">${money(r.amount)}</td></tr>
      <tr><th>Category</th><td>${esc(r.category)}</td></tr>
      <tr><th>Description</th><td>${esc(r.description)}</td></tr>
      <tr><th>Vendor</th><td>${esc(r.vendor||'—')}</td></tr>
      <tr><th>Requester</th><td>${esc(r.requester_name)}</td></tr>
    </tbody></table>`;
  new bootstrap.Modal(document.getElementById('decideModal')).show();
}

function decide(decision){
  const id=document.getElementById('decideId').value;
  const comment=document.getElementById('decideComment').value;
  const fd=new FormData();fd.append('action','decide');fd.append('id',id);fd.append('decision',decision);fd.append('comment',comment);
  fetch('ajax/approvals.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    alert(d.message);
    if(d.success){bootstrap.Modal.getInstance(document.getElementById('decideModal')).hide();loadInbox();}
  });
}
function disburse(id){
  if(!confirm('Post this request to the expense ledger?'))return;
  const fd=new FormData();fd.append('action','disburse');fd.append('id',id);
  fetch('ajax/approvals.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{alert(d.message);if(d.success)loadInbox();});
}
loadInbox();
</script>
<?php finance_page_footer(); ?>
