<?php
// Budgets — planned amount per category per month (Section 8, B1/B2,
// Phase 8). Plain POST/redirect/GET, like Manage/Settings — this is an
// advanced page (Section 3), set once a month, not the daily-use loop.
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/validation.php';
require_once __DIR__ . '/includes/visitor_log.php';
log_visit();
require_login();

$isAdmin = current_user_is_admin();

$db = get_db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$isAdmin) {
        header('Location: index.php');
        exit;
    }
    if (!csrf_verify($_POST['csrf_token'] ?? null)) {
        header('Location: budgets.php');
        exit;
    }

    $month = resolve_viewed_month($_POST['month'] ?? null);
    [$year, $monthNum] = split_year_month($month);
    $amounts = is_array($_POST['amounts'] ?? null) ? $_POST['amounts'] : [];

    $errors = [];

    foreach ($amounts as $categoryId => $raw) {
        $categoryId = (int) $categoryId;
        $raw = trim((string) $raw);

        if ($raw === '') {
            // Blank means "no plan for this category" — remove any existing row.
            $db->prepare('DELETE FROM budgets WHERE category_id = :cid AND budget_year = :y AND budget_month = :m')
                ->execute(['cid' => $categoryId, 'y' => $year, 'm' => $monthNum]);
            continue;
        }

        $normalized = normalize_amount($raw);
        if ($normalized === null || (float) $normalized < 0 || (float) $normalized > 99999999.99) {
            $errors[$categoryId] = 'Please enter 0 or a positive amount.';
            continue;
        }

        // VALUES(planned_amount), not a repeated :amount placeholder — see
        // the set_setting() fix in helpers.php for why (native prepares
        // don't allow binding the same named parameter twice).
        $db->prepare(
            'INSERT INTO budgets (category_id, budget_year, budget_month, planned_amount)
             VALUES (:cid, :y, :m, :amount)
             ON DUPLICATE KEY UPDATE planned_amount = VALUES(planned_amount)'
        )->execute(['cid' => $categoryId, 'y' => $year, 'm' => $monthNum, 'amount' => $normalized]);
    }

    if ($errors) {
        $_SESSION['budgets_errors'] = $errors;
        $_SESSION['budgets_old'] = $amounts;
    } else {
        $_SESSION['budgets_flash'] = 'Budgets saved.';
    }
    header('Location: budgets.php?month=' . $month);
    exit;
}

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

$copiedNotice = copy_budgets_forward_if_needed($month);

$categories = get_active_expense_categories();
$budgetMap = get_month_budget_map($month);
$plannedTotal = get_month_planned_total($month);

$flash = $_SESSION['budgets_flash'] ?? null;
$errors = $_SESSION['budgets_errors'] ?? [];
$oldAmounts = $_SESSION['budgets_old'] ?? null;
unset($_SESSION['budgets_flash'], $_SESSION['budgets_errors'], $_SESSION['budgets_old']);

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

<?php if ($flash): ?>
  <div class="alert alert-success py-2 small"><?= e($flash) ?></div>
<?php endif; ?>
<?php if ($copiedNotice): ?>
  <div class="alert alert-info py-2 small"><i class="bi bi-info-circle me-1"></i>Budgets copied from <?= e(month_label($prevMonth)) ?> — adjust anytime.</div>
<?php endif; ?>

<section class="card-x p-3 p-lg-4" aria-label="Budgets for <?= e(month_label($month)) ?>">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <div class="sec-title"><?= e(month_label($month)) ?> budgets</div>
    <div class="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="post">
    <?= csrf_field() ?>
    <input type="hidden" name="month" value="<?= e($month) ?>">

    <?php foreach ($categories as $i => $cat): ?>
      <?php
        $cid = (int) $cat['id'];
        $value = $oldAmounts[$cid] ?? ($budgetMap[$cid] ?? '');
      ?>
      <div class="d-flex align-items-center gap-2 py-2<?= $i > 0 ? ' border-top' : '' ?>" style="border-color:var(--line);">
        <span class="hrow-ic" style="--c:<?= e($cat['color']) ?>"><i class="bi <?= e(category_icon($cat['name'])) ?>"></i></span>
        <span class="flex-grow-1"><?= e($cat['name']) ?></span>
        <div class="amount-wrap" style="padding:.35rem .7rem;">
          <span class="amount-cur" style="font-size:1rem;"><?= e(get_setting('currency_symbol', '¥')) ?></span>
          <input class="amount-in tnum" style="font-size:1.05rem;" type="text" inputmode="decimal"
                 name="amounts[<?= e((string) $cid) ?>]" value="<?= e((string) $value) ?>" placeholder="0.00"
                 <?= $isAdmin ? '' : 'disabled' ?>>
        </div>
      </div>
      <?php if (isset($errors[$cid])): ?>
        <div class="field-error text-end"><?= e($errors[$cid]) ?></div>
      <?php endif; ?>
    <?php endforeach; ?>

    <div class="d-flex justify-content-between align-items-center mt-3 pt-3 border-top" style="border-color:var(--line);">
      <span class="fw-semibold">Planned total</span>
      <span class="tnum fw-bold fs-5"><?= e(format_money($plannedTotal)) ?></span>
    </div>

    <?php if ($isAdmin): ?>
      <button class="btn-save" type="submit">Save budgets</button>
    <?php endif; ?>
  </form>
</section>

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