<?php /* expenses/index.php */
$sym      = setting('currency_symbol','Rs.');
$data     = $pagination['data'];
$lastPage = $pagination['pages'];
$curPage  = $pagination['current'];
$perPage  = $pagination['perPage'];
$avgPerDay = $days > 0 ? round($totalAmt / $days, 2) : 0;
$maxBreak  = !empty($breakdown) ? max(array_column($breakdown,'total')) : 1;
?>

<style>
.exp-hero{background:linear-gradient(135deg,#450a0a,#dc2626 55%,#f97316);
  border-radius:12px;padding:20px 26px;color:#fff;margin-bottom:18px}
.kpi-pill{border-radius:10px;padding:12px 14px;text-align:center;height:100%}
.kpi-pill .val{font-size:1.3rem;font-weight:900;line-height:1}
.kpi-pill .lbl{font-size:.62rem;text-transform:uppercase;letter-spacing:.05em;margin-top:3px}
.exp-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.exp-table td{font-size:.78rem;padding:7px 10px;vertical-align:middle}
.exp-table tr:hover td{background:#fef2f2}
.cat-bar{height:8px;border-radius:4px;background:#fee2e2}
.cat-bar-fill{height:8px;border-radius:4px;background:linear-gradient(90deg,#dc2626,#f97316)}
</style>

<!-- Hero -->
<div class="exp-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <h5 class="fw-bold mb-1"><i class="bi bi-wallet2 me-2"></i>Expenses</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?=date('d M Y',strtotime($from))?> – <?=date('d M Y',strtotime($to))?>
        &nbsp;·&nbsp; <?=$totalCount?> records
        &nbsp;·&nbsp; Total: <strong><?=$sym?><?=number_format($totalAmt,2)?></strong>
        &nbsp;·&nbsp; Avg/day: <?=$sym?><?=number_format($avgPerDay,0)?>
      </div>
    </div>
    <div class="d-flex gap-2">
      <?php if(Auth::can('expenses.create')):?>
      <button class="btn btn-light btn-sm fw-semibold" style="color:#dc2626"
              data-bs-toggle="modal" data-bs-target="#addExpModal">
        <i class="bi bi-plus-circle me-1"></i>Add Expense
      </button>
      <?php endif;?>
      <button onclick="window.print()" class="btn btn-outline-light btn-sm">
        <i class="bi bi-printer me-1"></i>Print
      </button>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- KPI Pills -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fef2f2;border:2px solid #dc2626">
      <div class="val" style="color:#dc2626"><?=$sym?><?=number_format($totalAmt,0)?></div>
      <div class="lbl" style="color:#dc2626">Total Expenses</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fff7ed;border:2px solid #f97316">
      <div class="val" style="color:#f97316"><?=$totalCount?></div>
      <div class="lbl" style="color:#f97316">Transactions</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fef9c3;border:2px solid #d97706">
      <div class="val" style="color:#d97706"><?=$sym?><?=number_format($avgPerDay,0)?></div>
      <div class="lbl" style="color:#d97706">Average / Day</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#f0fdf4;border:2px solid #16a34a">
      <div class="val" style="color:#16a34a"><?=count($breakdown)?></div>
      <div class="lbl" style="color:#16a34a">Categories Used</div>
    </div>
  </div>
</div>

<div class="row g-3">

  <!-- Left: Expenses list -->
  <div class="col-lg-8">

    <!-- Filters -->
    <div class="card mb-3">
      <div class="card-body py-2">
        <form method="GET" action="<?=APP_URL?>/expenses"
              class="d-flex gap-2 flex-wrap align-items-end">
          <div class="d-flex gap-1 align-items-center">
            <input type="date" name="from" class="form-control form-control-sm"
                   value="<?=e($from)?>" style="width:135px">
            <span class="text-muted small">to</span>
            <input type="date" name="to" class="form-control form-control-sm"
                   value="<?=e($to)?>" style="width:135px">
          </div>
          <div class="input-group input-group-sm" style="max-width:180px">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" name="search" class="form-control"
                   placeholder="Title, reference…"
                   value="<?=e($search)?>">
          </div>
          <select name="category" class="form-select form-select-sm" style="max-width:150px">
            <option value="0">All Categories</option>
            <?php foreach($categories as $cat):?>
            <option value="<?=$cat['id']?>" <?=$catId==$cat['id']?'selected':''?>>
              <?=e($cat['category_name'])?>
            </option>
            <?php endforeach;?>
          </select>
          <button class="btn btn-secondary btn-sm fw-semibold">
            <i class="bi bi-funnel me-1"></i>Filter
          </button>
          <a href="<?=APP_URL?>/expenses" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-x-lg"></i>
          </a>
          <!-- Quick shortcuts -->
          <div class="d-flex gap-1">
            <?php foreach([
              'Today'     =>[date('Y-m-d'),date('Y-m-d')],
              'This Week' =>[date('Y-m-d',strtotime('monday this week')),date('Y-m-d')],
              'This Month'=>[date('Y-m-01'),date('Y-m-d')],
              'Last Month'=>[date('Y-m-01',strtotime('first day of last month')),
                             date('Y-m-t',strtotime('last day of last month'))],
            ] as $lbl=>[$f,$t]):
              $active=($from===$f&&$to===$t);
            ?>
            <a href="?from=<?=$f?>&to=<?=$t?>"
               class="btn btn-sm <?=$active?'btn-danger':'btn-outline-secondary'?>">
              <?=$lbl?>
            </a>
            <?php endforeach;?>
          </div>
        </form>
      </div>
    </div>

    <!-- Expense Table -->
    <div class="card">
      <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
        <span class="fw-semibold small">
          <i class="bi bi-receipt me-1"></i>Expense Records
        </span>
        <span class="badge bg-secondary">
          <?=number_format($pagination['total'])?> · Page <?=$curPage?>/<?=$lastPage?>
        </span>
      </div>
      <div class="table-responsive">
        <table class="table table-sm table-hover mb-0 exp-table">
          <thead class="table-dark">
            <tr>
              <th class="ps-3">#</th>
              <th>Title</th>
              <th>Category</th>
              <th class="text-center">Date</th>
              <th>Reference</th>
              <th class="text-end">Amount</th>
              <th class="text-center">By</th>
              <th class="text-center">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if(empty($data)):?>
            <tr>
              <td colspan="8" class="text-center text-muted py-5">
                <i class="bi bi-wallet2 d-block fs-2 mb-2 opacity-25"></i>
                No expenses for selected period.
              </td>
            </tr>
            <?php endif;?>

            <?php
            $rowNum = ($curPage-1)*$perPage;
            foreach($data as $exp):
              $rowNum++;
            ?>
            <tr>
              <td class="ps-3 text-muted small"><?=$rowNum?></td>

              <td>
                <div class="fw-semibold"><?=e($exp['title'])?></div>
                <?php if($exp['note']??''):?>
                <div style="font-size:.65rem;color:#94a3b8"><?=e(substr($exp['note'],0,40))?></div>
                <?php endif;?>
              </td>

              <td>
                <span class="badge bg-danger bg-opacity-10 text-danger fw-semibold"
                      style="font-size:.68rem">
                  <?=e($exp['category_name'])?>
                </span>
              </td>

              <td class="text-center small">
                <div class="fw-semibold"><?=date('d M Y',strtotime($exp['expense_date']))?></div>
              </td>

              <td class="text-muted small"><?=e($exp['reference']??'—')?></td>

              <td class="text-end fw-bold" style="color:#dc2626">
                <?=$sym?><?=number_format($exp['amount'],2)?>
              </td>

              <td class="text-center text-muted small">
                <?=e($exp['created_by_name']??'—')?>
              </td>

              <td class="text-center">
                <?php if(Auth::can('expenses.delete')):?>
                <form method="POST"
                      action="<?=APP_URL?>/expenses/delete/<?=$exp['id']?>"
                      onsubmit="return confirm('Delete this expense?')">
                  <?=Auth::csrfField()?>
                  <button class="btn btn-sm btn-outline-danger py-0 px-1" title="Delete">
                    <i class="bi bi-trash3"></i>
                  </button>
                </form>
                <?php endif;?>
              </td>
            </tr>
            <?php endforeach;?>
          </tbody>

          <?php if(!empty($data)):?>
          <tfoot class="table-secondary fw-bold" style="font-size:.75rem">
            <tr>
              <td colspan="5" class="ps-3">PAGE TOTAL (<?=count($data)?>)</td>
              <td class="text-end" style="color:#dc2626">
                <?=$sym?><?=number_format(array_sum(array_column($data,'amount')),2)?>
              </td>
              <td colspan="2"></td>
            </tr>
          </tfoot>
          <?php endif;?>
        </table>
      </div>

      <!-- Pagination -->
      <?php if($lastPage > 1):?>
      <div class="card-footer d-flex justify-content-between align-items-center py-2">
        <span class="text-muted small">Page <?=$curPage?>/<?=$lastPage?></span>
        <nav>
          <ul class="pagination pagination-sm mb-0">
            <li class="page-item <?=$curPage<=1?'disabled':''?>">
              <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$curPage-1]))?>">‹</a>
            </li>
            <?php foreach(range(max(1,$curPage-2),min($lastPage,$curPage+2)) as $p):?>
            <li class="page-item <?=$p===$curPage?'active':''?>">
              <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$p]))?>"><?=$p?></a>
            </li>
            <?php endforeach;?>
            <li class="page-item <?=$curPage>=$lastPage?'disabled':''?>">
              <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$curPage+1]))?>">›</a>
            </li>
          </ul>
        </nav>
      </div>
      <?php endif;?>
    </div>
  </div>

  <!-- Right: Category breakdown -->
  <div class="col-lg-4">

    <!-- Breakdown chart -->
    <div class="card mb-3">
      <div class="card-header fw-semibold small bg-transparent">
        <i class="bi bi-pie-chart me-1 text-danger"></i>By Category
      </div>
      <div class="card-body">
        <?php if(empty($breakdown)):?>
        <div class="text-center text-muted py-3 small">No data</div>
        <?php endif;?>
        <?php foreach($breakdown as $b):
          $pct = $maxBreak > 0 ? round((float)$b['total']/$maxBreak*100) : 0;
          $share = $totalAmt > 0 ? round((float)$b['total']/$totalAmt*100,1) : 0;
        ?>
        <div class="mb-3">
          <div class="d-flex justify-content-between align-items-center mb-1">
            <span class="small fw-semibold"><?=e($b['category_name'])?></span>
            <div class="text-end">
              <div class="fw-bold small" style="color:#dc2626">
                <?=$sym?><?=number_format($b['total'],0)?>
              </div>
              <div style="font-size:.62rem;color:#94a3b8">
                <?=$share?>% · <?=$b['count']?> records
              </div>
            </div>
          </div>
          <div class="cat-bar">
            <div class="cat-bar-fill" style="width:<?=$pct?>%"></div>
          </div>
        </div>
        <?php endforeach;?>

        <?php if(!empty($breakdown)):?>
        <div class="border-top pt-2 mt-1 d-flex justify-content-between"
             style="font-size:.75rem;font-weight:700">
          <span>TOTAL</span>
          <span style="color:#dc2626"><?=$sym?><?=number_format($totalAmt,2)?></span>
        </div>
        <?php endif;?>
      </div>
    </div>

    <!-- Quick add recent categories -->
    <?php if(Auth::can('expenses.create') && !empty($categories)):?>
    <div class="card">
      <div class="card-header fw-semibold small bg-transparent">
        <i class="bi bi-lightning me-1 text-warning"></i>Quick Add Expense
      </div>
      <div class="card-body">
        <form method="POST" action="<?=APP_URL?>/expenses/store">
          <?=Auth::csrfField()?>
          <div class="mb-2">
            <input type="text" name="title" class="form-control form-control-sm"
                   placeholder="Expense title *" required>
          </div>
          <div class="row g-2 mb-2">
            <div class="col-7">
              <select name="expense_category_id" class="form-select form-select-sm" required>
                <option value="">Category *</option>
                <?php foreach($categories as $cat):?>
                <option value="<?=$cat['id']?>"><?=e($cat['category_name'])?></option>
                <?php endforeach;?>
              </select>
            </div>
            <div class="col-5">
              <input type="date" name="expense_date"
                     class="form-control form-control-sm"
                     value="<?=date('Y-m-d')?>">
            </div>
          </div>
          <div class="row g-2 mb-2">
            <div class="col-6">
              <div class="input-group input-group-sm">
                <span class="input-group-text"><?=$sym?></span>
                <input type="number" name="amount" class="form-control"
                       step="0.01" min="0.01" placeholder="Amount *" required>
              </div>
            </div>
            <div class="col-6">
              <input type="text" name="reference" class="form-control form-control-sm"
                     placeholder="Reference (opt.)">
            </div>
          </div>
          <button type="submit" class="btn btn-danger btn-sm fw-semibold w-100">
            <i class="bi bi-plus-circle me-1"></i>Add Expense
          </button>
        </form>
      </div>
    </div>
    <?php endif;?>
  </div>
