<?php
// Manage — categories and payment methods (Section 8, A10/A11, Phase 7).
// Categories has an expense/income type filter (Phase 9) so income
// categories (Paycheck, Bonus, ...) are manageable here too, reusing the
// exact same add/edit/reorder logic, just scoped by type.
// An "advanced" page (Section 3): plain POST/redirect/GET forms, no fetch —
// unlike the dashboard, nothing here needs to feel instant, and this way it
// works with JavaScript off too.
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(); // Manage is Motaher-only — Sumona no longer sees this page at all.

$isAdmin = current_user_is_admin();

$db = get_db();
$activeTab = ($_GET['tab'] ?? 'categories') === 'payment_methods' ? 'payment_methods' : 'categories';
$categoryType = ($_GET['category_type'] ?? 'expense') === 'income' ? 'income' : 'expense';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$isAdmin) {
        header('Location: index.php');
        exit;
    }
    $errors = [];
    $flash = null;
    $action = (string) ($_POST['action'] ?? '');
    $postedCategoryType = ($_POST['category_type'] ?? 'expense') === 'income' ? 'income' : 'expense';
    $categoryType = $postedCategoryType;

    if (!csrf_verify($_POST['csrf_token'] ?? null)) {
        $errors['general'] = 'Your session expired — please try again.';
    } elseif ($action === 'save_category') {
        $id = (int) ($_POST['id'] ?? 0);
        $result = validate_category_input($_POST, $id > 0 ? $id : null, $postedCategoryType);
        $errors = $result['errors'];
        if (!$errors) {
            $isActive = isset($_POST['is_active']) ? 1 : 0;
            if ($id > 0) {
                $db->prepare('UPDATE categories SET name = :name, color = :color, is_active = :active WHERE id = :id')
                    ->execute(['name' => $result['data']['name'], 'color' => $result['data']['color'], 'active' => $isActive, 'id' => $id]);
                $flash = 'Category updated.';
            } else {
                $orderStmt = $db->prepare('SELECT COALESCE(MAX(sort_order), 0) + 1 FROM categories WHERE type = :type');
                $orderStmt->execute(['type' => $postedCategoryType]);
                $nextOrder = (int) $orderStmt->fetchColumn();
                $db->prepare('INSERT INTO categories (name, type, color, sort_order, is_active) VALUES (:name, :type, :color, :sort_order, 1)')
                    ->execute(['name' => $result['data']['name'], 'type' => $postedCategoryType, 'color' => $result['data']['color'], 'sort_order' => $nextOrder]);
                $flash = 'Category added.';
            }
        }
    } elseif ($action === 'reorder_category') {
        $id = (int) ($_POST['id'] ?? 0);
        $direction = $_POST['direction'] ?? '';
        $stmt = $db->prepare('SELECT sort_order FROM categories WHERE id = :id AND type = :type');
        $stmt->execute(['id' => $id, 'type' => $postedCategoryType]);
        $current = $stmt->fetchColumn();
        if ($current !== false) {
            $comparator = $direction === 'up' ? '<' : '>';
            $order = $direction === 'up' ? 'DESC' : 'ASC';
            $stmt = $db->prepare(
                "SELECT id, sort_order FROM categories WHERE type = :type AND sort_order $comparator :current
                 ORDER BY sort_order $order LIMIT 1"
            );
            $stmt->execute(['type' => $postedCategoryType, 'current' => $current]);
            $neighbor = $stmt->fetch();
            if ($neighbor) {
                $db->prepare('UPDATE categories SET sort_order = :order WHERE id = :id')->execute(['order' => $neighbor['sort_order'], 'id' => $id]);
                $db->prepare('UPDATE categories SET sort_order = :order WHERE id = :id')->execute(['order' => $current, 'id' => $neighbor['id']]);
            }
        }
    } elseif ($action === 'save_payment_method') {
        $id = (int) ($_POST['id'] ?? 0);
        $result = validate_payment_method_input($_POST, $id > 0 ? $id : null);
        $errors = $result['errors'];
        if (!$errors) {
            $isActive = isset($_POST['is_active']) ? 1 : 0;
            if ($id > 0) {
                $db->prepare('UPDATE payment_methods SET name = :name, is_active = :active WHERE id = :id')
                    ->execute(['name' => $result['data']['name'], 'active' => $isActive, 'id' => $id]);
                $flash = 'Payment method updated.';
            } else {
                $nextOrder = (int) $db->query('SELECT COALESCE(MAX(sort_order), 0) + 1 FROM payment_methods')->fetchColumn();
                $db->prepare('INSERT INTO payment_methods (name, sort_order, is_active) VALUES (:name, :sort_order, 1)')
                    ->execute(['name' => $result['data']['name'], 'sort_order' => $nextOrder]);
                $flash = 'Payment method added.';
            }
        }
    } elseif ($action === 'reorder_payment_method') {
        $id = (int) ($_POST['id'] ?? 0);
        $direction = $_POST['direction'] ?? '';
        $stmt = $db->prepare('SELECT sort_order FROM payment_methods WHERE id = :id');
        $stmt->execute(['id' => $id]);
        $current = $stmt->fetchColumn();
        if ($current !== false) {
            $comparator = $direction === 'up' ? '<' : '>';
            $order = $direction === 'up' ? 'DESC' : 'ASC';
            $stmt = $db->prepare(
                "SELECT id, sort_order FROM payment_methods WHERE sort_order $comparator :current ORDER BY sort_order $order LIMIT 1"
            );
            $stmt->execute(['current' => $current]);
            $neighbor = $stmt->fetch();
            if ($neighbor) {
                $db->prepare('UPDATE payment_methods SET sort_order = :order WHERE id = :id')->execute(['order' => $neighbor['sort_order'], 'id' => $id]);
                $db->prepare('UPDATE payment_methods SET sort_order = :order WHERE id = :id')->execute(['order' => $current, 'id' => $neighbor['id']]);
            }
        }
    }

    if ($errors) {
        $_SESSION['manage_errors'] = $errors;
        $_SESSION['manage_old'] = $_POST;
    } elseif ($flash) {
        $_SESSION['manage_flash'] = $flash;
    }
    $redirect = 'manage.php?tab=' . $activeTab;
    if ($activeTab === 'categories') {
        $redirect .= '&category_type=' . $categoryType;
    }
    header('Location: ' . $redirect);
    exit;
}

