<?php
declare(strict_types=1);

/**
 * modules/accounts/income/list.php
 *
 * Manual Income entries (non-booking / non-rental)
 * - Shows transactions where type='income' AND booking_id IS NULL AND rental_id IS NULL
 * - Filters: date range, account (Chauffeur/Rental/Other), search (reference/notes)
 * - Add new manual income (go to add.php)
 * - Delete a manual income row (safety: only when booking_id AND rental_id are NULL)
 * - CSV export for the filtered view
 */

/////////////////////////////////////////////////////////
// 1) Bootstrap & guards
/////////////////////////////////////////////////////////
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;

/////////////////////////////////////////////////////////
// 2) Config: allowed income accounts for manual entries
/////////////////////////////////////////////////////////
$incomeAccounts = [
  'CHAUF_INCOME'   => 'Chauffeur Income',
  'RENTAL_INCOME'  => 'Rental Income',
  'OTHER_INCOME'   => 'Other Income',
];

/////////////////////////////////////////////////////////
// 3) Filters (date range, account, search)
/////////////////////////////////////////////////////////
$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'));
$acc     = (string)($_GET['account'] ?? 'ALL');
$q       = trim((string)($_GET['q'] ?? ''));

// Normalize filters
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');
if ($acc !== 'ALL' && !array_key_exists($acc, $incomeAccounts)) $acc = 'ALL';

/////////////////////////////////////////////////////////
// 4) POST actions: delete only (creation happens in add.php)
/////////////////////////////////////////////////////////
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));
    $action = (string)($_POST['action'] ?? '');

    if ($action === 'delete') {
      $id = (int)($_POST['id'] ?? 0);
      if ($id <= 0) throw new RuntimeException('Invalid row.');

      $del = db()->prepare("
        DELETE FROM transactions
         WHERE id=:id AND company_id=:cid AND type='income'
           AND booking_id IS NULL AND rental_id IS NULL
      ");
      $del->execute([':id'=>$id, ':cid'=>$cid]);

      audit_log('income.manual.delete','transactions',$id,[]);
      $qs = http_build_query(['from'=>$from,'to'=>$to,'account'=>$acc,'q'=>$q,'ok'=>1]);
      redirect(url_modules('accounts/income/list.php').'?'.$qs);
    }

  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Action failed.';
  }
}

if (isset($_GET['ok'])) $notice = 'Saved.';

/////////////////////////////////////////////////////////
// 5) Data query (filtered manual income only)
/////////////////////////////////////////////////////////
$rows = [];
$total = 0.0;

try {
  $where = [
    "t.company_id = :cid",
    "t.`date` BETWEEN :from AND :to",
    "t.type = 'income'",
    "t.booking_id IS NULL",
    "t.rental_id  IS NULL",
  ];
  $args = [':cid'=>$cid, ':from'=>$from, ':to'=>$to];

  if ($acc !== 'ALL') {
    $where[] = "t.account_code = :acc";
    $args[':acc'] = $acc;
  }
  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.segment, t.amount, t.reference, t.notes
      FROM transactions t
     WHERE ".implode(' AND ', $where)."
     ORDER BY t.`date` DESC, t.id DESC
     LIMIT 500
  ";
  $st = db()->prepare($sql);
  $st->execute($args);
  $rows = $st->fetchAll();

  $sumSql = "SELECT COALESCE(SUM(t.amount),0) FROM transactions t WHERE ".implode(' AND ', $where);
  $sst = db()->prepare($sumSql);
  $sst->execute($args);
  $total = (float)$sst->fetchColumn();

} catch (Throwable $e) {
  $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unable to load data.';
}

