<?php
declare(strict_types=1);

/**
 * modules/accounts/expenses/list.php
 *
 * Expense list with filters:
 *  - Date range (defaults to current month)
 *  - Segment (Rent / Chauffeur)
 *  - Expense type (COGS / Operating)
 *  - Account (from chart_of_accounts.code)
 *  - Search (reference / notes)
 * Extras:
 *  - Sum total for the filtered view
 *  - CSV export (keeps current filters)
 */

require_once dirname(__DIR__, 3) . '/config/functions.php';
require_role(['Accounts','MD','Admin','Management']);

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('login.php'));

$errors = [];
$notice = null;

// ------------------------------------------------------
// 1) Filters
// ------------------------------------------------------
$today      = new DateTimeImmutable('today');
$monthStart = $today->modify('first day of this month');
$monthEnd   = $today->modify('last day of this month');

$from   = (string)($_GET['from'] ?? $monthStart->format('Y-m-01'));
$to     = (string)($_GET['to']   ?? $monthEnd->format('Y-m-d'));
$seg    = trim((string)($_GET['segment'] ?? ''));
$type   = trim((string)($_GET['type'] ?? '')); // cogs or expense
$acct   = trim((string)($_GET['account'] ?? ''));
$q      = trim((string)($_GET['q'] ?? ''));
$export = (int)($_GET['export'] ?? 0);

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) $from = $monthStart->format('Y-m-d');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to))   $to   = $monthEnd->format('Y-m-d');

// ------------------------------------------------------
// 2) Filter options
// ------------------------------------------------------
$accounts = []; // [code => "Name (CODE)"]

try {
  $sql = "
    SELECT code, name, type
    FROM chart_of_accounts
    WHERE company_id = :cid
      AND type IN ('cogs','expense')
      AND (is_active = 1 OR is_active IS NULL)
    ORDER BY name ASC
  ";
  $st = db()->prepare($sql);
  $st->execute([':cid'=>$cid]);
  foreach ($st->fetchAll() as $row) {
    $accounts[(string)$row['code']] = $row['name'].' ('.$row['code'].')';
  }
} catch (Throwable $e) {
  $errors[] = 'Unable to load accounts.';
}

// ------------------------------------------------------
// 3) Fetch expenses
// ------------------------------------------------------
$rows = [];
$totalAmount = 0.0;

try {
  $where = [
    "t.company_id = :cid",
    "t.type = 'expense'",
    "t.date BETWEEN :from AND :to",
  ];
  $args = [':cid'=>$cid, ':from'=>$from, ':to'=>$to];

  if ($seg !== '') {
    $where[] = "t.segment = :seg";
    $args[':seg'] = $seg;
  }
  if ($type !== '') {
    $where[] = "coa.type = :etype";
    $args[':etype'] = $type;
  }
  if ($acct !== '' && isset($accounts[$acct])) {
    $where[] = "t.account_code = :acct";
    $args[':acct'] = $acct;
  }
  if ($q !== '') {
    $where[] = "(t.reference LIKE :q OR t.notes LIKE :q)";
    $args[':q'] = '%'.$q.'%';
  }

  $sql = "
    SELECT
      t.id, t.date, t.account_code, t.amount, t.reference, t.notes, t.segment,
      COALESCE(coa.name, t.account_code) AS account_name,
      COALESCE(coa.type, '') AS expense_type
    FROM transactions t
    LEFT JOIN chart_of_accounts coa
      ON coa.company_id = t.company_id
     AND coa.code = t.account_code
    WHERE ".implode(' AND ', $where)."
    ORDER BY t.date DESC, t.id DESC
    LIMIT 1000
  ";
  $st = db()->prepare($sql);
  $st->execute($args);
  $rows = $st->fetchAll();

  foreach ($rows as $r) $totalAmount += (float)$r['amount'];

} catch (Throwable $e) {
  $errors[] = 'Unable to load expenses. '.$e->getMessage();
}

// ------------------------------------------------------
// 4) CSV export
// ------------------------------------------------------
if ($export === 1) {
  $fn = 'expenses_'.$from.'_to_'.$to.'.csv';
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename="'.$fn.'"');

  $out = fopen('php://output', 'w');
  fputcsv($out, ['Date','Segment','Expense Type','Account Code','Account Name','Reference','Notes','Amount']);
  foreach ($rows as $r) {
    fputcsv($out, [
      $r['date'],
      $r['segment'] ?? '',
      $r['expense_type'],
      $r['account_code'],
      $r['account_name'],
      $r['reference'] ?? '',
      $r['notes'] ?? '',
      number_format((float)$r['amount'], 2, '.', '')
    ]);
  }
  fclose($out);
  exit;
}

