<?php
require_once __DIR__ . '/../../admin/_nav.php';
require_once VIEWS . '/accountant/_nav.php';
$pageTitle  = 'Local Purchase Orders';
$_role = \Core\Session::get('user')['role'] ?? '';
$sidebarNav = $_role === 'accountant' ? accountantNav() : adminNav();
$u = function($p) { return \Core\View::url($p); };
$statusColors = ['draft'=>'#6b7280','approved'=>'#3b82f6','delivered'=>'#f59e0b','paid'=>'#10b981','cancelled'=>'#ef4444'];
$statusBadge  = ['draft'=>'badge-gray','approved'=>'badge-info','delivered'=>'badge-warning','paid'=>'badge-success','cancelled'=>'badge-danger'];
?>
<div class="page-header">
  <div><h1><i class="bi bi-file-earmark-text"></i> Local Purchase Orders (LPOs)</h1><p>Procurement tracking</p></div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <a href="<?= $u('admin/finance') ?>" class="btn btn-secondary"><i class="bi bi-speedometer2"></i> Dashboard</a>
    <a href="<?= $u('admin/fees/voteheads') ?>" class="btn btn-secondary"><i class="bi bi-diagram-3"></i> Vote Heads</a>
    <button onclick="openModal('addLpo')" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Create LPO</button>
  </div>
</div>

<!-- Status Filter -->
<div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap">
  <?php foreach([''=>'All','draft'=>'Draft','approved'=>'Approved','delivered'=>'Delivered','paid'=>'Paid','cancelled'=>'Cancelled'] as $sv=>$sl):
    $active = ($status??'')===$sv; ?>
  <a href="?status=<?= $sv ?>" style="padding:6px 14px;border-radius:20px;font-size:13px;font-weight:500;text-decoration:none;border:2px solid <?= $statusColors[$sv]??'var(--gray)' ?>;color:<?= $active?'#fff':($statusColors[$sv]??'var(--gray)') ?>;background:<?= $active?($statusColors[$sv]??'var(--gray)'):'transparent' ?>">
    <?= $sl ?>
  </a>
  <?php endforeach; ?>
</div>

<div class="card">
  <div class="table-wrap"><table>
    <thead><tr><th>LPO No.</th><th>Vendor</th><th>Description</th><th>Vote Head</th><th>Amount</th><th>Issue Date</th><th>Delivery</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
      <?php foreach($lpos['data'] as $lpo): ?>
      <tr>
        <td><strong style="color:var(--primary)"><?= htmlspecialchars($lpo['lpo_number']) ?></strong></td>
        <td>
          <div style="font-weight:500"><?= htmlspecialchars($lpo['vendor']) ?></div>
          <?php if($lpo['created_by_name']): ?><div style="font-size:11px;color:var(--gray)">By: <?= htmlspecialchars($lpo['created_by_name']) ?></div><?php endif; ?>
        </td>
        <td style="max-width:200px;font-size:13px"><?= htmlspecialchars($lpo['description']) ?></td>
        <td style="font-size:12px;color:var(--gray)"><?= htmlspecialchars($lpo['vote_head_name']??'—') ?></td>
        <td><strong>KES <?= number_format($lpo['amount'],2) ?></strong></td>
        <td style="font-size:12px"><?= $lpo['issue_date'] ?></td>
        <td style="font-size:12px"><?= $lpo['delivery_date']??'—' ?></td>
        <td><span class="badge <?= $statusBadge[$lpo['status']]??'badge-gray' ?>"><?= ucfirst($lpo['status']) ?></span></td>
        <td style="white-space:nowrap">
          <?php if($lpo['status']!=='paid' && $lpo['status']!=='cancelled'): ?>
          <button onclick="openStatusModal(<?= $lpo['id'] ?>, '<?= $lpo['status'] ?>')" class="btn btn-sm btn-secondary" title="Update Status"><i class="bi bi-arrow-repeat"></i></button>
          <?php endif; ?>
          <form method="POST" action="<?= $u('admin/fees/lpos/'.$lpo['id'].'/delete') ?>" style="display:inline" onsubmit="return confirm('Delete this LPO?')">
            <?= \Core\View::csrf() ?>
            <button type="submit" class="btn btn-sm btn-danger" title="Delete"><i class="bi bi-trash"></i></button>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php if(empty($lpos['data'])): ?><tr><td colspan="9" style="text-align:center;padding:40px;color:var(--gray)"><i class="bi bi-file-earmark" style="font-size:32px"></i><p style="margin-top:8px">No LPOs found</p></td></tr><?php endif; ?>
    </tbody>
  </table></div>
  <div style="padding:14px"><?= \Core\View::paginate($lpos, $u('admin/fees/lpos')) ?></div>
</div>

<!-- Create LPO Modal -->
<div class="modal" id="addLpo"><div class="modal-box" style="max-width:560px">
  <div class="card-header"><h5>Create LPO</h5><button onclick="closeModal('addLpo')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body"><form method="POST" action="<?= $u('admin/fees/lpos/store') ?>">
    <?= \Core\View::csrf() ?>
    <div class="grid g2">
      <div class="form-group" style="grid-column:span 2"><label>Vendor / Supplier *</label><input type="text" name="vendor" required placeholder="e.g. ABC Suppliers Ltd"></div>
      <div class="form-group" style="grid-column:span 2"><label>Description *</label><textarea name="description" required rows="2" placeholder="Items/services being procured"></textarea></div>
      <div class="form-group"><label>Amount (KES) *</label><input type="number" name="amount" min="0" step="0.01" required></div>
      <div class="form-group"><label>Issue Date *</label><input type="date" name="issue_date" value="<?= date('Y-m-d') ?>" required></div>
      <div class="form-group"><label>Expected Delivery</label><input type="date" name="delivery_date"></div>
      <div class="form-group"><label>Vote Head</label>
        <select name="vote_head_id">
          <option value="">None</option>
          <?php foreach($voteHeads as $vh): ?><option value="<?= $vh['id'] ?>"><?= htmlspecialchars($vh['code'].' - '.$vh['name']) ?></option><?php endforeach; ?>
        </select>
      </div>
    </div>
    <div class="form-group"><label>Notes</label><textarea name="notes" rows="2"></textarea></div>
    <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Create LPO</button>
  </form></div>
</div></div>

<!-- Update Status Modal -->
<div class="modal" id="statusModal"><div class="modal-box" style="max-width:380px">
  <div class="card-header"><h5>Update LPO Status</h5><button onclick="closeModal('statusModal')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body"><form method="POST" id="statusForm" action="">
    <?= \Core\View::csrf() ?>
    <div class="form-group"><label>New Status *</label>
      <select name="status" id="statusSelect" required>
        <option value="draft">Draft</option>
        <option value="approved">Approved</option>
        <option value="delivered">Delivered</option>
        <option value="paid">Paid</option>
        <option value="cancelled">Cancelled</option>
      </select>
    </div>
    <button type="submit" class="btn btn-primary">Update Status</button>
  </form></div>
</div></div>

<?php
$lpoBase = $u('admin/fees/lpos/');
$extraScripts = '<script>
function openStatusModal(id, currentStatus){
  document.getElementById("statusForm").action="'.$lpoBase.'"+id+"/status";
  document.getElementById("statusSelect").value=currentStatus;
  openModal("statusModal");
}
</script>';
?>