/////////////////////////////////////////////////////////
// 6) CSV export
/////////////////////////////////////////////////////////
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename="manual_income_'.$from.'_to_'.$to.'.csv"');
  $out = fopen('php://output', 'w');
  fputcsv($out, ['Manual Income', $from, $to, 'Account: '.($acc==='ALL'?'ALL':($incomeAccounts[$acc] ?? $acc))]);
  fputcsv($out, []);
  fputcsv($out, ['Date','Account','Segment','Amount','Reference','Notes']);
  foreach ($rows as $r) {
    fputcsv($out, [
      (string)$r['date'],
      (string)($incomeAccounts[$r['account_code']] ?? $r['account_code']),
      (string)($r['segment'] ?? ''),
      number_format((float)$r['amount'], 2, '.', ''),
      (string)($r['reference'] ?? ''),
      (string)($r['notes'] ?? ''),
    ]);
  }
  fputcsv($out, []);
  fputcsv($out, ['Total', number_format($total, 2, '.', '')]);
  fclose($out);
  exit;
}

/////////////////////////////////////////////////////////
// 7) 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">Manual Income</h1>
    <div class="text-muted">Non-booking / non-rental income in the selected range.</div>
  </div>
  <div class="d-flex flex-wrap gap-2">
    <?php $exportQs = http_build_query(['from'=>$from,'to'=>$to,'account'=>$acc,'q'=>$q,'export'=>'csv']); ?>
    <a class="btn btn-dark" href="<?= e(url_modules('accounts/income/add.php')) ?>">+ Add Income</a>
    <a class="btn btn-outline-primary" href="<?= e(url_modules('accounts/income/list.php').'?'.$exportQs) ?>">⬇️ Export CSV</a>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('accounts/index.php')) ?>">↩ Accounts Dashboard</a>
  </div>
</div>

<?php if ($notice): ?><div class="alert alert-success"><?= e($notice) ?></div><?php endif; ?>
<?php if ($errors): ?>
  <div class="alert alert-danger"><ul class="mb-0"><?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" autocomplete="off">
      <div class="col-md-3">
        <label class="form-label">From</label>
        <input type="date" class="form-control" name="from" value="<?= e($from) ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">To</label>
        <input type="date" class="form-control" name="to" value="<?= e($to) ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Account</label>
        <select class="form-select" name="account">
          <option value="ALL" <?= $acc==='ALL'?'selected':'' ?>>ALL</option>
          <?php foreach ($incomeAccounts as $code=>$label): ?>
            <option value="<?= e($code) ?>" <?= $acc===$code?'selected':'' ?>><?= e($label) ?> (<?= e($code) ?>)</option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">Search</label>
        <input class="form-control" name="q" placeholder="Reference / Notes" value="<?= e($q) ?>">
      </div>
      <div class="col-md-2 d-grid">
        <button class="btn btn-dark">Filter</button>
      </div>
    </form>
  </div>
</div>

<div class="card shadow-sm">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead class="table-light">
        <tr>
          <th style="width:110px;">Date</th>
          <th>Account</th>
          <th>Segment</th>
          <th>Reference</th>
          <th>Notes</th>
          <th class="text-end" style="width:140px;">Amount</th>
          <th class="text-end" style="width:120px;">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($rows): foreach ($rows as $r): ?>
          <tr>
            <td><?= e($r['date']) ?></td>
            <td><?= e($incomeAccounts[$r['account_code']] ?? $r['account_code']) ?></td>
            <td><?= e((string)($r['segment'] ?? '')) ?></td>
            <td><?= e((string)($r['reference'] ?? '')) ?></td>
            <td><?= e((string)($r['notes'] ?? '')) ?></td>
            <td class="text-end">£<?= number_format((float)$r['amount'], 2) ?></td>
            <td class="text-end">
              <form method="post" class="d-inline" onsubmit="return confirm('Delete this income entry?');">
                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                <button class="btn btn-sm btn-outline-danger">Delete</button>
              </form>
            </td>
          </tr>
        <?php endforeach; else: ?>
          <tr><td colspan="7" class="text-center text-muted py-4">No results.</td></tr>
        <?php endif; ?>
      </tbody>
      <?php if ($rows): ?>
      <tfoot>
        <tr class="table-light">
          <th colspan="5" class="text-end">Total</th>
          <th class="text-end">£<?= number_format($total, 2) ?></th>
          <th></th>
        </tr>
      </tfoot>
      <?php endif; ?>
    </table>
  </div>
</div>

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