<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-expenditures">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Expenditure Management</h4>
      <div>
        <button id="btnExpReports" class="btn btn-outline-secondary me-2"><i class="bi bi-graph-up"></i> Reports</button>
        <button id="btnExpCategories" class="btn btn-outline-secondary me-2"><i class="bi bi-tags"></i> Categories</button>
        <button id="btnAddExpenditure" class="btn btn-primary"><i class="bi bi-plus"></i> Add Expenditure</button>
      </div>
    </div>

  <!-- Expenditure Reports Modal -->
  <div class="modal fade" id="expReportModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Expenditure Reports</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="row g-2 align-items-end mb-3">
            <div class="col-md-3">
              <label class="form-label">Period</label>
              <select id="expRepPeriod" class="form-select">
                <option value="day">Daily</option>
                <option value="week">Weekly</option>
                <option value="month" selected>Monthly</option>
                <option value="year">Yearly</option>
              </select>
            </div>
            <div class="col-md-3">
              <label class="form-label">From</label>
              <input type="date" id="expRepFrom" class="form-control">
            </div>
            <div class="col-md-3">
              <label class="form-label">To</label>
              <input type="date" id="expRepTo" class="form-control">
            </div>
            <div class="col-md-3">
              <label class="form-label">Category</label>
              <select id="expRepCategory" class="form-select"><option value="">All</option></select>
            </div>
            <?php if (has_role(['admin','super_admin'])): ?>
            <div class="col-md-3">
              <label class="form-label">Branch</label>
              <select id="expRepBranch" class="form-select"><option value="">All</option></select>
            </div>
            <?php endif; ?>
            <div class="col-md-3 d-flex gap-2">
              <button class="btn btn-primary" id="btnExpRepRun"><i class="bi bi-play"></i> Run</button>
              <button class="btn btn-outline-secondary" id="btnExpRepPrint"><i class="bi bi-printer"></i> Print</button>
              <button class="btn btn-outline-success" id="btnExpRepExport"><i class="bi bi-file-earmark-excel"></i> Export</button>
            </div>
          </div>
          <div class="table-responsive border rounded">
            <table class="table table-sm" id="expRepTable">
              <thead class="table-light"><tr><th>Bucket</th><th>Category</th><th class="text-end">Total (LKR)</th></tr></thead>
              <tbody></tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

