<?php
/** Expenditure requests — submit and track. */
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, '/') : '';

// Open events for optional linking.
$openEvents = [];
$r = $conn->query("SELECT id, name FROM event_accounts WHERE status!='closed' ORDER BY name");
while ($r && $row = $r->fetch_assoc()) $openEvents[] = $row;

finance_page_header('Expenditure Requests', 'requests');
?>
<div class="d-flex justify-content-between align-items-center mb-3">
    <div class="btn-group btn-group-sm" role="group">
        <button class="btn btn-outline-secondary active" id="scopeMine">My requests</button>
        <button class="btn btn-outline-secondary" id="scopeAll" style="display:none">All requests</button>
    </div>
    <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#newReqModal">
        <i class="fas fa-plus me-1"></i>New Request
    </button>
</div>

<div class="fin-card p-0">
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light"><tr>
                <th>Request #</th><th>Date</th><th>Category</th><th>Amount</th><th>Status</th><th>Stage</th><th></th>
            </tr></thead>
            <tbody id="reqBody">
                <tr><td colspan="7" class="text-center text-muted py-4">Loading…</td></tr>
            </tbody>
        </table>
    </div>
</div>

<!-- New request modal -->
<div class="modal fade" id="newReqModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <form id="newReqForm" enctype="multipart/form-data">
        <div class="modal-header"><h5 class="modal-title"><i class="fas fa-file-invoice me-2"></i>New Expenditure Request</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
        <div class="modal-body">
            <input type="hidden" name="action" value="create">
            <div class="row g-2">
                <div class="col-6"><label class="form-label small">Date *</label>
                    <input type="date" class="form-control" name="expense_date" value="<?= date('Y-m-d') ?>" required></div>
                <div class="col-6"><label class="form-label small">Amount (GHS) *</label>
                    <input type="number" step="0.01" min="0.01" class="form-control" name="amount" required></div>
                <div class="col-6"><label class="form-label small">Category *</label>
                    <select class="form-select" name="category" required>
                        <option value="">Select…</option>
                        <?php foreach (['Supplies','Maintenance','Repairs','Utilities','Transport','Events','Equipment','Other'] as $c): ?>
                            <option><?= $c ?></option>
                        <?php endforeach; ?>
                    </select></div>
                <div class="col-6"><label class="form-label small">Payment method</label>
                    <select class="form-select" name="payment_method">
                        <option value="cash">Cash</option><option value="bank_transfer">Bank Transfer</option><option value="card">Card</option>
                    </select></div>
                <div class="col-12"><label class="form-label small">Description *</label>
                    <textarea class="form-control" name="description" rows="2" required></textarea></div>
                <div class="col-6"><label class="form-label small">Vendor</label>
                    <input type="text" class="form-control" name="vendor"></div>
                <div class="col-6"><label class="form-label small">Link to event</label>
                    <select class="form-select" name="event_id">
                        <option value="">— none —</option>
                        <?php foreach ($openEvents as $e): ?><option value="<?= (int)$e['id'] ?>"><?= htmlspecialchars($e['name']) ?></option><?php endforeach; ?>
                    </select></div>
                <div class="col-12"><label class="form-label small">Receipts (optional — JPG/PNG/PDF)</label>
                    <input type="file" class="form-control" name="receipts[]" accept="image/*,application/pdf" multiple></div>
            </div>
            <div class="alert alert-info small mt-3 mb-0"><i class="fas fa-info-circle me-1"></i>
                The request routes through the approval workflow automatically based on its amount.</div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-success" id="submitReqBtn">Submit Request</button>
        </div>
    </form>
</div></div></div>

<!-- Detail modal -->
<div class="modal fade" id="detailModal" tabindex="-1"><div class="modal-dialog modal-lg"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Request details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body" id="detailBody">Loading…</div>
</div></div></div>

<script>
const BASE = "<?= $base ?>";
let currentScope = 'mine';

function pill(status){
  const map={pending:'st-pending',approved:'st-approved',rejected:'st-rejected',disbursed:'st-disbursed'};
  return `<span class="status-pill ${map[status]||''}">${status}</span>`;
}
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 loadList(){
  fetch(`ajax/requests.php?action=list&scope=${currentScope}`).then(r=>r.json()).then(d=>{
    const b=document.getElementById('reqBody');
    if(d.can_see_all){document.getElementById('scopeAll').style.display='';}
    if(!d.success||!d.data.length){b.innerHTML='<tr><td colspan="7" class="text-center text-muted py-4">No requests.</td></tr>';return;}
    b.innerHTML=d.data.map(r=>`<tr>
      <td class="fw-semibold">${esc(r.request_no)}</td>
      <td>${esc(r.expense_date)}</td>
      <td>${esc(r.category)}</td>
      <td>${money(r.amount)}</td>
      <td>${pill(r.status)}</td>
      <td class="small text-muted">${esc(r.step_label||'')}</td>
      <td><button class="btn btn-sm btn-outline-secondary" onclick="viewReq(${r.id})"><i class="fas fa-eye"></i></button></td>
    </tr>`).join('');
  });
}

