<?php use App\Helpers\Helper; ?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="admin-page-title mb-1">Expenses</h1>
    <p class="text-muted small mb-0">Track and manage all property expenses</p>
  </div>
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addExpenseModal">
    <i class="bi bi-plus-lg me-2"></i>Add Expense
  </button>
</div>

<!-- Stats -->
<?php
$pending  = array_filter($expenses, fn($e)=>$e['status']==='pending');
$approved = array_filter($expenses, fn($e)=>$e['status']==='approved');
$rejected = array_filter($expenses, fn($e)=>$e['status']==='rejected');
$totalPending = array_sum(array_column($pending,'amount'));
?>
<div class="row g-3 mb-4">
  <div class="col-md-3">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap red"><i class="bi bi-cash-stack"></i></div>
      <div><div class="stat-val" style="font-size:1.1rem"><?= Helper::money($total) ?></div><div class="stat-lbl">Total Approved</div></div>
    </div>
  </div>
  <div class="col-md-3">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap green"><i class="bi bi-check-circle"></i></div>
      <div><div class="stat-val"><?= count($approved) ?></div><div class="stat-lbl">Approved</div></div>
    </div>
  </div>
  <div class="col-md-3">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap orange"><i class="bi bi-clock"></i></div>
      <div><div class="stat-val"><?= count($pending) ?></div><div class="stat-lbl">Pending</div></div>
    </div>
  </div>
  <div class="col-md-3">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap blue"><i class="bi bi-building"></i></div>
      <div><div class="stat-val"><?= count($expenses) ?></div><div class="stat-lbl">Total Records</div></div>
    </div>
  </div>
</div>

