<?php
// Dashboard — the product (Section 20). Hero add-expense form, month
// summary, spending-by-category chart, and a short Recent list, in that
// priority order. Shows the current month by default; ?month=YYYY-MM
// browses the permanent archive (Section 8, Phase 5).
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/validation.php';
require_once __DIR__ . '/includes/visitor_log.php';
log_visit();
require_login();

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

$currentUser = current_user();
$isAdmin = current_user_is_admin();

$categories = get_active_expense_categories();
$paymentMethods = get_active_payment_methods();

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

$budgetCopiedNotice = copy_budgets_forward_if_needed($month);
$budgetSummary = get_budget_summary($month);

// Radial budget ring (r=36 circle, Section 20 summary card): the arc is
// capped at 100% visually (a full ring) even when over budget, but the
// label text still shows the real percentage so "142%" isn't hidden.
$ringCircumference = 226.19;
$ringPercentCapped = $budgetSummary ? min(100, (float) $budgetSummary['percent_used']) : 0;
$ringDashoffset = round($ringCircumference * (1 - $ringPercentCapped / 100), 2);

$monthTotalRaw = get_month_expense_total($month);
$monthTotalFormatted = format_money($monthTotalRaw);
$bdtEquivalent = format_bdt_equivalent($monthTotalRaw);

// My Expenses card (dashboard-only, this user's own total for the viewed
// month) — kept separate from the household-wide total above so a glance
// at this card never requires mentally subtracting the other person's spending.
$myMonthTotalRaw = get_user_month_expense_total($month, (int) $currentUser['id']);
$myMonthTotalFormatted = format_money($myMonthTotalRaw);

$categoryChart = build_category_chart_data(get_month_category_totals($month));
$recent = array_map('format_recent_expense_row', get_recent_expenses($month, 5));

// Year-to-date total (Section 20 addition): always the real current
// calendar year, independent of whichever month is being browsed above.
$yearNow = (int) date('Y');
$yearTotalRaw = get_year_expense_total($yearNow);
$yearTotalFormatted = format_money($yearTotalRaw);
$yearBdtEquivalent = format_bdt_equivalent($yearTotalRaw);
$yearMonths = get_year_month_breakdown($yearNow);

// The add form's date defaults into whichever month is being viewed —
// today's date if that's the current month, otherwise the 1st, so
// backfilling a past (or pre-entering a future) month is painless.
$defaultDate = $isCurrentMonth ? date('Y-m-d') : $month . '-01';

$oldAmount = $oldInput['amount'] ?? '';
$oldDescription = $oldInput['description'] ?? '';
$oldDate = $oldInput['expense_date'] ?? $defaultDate;
$oldCategoryId = isset($oldInput['category_id']) && $oldInput['category_id'] !== ''
    ? (int) $oldInput['category_id']
    : ($categories[0]['id'] ?? 0);
$oldPaymentMethodId = isset($oldInput['payment_method_id']) && $oldInput['payment_method_id'] !== ''
    ? (int) $oldInput['payment_method_id']
    : ($paymentMethods[0]['id'] ?? 0);

$visibleCategories = array_slice($categories, 0, 7);
$hiddenCategories = array_slice($categories, 7);

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