$flash = $_SESSION['manage_flash'] ?? null;
$errors = $_SESSION['manage_errors'] ?? [];
$oldInput = $_SESSION['manage_old'] ?? [];
unset($_SESSION['manage_flash'], $_SESSION['manage_errors'], $_SESSION['manage_old']);

$categories = $db->prepare('SELECT * FROM categories WHERE type = :type ORDER BY sort_order');
$categories->execute(['type' => $categoryType]);
$categories = $categories->fetchAll();
$paymentMethods = $db->query('SELECT * FROM payment_methods ORDER BY sort_order')->fetchAll();

$pageTitle = 'Manage';
$currentPage = 'manage';
require __DIR__ . '/includes/layout/header.php';
?>

<?php if ($flash): ?>
  <div class="alert alert-success py-2 small"><?= e($flash) ?></div>
<?php endif; ?>
<?php if (isset($errors['general'])): ?>
  <div class="alert alert-danger py-2 small"><?= e($errors['general']) ?></div>
<?php endif; ?>

<ul class="nav nav-tabs mb-3" role="tablist">
  <li class="nav-item" role="presentation">
    <a class="nav-link<?= $activeTab === 'categories' ? ' active' : '' ?>" href="manage.php?tab=categories&category_type=<?= e($categoryType) ?>">Categories</a>
  </li>
  <li class="nav-item" role="presentation">
    <a class="nav-link<?= $activeTab === 'payment_methods' ? ' active' : '' ?>" href="manage.php?tab=payment_methods">Payment methods</a>
  </li>
</ul>