<?php if (has_role(['admin','super_admin'])): ?>
<script>
(function(){
  if (!$('.page-expenditures').length) return;
  // Load branches into Branch filter for admins
  $.get('api/branches.php',{ action:'list' }, function(res){
    const $sel = $('#expBranchFilter'); if(!$sel.length) return; $sel.empty();
    $sel.append('<option value="">All</option>');
    (res.data||[]).forEach(b=>{ if (parseInt(b.is_active)) $sel.append(`<option value="${b.id}">${$('<div>').text(b.name||'').html()}</option>`); });
  });
})();
</script>
<?php endif; ?>

    <div class="row g-3 mb-3">
      <div class="col-md-3">
        <div class="card shadow-sm"><div class="card-body"><div class="text-muted small">Today's Expenses</div><div id="exp_today_total" class="fs-5">LKR 0.00</div></div></div>
      </div>
      <div class="col-md-3">
        <div class="card shadow-sm"><div class="card-body"><div class="text-muted small">This Month</div><div id="exp_month_total" class="fs-5">LKR 0.00</div></div></div>
      </div>
      <div class="col-md-3">
        <div class="card shadow-sm"><div class="card-body"><div class="text-muted small">This Year</div><div id="exp_year_total" class="fs-5">LKR 0.00</div></div></div>
      </div>
      <div class="col-md-3">
        <div class="card shadow-sm"><div class="card-body"><div class="text-muted small">Daily Average</div><div id="exp_daily_avg" class="fs-5">LKR 0.00</div></div></div>
      </div>
      <div class="col-md-3">
        <div class="card shadow-sm"><div class="card-body"><div class="text-muted small">Filter Amount</div><div id="exp_filter_total" class="fs-5">LKR 0.00</div></div></div>
      </div>
    </div>

    <div class="card shadow-sm mb-3">
      <div class="card-body">
        <div class="row g-2 align-items-end">
          <div class="col-md-3">
            <label class="form-label">Search</label>
            <input type="text" id="expSearch" class="form-control" placeholder="Description, vendor, invoice...">
          </div>
          <div class="col-md-2">
            <label class="form-label">Category</label>
            <select id="expCategoryFilter" class="form-select"><option value="">All Categories</option></select>
          </div>
          <div class="col-md-2">
            <label class="form-label">From Date</label>
            <input type="date" id="expFromDate" class="form-control">
          </div>
          <div class="col-md-2">
            <label class="form-label">To Date</label>
            <input type="date" id="expToDate" class="form-control">
          </div>
          <?php if (has_role(['admin','super_admin'])): ?>
          <div class="col-md-2">
            <label class="form-label">Branch</label>
            <select id="expBranchFilter" class="form-select"><option value="">All</option></select>
          </div>
          <?php endif; ?>
          <div class="col-md-3 d-flex gap-2">
            <button class="btn btn-primary" id="btnExpSearch"><i class="bi bi-search"></i> Search</button>
            <button class="btn btn-outline-secondary" id="btnExpClear">Clear</button>
          </div>
        </div>
      </div>
    </div>

    <div class="card shadow-sm">
      <div class="card-body">
        <div class="table-responsive">
          <table id="exp-table" class="table table-hover align-middle">
            <thead>
              <tr>
                <th>Date</th>
                <th>Category</th>
                <th>Description</th>
                <th>Vendor</th>
                <th>Amount</th>
                <th>Payment</th>
                <th>Invoice</th>
                <th>Receipt/Bill</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <input type="hidden" id="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>" />
  <input type="hidden" id="basePath" value="<?php echo htmlspecialchars(BASE_PATH); ?>" />

  <div class="modal fade" id="expModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header bg-primary text-white">
          <h5 class="modal-title">Expenditure Details</h5>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form id="expForm" enctype="multipart/form-data">
          <div class="modal-body">
            <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
            <input type="hidden" name="id" id="expId">
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">Category <span class="text-danger">*</span></label>
                <select class="form-select" name="category_id" id="exp_category_id" required></select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Expense Date <span class="text-danger">*</span></label>
                <input type="date" class="form-control" name="expense_date" id="exp_date" required>
              </div>
              <div class="col-12">
                <label class="form-label">Description <span class="text-danger">*</span></label>
                <input type="text" class="form-control" name="description" id="exp_description" placeholder="Brief description" required>
              </div>
              <div class="col-md-4">
                <label class="form-label">Amount (LKR) <span class="text-danger">*</span></label>
                <input type="number" step="0.01" class="form-control" name="amount" id="exp_amount" required>
              </div>
              <div class="col-md-4">
                <label class="form-label">Payment Method <span class="text-danger">*</span></label>
                <select class="form-select" name="payment_method" id="exp_payment" required></select>
              </div>
              <div class="col-md-4">
                <label class="form-label">Vendor/Supplier</label>
                <input type="text" class="form-control" name="vendor" id="exp_vendor" placeholder="Vendor or supplier name">
              </div>
              <div class="col-md-6">
                <label class="form-label">Invoice/Bill Number</label>
                <input type="text" class="form-control" name="invoice_no" id="exp_invoice">
              </div>
              <div class="col-md-6">
                <label class="form-label">Receipt/Bill Upload</label>
                <input type="file" class="form-control" name="receipt" id="exp_receipt" accept="image/*,.pdf,.doc,.docx">
                <div class="form-text">Upload receipt (JPG, PNG, PDF, DOC)</div>
              </div>
              <div class="col-12">
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" value="1" id="exp_recurring" name="is_recurring">
                  <label class="form-check-label" for="exp_recurring">This is a recurring expense</label>
                </div>
              </div>
              <div class="col-12">
                <label class="form-label">Notes</label>
                <textarea class="form-control" name="notes" id="exp_notes" rows="3"></textarea>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Save</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <div class="modal fade" id="expCatModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog  modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Expenditure Categories</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="input-group mb-2">
            <input type="text" class="form-control" id="expCatName" placeholder="New category name">
            <button class="btn btn-primary" id="btnAddExpCat">Add</button>
          </div>
          <div class="table-responsive">
            <table class="table table-sm align-middle" id="exp-cat-table">
              <thead><tr><th style="width:60px;">ID</th><th>Name</th><th style="width:100px;">Active</th><th style="width:150px;">Actions</th></tr></thead>
              <tbody></tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>
</div>