<div class="dash-grid">

  <!-- ============ Add Expense — the hero ============
       Mobile order (Section 20 update): Summary, then Add Expense, then
       Chart, then Recent. Desktop (≥992px): back to sticky-left beside
       Summary/Chart/Recent stacked on the right, per the original split.
       grid-area placement (dash-grid CSS) drives both, not Bootstrap's
       row/col/order utilities — those can't reorder one nested section
       independently of its siblings, only whole columns as a block. -->
  <div class="dash-add">
    <section class="hero sticky-col" aria-label="Add expense">
      <div class="hero-title"><i class="bi bi-plus-circle-fill"></i>Add expense</div>

      <form id="addForm" action="api/expense_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="amount">Amount</label>
        <div class="amount-wrap<?= isset($formErrors['amount']) ? ' has-error' : '' ?>" id="amountWrap">
          <span class="amount-cur"><?= e(get_setting('currency_symbol', '¥')) ?></span>
          <input class="amount-in tnum" id="amount" 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($visibleCategories, $hiddenCategories, $oldCategoryId, 'categoryId', 'category_id', 'catGrid', 'moreCats'); ?>
        <?php if (isset($formErrors['category_id'])): ?>
          <div class="field-error"><?= e($formErrors['category_id']) ?></div>
        <?php endif; ?>

        <label class="field-label" for="desc">Description</label>
        <input class="form-control" id="desc" name="description" type="text" required
               maxlength="255" placeholder="e.g. Lunch at noodle place" value="<?= e($oldDescription) ?>">
        <?php if (isset($formErrors['description'])): ?>
          <div class="field-error"><?= e($formErrors['description']) ?></div>
        <?php endif; ?>

        <div class="row g-2">
          <div class="col-6">
            <label class="field-label" for="date">Date</label>
            <input class="form-control tnum" id="date" name="expense_date" type="date" value="<?= e($oldDate) ?>">
            <?php if (isset($formErrors['expense_date'])): ?>
              <div class="field-error"><?= e($formErrors['expense_date']) ?></div>
            <?php endif; ?>
          </div>
          <div class="col-6">
            <label class="field-label" for="method">Paid with</label>
            <select class="form-select" id="method" name="payment_method_id">
              <?php foreach ($paymentMethods as $method): ?>
                <option value="<?= e((string) $method['id']) ?>" <?= (int) $method['id'] === $oldPaymentMethodId ? 'selected' : '' ?>>
                  <?= e($method['name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>

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

  <div class="dash-myexpenses">
    <!-- ============ My Expenses — this user's own total, this month ============
         Minimal-row treatment (design review, Option 5 refined): a compact
         linked row instead of a boxed card — the accent rail on the left
         marks it as "yours," and the whole row is the tap target rather
         than a separate button chip. Deliberately separate from the
         household summary card below: shows only what the logged-in user
         spent, with no math required to see it, and links to the All
         Expenses archive pre-filtered to just their own entries. -->
    <a href="expenses.php?user_id=<?= e((string) $currentUser['id']) ?>"
       class="myx-row d-flex align-items-center justify-content-between text-decoration-none gap-3"
       aria-label="My expenses this month — view all">
      <div>
        <div class="kicker mb-1">My expenses · <?= e(month_name($month)) ?></div>
        <div class="fw-bold tnum myx-amount" id="myExpensesTotal"><?= e($myMonthTotalFormatted) ?></div>
      </div>
      <span class="myx-link d-flex align-items-center gap-1 fw-semibold flex-shrink-0">
        My Expenses <i class="bi bi-arrow-right"></i>
      </span>
    </a>
  </div>

  <div class="dash-summary">
    <!-- ============ Current month summary ============ -->
    <section class="card-summary-dark p-3 p-lg-4" aria-label="<?= e(month_name($month)) ?> summary">
      <div class="d-flex align-items-start">
        <div class="cs-ring-wrap<?= $budgetSummary ? '' : ' d-none' ?>" id="ringWrap">
          <svg viewBox="0 0 84 84" width="84" height="84" aria-hidden="true">
            <circle cx="42" cy="42" r="36" fill="none" class="cs-ring-track" stroke-width="8"/>
            <circle cx="42" cy="42" r="36" fill="none" stroke-width="8" stroke-linecap="round"
                    class="cs-ring-fill<?= ($budgetSummary && $budgetSummary['over_budget']) ? ' over' : '' ?>"
                    id="budgetRing" stroke-dasharray="<?= e((string) $ringCircumference) ?>"
                    stroke-dashoffset="<?= e((string) $ringDashoffset) ?>" transform="rotate(-90 42 42)"/>
          </svg>
          <div class="cs-ring-label tnum<?= ($budgetSummary && $budgetSummary['over_budget']) ? ' over' : '' ?>" id="ringLabel">
            <?= $budgetSummary ? e((string) $budgetSummary['percent_used']) . '%' : '' ?>
          </div>
        </div>
        <div>
          <label for="monthPicker" class="kicker d-inline-flex align-items-center gap-1 mb-0" style="cursor:pointer;" aria-label="Jump to a month">
            Spent in <?= e(month_name($month)) ?><i class="bi bi-chevron-down" style="font-size:.6rem;"></i>
          </label>
          <div class="spent-big tnum" id="summaryTotal"><?= e($monthTotalFormatted) ?></div>
          <div class="small mt-1<?= $bdtEquivalent === null ? ' d-none' : '' ?>" id="bdtEquivalent"><?= e($bdtEquivalent ?? '') ?></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>

      <div id="budgetRow" class="d-flex justify-content-between small mt-3 pt-3 cs-divider<?= $budgetSummary ? '' : ' d-none' ?>">
        <span class="text-secondary">Budget <span class="tnum fw-semibold text-body" id="budgetPlanned"><?= e($budgetSummary['planned_formatted'] ?? '') ?></span></span>
        <span class="text-secondary"><span id="budgetRemainingLabel"><?= $budgetSummary && $budgetSummary['over_budget'] ? 'Over by' : 'Left' ?></span>
          <span class="tnum fw-bold cs-good" id="budgetRemaining" data-over="<?= ($budgetSummary && $budgetSummary['over_budget']) ? '1' : '0' ?>"><?= e($budgetSummary['remaining_formatted'] ?? '') ?></span>
        </span>
      </div>

      <?php if ($budgetCopiedNotice): ?>
        <div class="small text-secondary mt-2"><i class="bi bi-info-circle me-1"></i>Budgets copied from <?= e(month_label($prevMonth)) ?> — <a href="budgets.php?month=<?= e($month) ?>" class="link-quiet">adjust anytime</a>.</div>
      <?php endif; ?>

      <form method="get" id="monthPickerForm">
        <input type="month" name="month" id="monthPicker" 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>
  </div>

  <div class="dash-chart">
    <!-- ============ Spending by category ============ -->
    <section class="card-x p-3 p-lg-4" aria-label="Spending by category">
      <div class="d-flex align-items-baseline justify-content-between mb-1">
        <div class="sec-title">Spending by category</div>
        <div class="sec-sub"><?= e(month_name($month)) ?> · highest first</div>
      </div>

      <p class="text-secondary small mb-0<?= $categoryChart ? ' d-none' : '' ?>" id="categoryChartEmpty">
        No expenses yet in <?= e(month_name($month)) ?>. Add the first one above.
      </p>
      <div id="categoryChartBody">
        <?php foreach ($categoryChart as $row): ?>
          <div class="hrow" style="--c:<?= e($row['color']) ?>">
            <span class="hrow-ic"><i class="bi <?= e($row['icon']) ?>"></i></span>
            <div class="hrow-body">
              <div class="hrow-top">
                <span class="hname"><?= e($row['name']) ?></span>
                <span class="hamt tnum"><?= e($row['amount_formatted']) ?></span>
                <span class="hpct tnum"><?= e((string) $row['percent']) ?>%</span>
              </div>
              <div class="htrack"><span style="width:<?= e((string) $row['width_percent']) ?>%"></span></div>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    </section>
  </div>

  <div class="dash-recent">
    <!-- ============ Recent — secondary ============ -->
    <section class="card-x p-3 p-lg-4" aria-label="Recent expenses">
      <div class="d-flex align-items-baseline justify-content-between mb-1">
        <div class="sec-title">Recent</div>
        <a class="link-quiet" href="expenses.php">All Expenses <i class="bi bi-arrow-right"></i></a>
      </div>

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

  <div class="dash-yeartotal">
    <!-- ============ This year's total expenses so far ============ -->
    <section class="card-x p-3 p-lg-4" aria-label="Year to date expenses">
      <div class="d-flex align-items-baseline justify-content-between mb-1">
        <div class="sec-title">This year's total expenses so far</div>
        <a class="link-quiet" href="expenses.php">All Expenses <i class="bi bi-arrow-right"></i></a>
      </div>

      <div class="d-flex align-items-baseline gap-2 flex-wrap mt-2">
        <div class="spent-big tnum" style="color:var(--ink);"><?= e($yearTotalFormatted) ?></div>
        <span class="year-badge tnum"><?= e((string) $yearNow) ?></span>
      </div>
      <div class="small text-secondary mb-3<?= $yearBdtEquivalent === null ? ' d-none' : '' ?>"><?= e($yearBdtEquivalent ?? '') ?></div>

      <p class="text-secondary small mb-0<?= $yearMonths ? ' d-none' : '' ?>">No expenses yet this year.</p>
      <?php foreach ($yearMonths as $row): ?>
        <a class="hrow hrow-link" href="index.php?month=<?= e($row['month']) ?>">
          <span class="hrow-ic hrow-ic-num"><?= e(substr($row['month'], 5, 2)) ?></span>
          <div class="hrow-body">
            <div class="hrow-top">
              <span class="hname"><?= e($row['label']) ?></span>
              <span class="hamt tnum"><?= e($row['total_formatted']) ?></span>
              <span class="hpct tnum"><?= e((string) $row['percent']) ?>%</span>
            </div>
            <div class="htrack"><span style="width:<?= e((string) $row['width_percent']) ?>%;background:var(--accent);"></span></div>
          </div>
        </a>
      <?php endforeach; ?>
    </section>
  </div>

</div>

<?php require __DIR__ . '/includes/layout/edit_modal.php'; ?>
<?php require __DIR__ . '/includes/layout/budget_warning_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'; ?>