<?php if ($activeTab === 'categories'): ?>

  <div class="btn-group mb-3" role="group" aria-label="Category type">
    <a href="manage.php?tab=categories&category_type=expense" class="btn btn-sm <?= $categoryType === 'expense' ? 'btn-accent' : 'btn-outline-secondary' ?>">Expense</a>
    <a href="manage.php?tab=categories&category_type=income" class="btn btn-sm <?= $categoryType === 'income' ? 'btn-accent' : 'btn-outline-secondary' ?>">Income</a>
  </div>

  <?php if ($isAdmin): ?>
  <section class="card-x p-3 p-lg-4 mb-3" aria-label="Add category">
    <div class="sec-title mb-2">Add a <?= e($categoryType) ?> category</div>
    <form method="post" class="row g-2 align-items-end">
      <?= csrf_field() ?>
      <input type="hidden" name="action" value="save_category">
      <input type="hidden" name="category_type" value="<?= e($categoryType) ?>">
      <div class="col-auto">
        <label class="field-label mt-0" for="new_cat_color">Color</label>
        <input type="color" class="form-control form-control-color" id="new_cat_color" name="color"
               value="<?= e($oldInput['color'] ?? '#5a5bd8') ?>" title="Choose a color">
      </div>
      <div class="col">
        <label class="field-label mt-0" for="new_cat_name">Name</label>
        <input class="form-control" type="text" id="new_cat_name" name="name" maxlength="50" value="<?= e($oldInput['name'] ?? '') ?>">
        <?php if (isset($errors['name']) && ($oldInput['action'] ?? '') === 'save_category' && empty($oldInput['id'])): ?>
          <div class="field-error"><?= e($errors['name']) ?></div>
        <?php endif; ?>
      </div>
      <div class="col-auto">
        <button class="btn-accent" type="submit">Add category</button>
      </div>
    </form>
  </section>
  <?php endif; ?>

  <section class="card-x p-3 p-lg-4" aria-label="Categories">
    <?php foreach ($categories as $i => $cat): ?>
      <div class="d-flex align-items-center gap-2 py-2<?= $i > 0 ? ' border-top' : '' ?>" style="border-color:var(--line);">
        <form method="post" class="d-flex align-items-center gap-2 flex-grow-1 flex-wrap">
          <?= csrf_field() ?>
          <input type="hidden" name="action" value="save_category">
          <input type="hidden" name="category_type" value="<?= e($categoryType) ?>">
          <input type="hidden" name="id" value="<?= e((string) $cat['id']) ?>">
          <input type="color" class="form-control form-control-color" name="color" value="<?= e($cat['color']) ?>" style="width:2.5rem;" title="Choose a color" <?= $isAdmin ? '' : 'disabled' ?>>
          <input class="form-control" type="text" name="name" maxlength="50" value="<?= e($cat['name']) ?>" style="max-width:220px;" <?= $isAdmin ? '' : 'disabled' ?>>
          <div class="form-check form-switch mb-0">
            <input class="form-check-input" type="checkbox" role="switch" name="is_active" value="1" <?= $cat['is_active'] ? 'checked' : '' ?> <?= $isAdmin ? '' : 'disabled' ?>>
            <label class="form-check-label small text-secondary">Active</label>
          </div>
          <?php if ($isAdmin): ?>
            <button class="btn btn-sm btn-outline-secondary" type="submit">Save</button>
          <?php endif; ?>
          <?php if ((int) ($oldInput['id'] ?? 0) === (int) $cat['id'] && ($oldInput['action'] ?? '') === 'save_category'): ?>
            <?php if (isset($errors['name'])): ?><span class="field-error mb-0"><?= e($errors['name']) ?></span><?php endif; ?>
            <?php if (isset($errors['color'])): ?><span class="field-error mb-0"><?= e($errors['color']) ?></span><?php endif; ?>
          <?php endif; ?>
        </form>
        <?php if ($isAdmin): ?>
        <form method="post" class="d-flex gap-1">
          <?= csrf_field() ?>
          <input type="hidden" name="action" value="reorder_category">
          <input type="hidden" name="category_type" value="<?= e($categoryType) ?>">
          <input type="hidden" name="id" value="<?= e((string) $cat['id']) ?>">
          <button class="btn btn-sm btn-outline-secondary" type="submit" name="direction" value="up" <?= $i === 0 ? 'disabled' : '' ?> aria-label="Move up"><i class="bi bi-arrow-up"></i></button>
          <button class="btn btn-sm btn-outline-secondary" type="submit" name="direction" value="down" <?= $i === count($categories) - 1 ? 'disabled' : '' ?> aria-label="Move down"><i class="bi bi-arrow-down"></i></button>
        </form>
        <?php endif; ?>
      </div>
    <?php endforeach; ?>
  </section>