// ------------------------------------------------------
// 5) Render
// ------------------------------------------------------
include dirname(__DIR__, 3) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h1 class="h4 mb-0">Expenses</h1>
    <div class="text-muted">Filter by date, segment, expense type and account.</div>
  </div>
  <?php $exportQs = http_build_query(['from'=>$from,'to'=>$to,'segment'=>$seg,'type'=>$type,'account'=>$acct,'q'=>$q,'export'=>1]); ?>
  <a class="btn btn-outline-primary" href="?<?= e($exportQs) ?>">⬇️ Export CSV</a>
</div>

<?php if ($errors): ?>
  <div class="alert alert-danger"><ul><?php foreach ($errors as $er) echo '<li>'.e($er).'</li>'; ?></ul></div>
<?php endif; ?>

<div class="card shadow-sm mb-3">
  <div class="card-body">
    <form class="row g-2 align-items-end" method="get">
      <div class="col-md-2">
        <label class="form-label">From</label>
        <input type="date" class="form-control" name="from" value="<?= e($from) ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">To</label>
        <input type="date" class="form-control" name="to" value="<?= e($to) ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Segment</label>
        <select class="form-select" name="segment">
          <option value="">All</option>
          <option value="Rent" <?= $seg==='Rent'?'selected':'' ?>>Rent</option>
          <option value="Chauffeur" <?= $seg==='Chauffeur'?'selected':'' ?>>Chauffeur</option>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Expense Type</label>
        <select class="form-select" name="type">
          <option value="">All</option>
          <option value="cogs" <?= $type==='cogs'?'selected':'' ?>>Cost of Goods Sold</option>
          <option value="expense" <?= $type==='expense'?'selected':'' ?>>Operating Expense</option>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Account</label>
        <select class="form-select" name="account">
          <option value="">All</option>
          <?php foreach ($accounts as $code => $label): ?>
            <option value="<?= e($code) ?>" <?= $code===$acct?'selected':'' ?>><?= e($label) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Search</label>
        <input class="form-control" name="q" placeholder="Reference / Notes" value="<?= e($q) ?>">
      </div>
      <div class="col-12 col-md-2 d-grid">
  <button class="btn btn-dark">Filter</button>
</div>
<div class="col-12 col-md-2 d-grid">
  <a href="<?= e(url_modules('accounts/expenses/add.php')) ?>" class="btn btn-success">
    ➕ Add Expense
  </a>
</div>

    </form>
  </div>
</div>



<div class="card shadow-sm">
  <div class="card-body d-flex justify-content-between align-items-center">
    <div class="small text-muted">
      Showing <strong><?= number_format(count($rows)) ?></strong> records
      from <strong><?= e($from) ?></strong> to <strong><?= e($to) ?></strong>.
    </div>
    <div class="fs-5">Total: <strong>£<?= number_format($totalAmount, 2) ?></strong></div>
  </div>
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead class="table-light">
        <tr>
          <th>Date</th>
          <th>Segment</th>
          <th>Expense Type</th>
          <th>Account</th>
          <th>Reference</th>
          <th>Notes</th>
          <th class="text-end">Amount (£)</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($rows): foreach ($rows as $r): ?>
          <tr>
            <td><?= e($r['date']) ?></td>
            <td><span class="badge bg-secondary"><?= e($r['segment'] ?? '-') ?></span></td>
            <td><?= $r['expense_type']==='cogs'?'COGS':'Operating' ?></td>
            <td>
              <div class="fw-semibold"><?= e($r['account_name']) ?></div>
              <div class="text-muted small"><?= e($r['account_code']) ?></div>
            </td>
            <td><?= e($r['reference'] ?? '—') ?></td>
            <td class="text-wrap"><?= e($r['notes'] ?? '—') ?></td>
            <td class="text-end">£<?= number_format((float)$r['amount'], 2) ?></td>
          </tr>
        <?php endforeach; else: ?>
          <tr><td colspan="7" class="text-center text-muted py-4">No expenses found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php include dirname(__DIR__, 3) . '/includes/footer.php';