<!-- Filter & Search -->
<div class="data-card mb-4">
  <div class="p-3">
    <div class="row g-2 align-items-end">
      <div class="col-md-3">
        <label class="form-label fw-600 small">Property</label>
        <select id="filterProperty" class="form-select form-select-sm" onchange="filterTable()">
          <option value="">All Properties</option>
          <?php foreach ($properties as $p): ?>
          <option value="<?= Helper::e($p['name']) ?>"><?= Helper::e($p['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label fw-600 small">Status</label>
        <select id="filterStatus" class="form-select form-select-sm" onchange="filterTable()">
          <option value="">All Statuses</option>
          <option value="approved">Approved</option>
          <option value="pending">Pending</option>
          <option value="rejected">Rejected</option>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label fw-600 small">Search</label>
        <input type="text" id="expenseSearch" class="form-control form-control-sm" placeholder="Search category, vendor, description...">
      </div>
      <div class="col-md-2">
        <button class="btn btn-outline-secondary btn-sm w-100" onclick="clearFilters()"><i class="bi bi-x me-1"></i>Clear</button>
      </div>
    </div>
  </div>
</div>

<!-- Expenses Table -->
<div class="data-card">
  <div class="data-card-header">
    <h6><i class="bi bi-receipt me-2 text-primary"></i>Expense Records <span class="badge bg-primary ms-2"><?= count($expenses) ?></span></h6>
  </div>
  <div class="table-responsive">
    <table class="table mb-0" id="expensesTable">
      <thead>
        <tr>
          <th>#</th>
          <th>Date</th>
          <th>Category</th>
          <th>Description</th>
          <th>Property</th>
          <th>Vendor</th>
          <th>Amount</th>
          <th>Status</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($expenses as $i => $e): ?>
        <tr>
          <td class="text-muted small"><?= $i + 1 ?></td>
          <td class="small"><?= Helper::date($e['expense_date']) ?></td>
          <td>
            <?php
              $catColors = ['rent'=>'primary','utilities'=>'info','maintenance'=>'warning','salary'=>'success','supplies'=>'secondary','other'=>'dark'];
              $cc = $catColors[strtolower($e['category'])] ?? 'secondary';
            ?>
            <span class="badge bg-<?= $cc ?> text-white"><?= Helper::e($e['category']) ?></span>
          </td>
          <td class="small" style="max-width:200px">
            <span title="<?= Helper::e($e['description']) ?>"><?= Helper::e(mb_substr($e['description'],0,50)) ?><?= mb_strlen($e['description'])>50?'...':'' ?></span>
          </td>
          <td class="small"><?= Helper::e($e['property_name'] ?? '—') ?></td>
          <td class="small text-muted"><?= Helper::e($e['vendor'] ?? '—') ?></td>
          <td class="fw-700 text-danger"><?= Helper::money($e['amount']) ?></td>
          <td><?= Helper::statusBadge($e['status']) ?></td>
          <td>
            <div class="d-flex gap-1">
              <button class="btn btn-action btn-outline-primary" title="Edit"
                onclick="openEdit(<?= htmlspecialchars(json_encode($e), ENT_QUOTES) ?>)"
              ><i class="bi bi-pencil"></i></button>
              <form method="POST" action="<?= APP_URL ?>/admin/expenses/<?= $e['id'] ?>/delete" class="d-inline"
                onsubmit="return confirm('Delete this expense?')">
                <?= Helper::csrf() ?>
                <button class="btn btn-action btn-outline-danger" title="Delete"><i class="bi bi-trash"></i></button>
              </form>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($expenses)): ?>
        <tr><td colspan="9" class="text-center py-5 text-muted">
          <i class="bi bi-receipt fs-1 d-block mb-2 opacity-25"></i>No expenses recorded yet.
        </td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Add Expense Modal -->
<div class="modal fade" id="addExpenseModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header" style="background:linear-gradient(135deg,#1a3c5e,#2d6a9f);color:#fff">
        <h5 class="modal-title fw-700"><i class="bi bi-plus-circle me-2"></i>Add Expense</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?= APP_URL ?>/admin/expenses" enctype="multipart/form-data">
        <?= Helper::csrf() ?>
        <div class="modal-body p-4">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label fw-600">Category <span class="text-danger">*</span></label>
              <select name="category" class="form-select" required>
                <option value="">— Select Category —</option>
                <?php foreach (['Rent','Utilities','Maintenance','Salary','Supplies','Insurance','Taxes','Marketing','Repairs','Security','Cleaning','Other'] as $cat): ?>
                <option value="<?= $cat ?>"><?= $cat ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Property</label>
              <select name="property_id" class="form-select">
                <option value="">— General (All Properties) —</option>
                <?php foreach ($properties as $p): ?>
                <option value="<?= $p['id'] ?>"><?= Helper::e($p['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Amount (TZS) <span class="text-danger">*</span></label>
              <input type="number" name="amount" class="form-control" min="0" step="0.01" required placeholder="e.g. 150000">
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Expense Date <span class="text-danger">*</span></label>
              <input type="date" name="expense_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Vendor / Supplier</label>
              <input type="text" name="vendor" class="form-control" placeholder="e.g. TANESCO, DAWASCO">
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Receipt / Document</label>
              <input type="file" name="receipt" class="form-control" accept=".pdf,.jpg,.jpeg,.png">
            </div>
            <div class="col-12">
              <label class="form-label fw-600">Description <span class="text-danger">*</span></label>
              <textarea name="description" class="form-control" rows="2" required placeholder="Brief description of the expense..."></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer bg-light">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary px-4"><i class="bi bi-save me-2"></i>Save Expense</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Expense Modal -->
<div class="modal fade" id="editExpenseModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header" style="background:linear-gradient(135deg,#1a3c5e,#2d6a9f);color:#fff">
        <h5 class="modal-title fw-700"><i class="bi bi-pencil me-2"></i>Edit Expense</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" id="editExpenseForm" enctype="multipart/form-data">
        <?= Helper::csrf() ?>
        <div class="modal-body p-4">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label fw-600">Category <span class="text-danger">*</span></label>
              <select name="category" id="edit_category" class="form-select" required>
                <?php foreach (['Rent','Utilities','Maintenance','Salary','Supplies','Insurance','Taxes','Marketing','Repairs','Security','Cleaning','Other'] as $cat): ?>
                <option value="<?= $cat ?>"><?= $cat ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Amount (TZS) <span class="text-danger">*</span></label>
              <input type="number" name="amount" id="edit_amount" class="form-control" required>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Expense Date</label>
              <input type="date" name="expense_date" id="edit_expense_date" class="form-control">
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Status</label>
              <select name="status" id="edit_status" class="form-select">
                <option value="approved">Approved</option>
                <option value="pending">Pending</option>
                <option value="rejected">Rejected</option>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label fw-600">Description</label>
              <textarea name="description" id="edit_description" class="form-control" rows="2"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer bg-light">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary px-4"><i class="bi bi-save me-2"></i>Update Expense</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function openEdit(e) {
  document.getElementById('editExpenseForm').action = '<?= APP_URL ?>/admin/expenses/' + e.id;
  document.getElementById('edit_category').value    = e.category;
  document.getElementById('edit_amount').value      = e.amount;
  document.getElementById('edit_expense_date').value= e.expense_date;
  document.getElementById('edit_status').value      = e.status;
  document.getElementById('edit_description').value = e.description;
  new bootstrap.Modal(document.getElementById('editExpenseModal')).show();
}

function filterTable() {
  const prop   = document.getElementById('filterProperty').value.toLowerCase();
  const status = document.getElementById('filterStatus').value.toLowerCase();
  const search = document.getElementById('expenseSearch').value.toLowerCase();
  document.querySelectorAll('#expensesTable tbody tr').forEach(row => {
    const text = row.textContent.toLowerCase();
    const matchProp   = !prop   || text.includes(prop);
    const matchStatus = !status || text.includes(status);
    const matchSearch = !search || text.includes(search);
    row.style.display = (matchProp && matchStatus && matchSearch) ? '' : 'none';
  });
}

function clearFilters() {
  document.getElementById('filterProperty').value = '';
  document.getElementById('filterStatus').value   = '';
  document.getElementById('expenseSearch').value  = '';
  filterTable();
}

document.getElementById('expenseSearch').addEventListener('input', filterTable);
</script>