<?php else: ?>

  <?php if ($isAdmin): ?>
  <section class="card-x p-3 p-lg-4 mb-3" aria-label="Add payment method">
    <div class="sec-title mb-2">Add a payment method</div>
    <form method="post" class="row g-2 align-items-end">
      <?= csrf_field() ?>
      <input type="hidden" name="action" value="save_payment_method">
      <div class="col">
        <label class="field-label mt-0" for="new_method_name">Name</label>
        <input class="form-control" type="text" id="new_method_name" name="name" maxlength="50" value="<?= e($oldInput['name'] ?? '') ?>">
        <?php if (isset($errors['name']) && ($oldInput['action'] ?? '') === 'save_payment_method' && empty($oldInput['id'])): ?>
          <div class="field-error"><?= e($errors['name']) ?></div>
        <?php endif; ?>
      </div>
      <div class="col-auto">
        <button class="btn-accent" type="submit">Add method</button>
      </div>
    </form>
  </section>
  <?php endif; ?>

  <section class="card-x p-3 p-lg-4" aria-label="Payment methods">
    <?php foreach ($paymentMethods as $i => $method): ?>
      <div class="d-flex align-items-center gap-2 py-2<?= $i > 0 ? ' border-top' : '' ?>" style="border-color:var(--line);">
        <form method="post" class="d-flex align-items-center gap-2 flex-grow-1 flex-wrap">
          <?= csrf_field() ?>
          <input type="hidden" name="action" value="save_payment_method">
          <input type="hidden" name="id" value="<?= e((string) $method['id']) ?>">
          <input class="form-control" type="text" name="name" maxlength="50" value="<?= e($method['name']) ?>" style="max-width:220px;" <?= $isAdmin ? '' : 'disabled' ?>>
          <div class="form-check form-switch mb-0">
            <input class="form-check-input" type="checkbox" role="switch" name="is_active" value="1" <?= $method['is_active'] ? 'checked' : '' ?> <?= $isAdmin ? '' : 'disabled' ?>>
            <label class="form-check-label small text-secondary">Active</label>
          </div>
          <?php if ($isAdmin): ?>
            <button class="btn btn-sm btn-outline-secondary" type="submit">Save</button>
          <?php endif; ?>
          <?php if ((int) ($oldInput['id'] ?? 0) === (int) $method['id'] && ($oldInput['action'] ?? '') === 'save_payment_method'): ?>
            <?php if (isset($errors['name'])): ?><span class="field-error mb-0"><?= e($errors['name']) ?></span><?php endif; ?>
          <?php endif; ?>
        </form>
        <?php if ($isAdmin): ?>
        <form method="post" class="d-flex gap-1">
          <?= csrf_field() ?>
          <input type="hidden" name="action" value="reorder_payment_method">
          <input type="hidden" name="id" value="<?= e((string) $method['id']) ?>">
          <button class="btn btn-sm btn-outline-secondary" type="submit" name="direction" value="up" <?= $i === 0 ? 'disabled' : '' ?> aria-label="Move up"><i class="bi bi-arrow-up"></i></button>
          <button class="btn btn-sm btn-outline-secondary" type="submit" name="direction" value="down" <?= $i === count($paymentMethods) - 1 ? 'disabled' : '' ?> aria-label="Move down"><i class="bi bi-arrow-down"></i></button>
        </form>
        <?php endif; ?>
      </div>
    <?php endforeach; ?>
  </section>

<?php endif; ?>

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