</div>

<!-- Add Expense Modal (full form) -->
<div class="modal fade" id="addExpModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:440px">
    <div class="modal-content">
      <div class="modal-header bg-dark text-white">
        <h6 class="modal-title fw-bold"><i class="bi bi-plus-circle me-2"></i>Add Expense</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?=APP_URL?>/expenses/store">
        <?=Auth::csrfField()?>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label small fw-semibold">Title <span class="text-danger">*</span></label>
            <input type="text" name="title" class="form-control" required autofocus
                   placeholder="e.g. LECO Electricity Bill">
          </div>
          <div class="row g-2 mb-3">
            <div class="col-8">
              <label class="form-label small fw-semibold">Category <span class="text-danger">*</span></label>
              <select name="expense_category_id" class="form-select" required>
                <option value="">— Select —</option>
                <?php foreach($categories as $cat):?>
                <option value="<?=$cat['id']?>"><?=e($cat['category_name'])?></option>
                <?php endforeach;?>
              </select>
            </div>
            <div class="col-4">
              <label class="form-label small fw-semibold">Date</label>
              <input type="date" name="expense_date" class="form-control"
                     value="<?=date('Y-m-d')?>">
            </div>
          </div>
          <div class="row g-2 mb-3">
            <div class="col-6">
              <label class="form-label small fw-semibold">Amount <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text fw-bold"><?=$sym?></span>
                <input type="number" name="amount" class="form-control fw-bold"
                       step="0.01" min="0.01" required placeholder="0.00">
              </div>
            </div>
            <div class="col-6">
              <label class="form-label small fw-semibold">Reference No.</label>
              <input type="text" name="reference" class="form-control"
                     placeholder="Receipt / invoice no.">
            </div>
          </div>
          <div>
            <label class="form-label small fw-semibold">Note</label>
            <textarea name="note" class="form-control" rows="2"
                      placeholder="Additional details…"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-danger fw-semibold">
            <i class="bi bi-check-circle me-1"></i>Save Expense
          </button>
        </div>
      </form>
    </div>
  </div>
</div>