<?php
// Income — record income entries (Section 8, B3, Phase 9). Mirrors the
// dashboard's add-expense flow: hero form + month total + list, with the
// same month browsing as index.php. Unlike expenses, income volume is
// naturally low, so this page just lists the whole month, no "Recent" cap.
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/validation.php';
require_once __DIR__ . '/includes/visitor_log.php';
log_visit();
require_login();
require_admin(); // Income is Motaher-only (Section 3 role split) — Sumona never sees this page.

// Errors + typed values survive a plain (JavaScript-disabled) form submit
// via a one-time session flash set by api/income_save.php.
$formErrors = $_SESSION['income_form_errors'] ?? [];
$oldInput = $_SESSION['income_form_old'] ?? [];
unset($_SESSION['income_form_errors'], $_SESSION['income_form_old']);

$incomeCategories = get_active_income_categories();

$month = resolve_viewed_month($_GET['month'] ?? null);
$isCurrentMonth = $month === current_month();
$prevMonth = adjacent_month($month, -1);
$nextMonth = adjacent_month($month, 1);

$monthTotalFormatted = format_money(get_month_income_total($month));
$incomes = array_map('format_recent_income_row', get_month_incomes($month));

// Same reasoning as the dashboard's add-expense form (Section 20, Phase 5):
// default into today if viewing the current month, otherwise the 1st.
$defaultDate = $isCurrentMonth ? date('Y-m-d') : $month . '-01';

$oldAmount = $oldInput['amount'] ?? '';
$oldDescription = $oldInput['description'] ?? '';
$oldDate = $oldInput['income_date'] ?? $defaultDate;
$oldCategoryId = isset($oldInput['category_id']) && $oldInput['category_id'] !== ''
    ? (int) $oldInput['category_id']
    : ($incomeCategories[0]['id'] ?? 0);

$pageTitle = 'Income — ' . month_label($month);
$currentPage = 'income';
require __DIR__ . '/includes/layout/header.php';
?>

<div class="row g-3 g-lg-4">

  <!-- ============ Add income — hero ============ -->
  <div class="col-lg-5 order-1">
    <section class="hero sticky-col" aria-label="Add income">
      <div class="hero-title"><i class="bi bi-plus-circle-fill"></i>Add income</div>

      <form id="addIncomeForm" action="api/income_save.php" method="post" novalidate
            data-is-current-month="<?= $isCurrentMonth ? '1' : '0' ?>" data-viewed-month="<?= e($month) ?>">
        <?= csrf_field() ?>
        <input type="hidden" name="viewed_month" value="<?= e($month) ?>">

        <label class="visually-hidden" for="incomeAmount">Amount</label>
        <div class="amount-wrap<?= isset($formErrors['amount']) ? ' has-error' : '' ?>" id="incomeAmountWrap">
          <span class="amount-cur"><?= e(get_setting('currency_symbol', '¥')) ?></span>
          <input class="amount-in tnum" id="incomeAmount" name="amount" type="text" inputmode="decimal"
                 placeholder="0.00" autocomplete="off" value="<?= e($oldAmount) ?>">
        </div>
        <?php if (isset($formErrors['amount'])): ?>
          <div class="field-error"><?= e($formErrors['amount']) ?></div>
        <?php endif; ?>

        <div class="field-label">Category</div>
        <?php render_category_grid($incomeCategories, [], $oldCategoryId, 'incomeCategoryId', 'category_id', 'incomeCatGrid', 'incomeMoreCats'); ?>
        <?php if (isset($formErrors['category_id'])): ?>
          <div class="field-error"><?= e($formErrors['category_id']) ?></div>
        <?php endif; ?>

        <label class="field-label" for="incomeDesc">Description <span class="fw-normal text-secondary">(optional)</span></label>
        <input class="form-control" id="incomeDesc" name="description" type="text"
               maxlength="255" placeholder="e.g. July salary" value="<?= e($oldDescription) ?>">
        <?php if (isset($formErrors['description'])): ?>
          <div class="field-error"><?= e($formErrors['description']) ?></div>
        <?php endif; ?>

        <label class="field-label" for="incomeDate">Date</label>
        <input class="form-control tnum" id="incomeDate" name="income_date" type="date" value="<?= e($oldDate) ?>">
        <?php if (isset($formErrors['income_date'])): ?>
          <div class="field-error"><?= e($formErrors['income_date']) ?></div>
        <?php endif; ?>

        <button class="btn-save" type="submit" id="incomeSaveBtn">Save income</button>
      </form>
    </section>
  </div>

  <div class="col-lg-7 order-2">

    <!-- ============ Month total ============ -->
    <section class="card-summary p-3 p-lg-4 mb-3 mb-lg-4" aria-label="<?= e(month_name($month)) ?> income">
      <div class="d-flex align-items-start">
        <div>
          <label for="incomeMonthPicker" class="kicker d-inline-flex align-items-center gap-1 mb-0" style="cursor:pointer;" aria-label="Jump to a month">
            Income in <?= e(month_name($month)) ?><i class="bi bi-chevron-down" style="font-size:.6rem;"></i>
          </label>
          <div class="spent-big tnum" id="incomeMonthTotal" style="color:var(--good);"><?= e($monthTotalFormatted) ?></div>
        </div>
        <div class="ms-auto d-flex gap-2">
          <a class="mini-nav" href="?month=<?= e($prevMonth) ?>" aria-label="Previous month, <?= e(month_label($prevMonth)) ?>"><i class="bi bi-chevron-left"></i></a>
          <a class="mini-nav" href="?month=<?= e($nextMonth) ?>" aria-label="Next month, <?= e(month_label($nextMonth)) ?>"><i class="bi bi-chevron-right"></i></a>
        </div>
      </div>
      <form method="get" id="incomeMonthPickerForm">
        <input type="month" name="month" id="incomeMonthPicker" value="<?= e($month) ?>" class="visually-hidden" min="2000-01" max="2100-12">
        <noscript><button type="submit" class="btn btn-sm btn-outline-secondary mt-2">Go</button></noscript>
      </form>
    </section>

    <!-- ============ Income list ============ -->
    <section class="card-x p-3 p-lg-4" aria-label="Income entries">
      <div class="d-flex align-items-baseline justify-content-between mb-1">
        <div class="sec-title"><?= e(month_name($month)) ?> income</div>
        <div class="sec-sub"><?= count($incomes) ?> <?= count($incomes) === 1 ? 'entry' : 'entries' ?></div>
      </div>

      <p class="text-secondary small mb-0<?= $incomes ? ' d-none' : '' ?>" id="incomeListEmpty">
        No income yet in <?= e(month_name($month)) ?>. Add the first one above.
      </p>
      <div id="incomeList">
        <?php foreach ($incomes as $item): ?>
          <?php render_income_row($item); ?>
        <?php endforeach; ?>
      </div>
    </section>

  </div>
</div>

<?php require __DIR__ . '/includes/layout/edit_income_modal.php'; ?>

<!-- Toasts -->
<div class="toast-container position-fixed bottom-0 start-50 translate-middle-x p-3" id="toasts"></div>

<?php require __DIR__ . '/includes/layout/footer.php'; ?>