function viewReq(id){
  const m=new bootstrap.Modal(document.getElementById('detailModal'));
  document.getElementById('detailBody').innerHTML='Loading…';
  m.show();
  fetch(`ajax/requests.php?action=get&id=${id}`).then(r=>r.json()).then(d=>{
    if(!d.success){document.getElementById('detailBody').innerHTML='<div class="text-danger">'+esc(d.message)+'</div>';return;}
    const r=d.request;
    let steps=d.required.map((s,i)=>{
      let cls='text-muted', ic='fa-circle';
      if(r.status==='rejected'){}
      else if(i<r.current_step){cls='text-success';ic='fa-check-circle';}
      else if(i==r.current_step && r.status==='pending'){cls='text-warning fw-semibold';ic='fa-hourglass-half';}
      else if(r.status==='approved'||r.status==='disbursed'){cls='text-success';ic='fa-check-circle';}
      return `<span class="${cls} me-3"><i class="fas ${ic} me-1"></i>${esc(s.label)} (≥${money(s.min_amount)})</span>`;
    }).join('');
    let log=d.log.length?d.log.map(l=>`<li class="small"><b>${esc(l.approver_name)}</b> (${esc(l.approver_role)}) — <span class="${l.action==='approved'?'text-success':'text-danger'}">${l.action}</span> ${l.comment?('· '+esc(l.comment)):''} <span class="text-muted">${esc(l.created_at)}</span></li>`).join(''):'<li class="text-muted small">No actions yet.</li>';
    let recs=d.attachments.length?d.attachments.map(a=>{
      const url=BASE+'/'+a.file_path;
      const isImg=(a.mime||'').startsWith('image/');
      return `<a href="${url}" target="_blank" class="d-inline-block me-2 mb-2 text-center" style="width:84px">
        ${isImg?`<img src="${url}" style="width:84px;height:64px;object-fit:cover;border-radius:8px;border:1px solid #ddd">`:`<div style="width:84px;height:64px;border:1px solid #ddd;border-radius:8px;display:flex;align-items:center;justify-content:center;background:#f8f9fa"><i class="fas fa-file-pdf fa-2x text-danger"></i></div>`}
        <div class="small text-truncate" style="width:84px">${esc(a.original_name||'')}</div></a>`;
    }).join(''):'<span class="text-muted small">No receipts attached.</span>';
    document.getElementById('detailBody').innerHTML=`
      <div class="d-flex justify-content-between"><h5>${esc(r.request_no)} ${pill(r.status)}</h5><h5>${money(r.amount)}</h5></div>
      <table class="table table-sm"><tbody>
        <tr><th style="width:35%">Requested by</th><td>${esc(r.requester_name)}</td></tr>
        <tr><th>Date</th><td>${esc(r.expense_date)}</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>
      </tbody></table>
      <div class="mb-2"><b class="small text-uppercase text-muted">Approval chain</b><br>${steps}</div>
      <div class="mb-2"><b class="small text-uppercase text-muted">Receipts</b><br>${recs}
        <div class="mt-2"><input type="file" id="addRec" class="form-control form-control-sm d-inline-block" style="max-width:260px" accept="image/*,application/pdf">
          <button class="btn btn-sm btn-outline-success" onclick="uploadRec(${r.id})">Attach</button></div></div>
      <div><b class="small text-uppercase text-muted">Audit trail</b><ul class="mb-0">${log}</ul></div>`;
  });
}

function uploadRec(reqId){
  const f=document.getElementById('addRec').files[0];
  if(!f){alert('Choose a file first.');return;}
  const fd=new FormData();fd.append('action','upload');fd.append('request_id',reqId);fd.append('receipt',f);
  fetch('ajax/receipts.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    if(d.success){viewReq(reqId);}else{alert(d.message);}
  });
}

document.getElementById('newReqForm').addEventListener('submit',function(e){
  e.preventDefault();
  const btn=document.getElementById('submitReqBtn');btn.disabled=true;
  fetch('ajax/requests.php',{method:'POST',body:new FormData(this)}).then(r=>r.json()).then(d=>{
    btn.disabled=false;
    if(d.success){bootstrap.Modal.getInstance(document.getElementById('newReqModal')).hide();this.reset();loadList();
      alert(d.message);}
    else alert(d.message);
  }).catch(()=>{btn.disabled=false;alert('Request failed.');});
});
document.getElementById('scopeMine').addEventListener('click',function(){currentScope='mine';this.classList.add('active');document.getElementById('scopeAll').classList.remove('active');loadList();});
document.getElementById('scopeAll').addEventListener('click',function(){currentScope='all';this.classList.add('active');document.getElementById('scopeMine').classList.remove('active');loadList();});
loadList();
</script>
<?php finance_page_footer(); ?>
