<?php
require_once __DIR__ . '/includes/expense_common.php';
expense_require_role(['admin','superadmin']);
expense_ensure_schema($conn);

$username = $_SESSION['username'] ?? 'Admin';
$role = $_SESSION['role'];
$csrf_token = expense_csrf_token();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!expense_csrf_valid()) {
        set_flash('danger', 'Invalid request.');
        header("Location: expense_settings.php");
        exit();
    }
    $action = $_POST['action'] ?? '';

    if ($action === 'add_category') {
        $name = trim($_POST['name'] ?? '');
        $max  = trim($_POST['max_amount'] ?? '');
        $max_val = ($max === '' ? null : (float)$max);
        if ($name === '') {
            set_flash('warning', 'Category name is required.');
        } else {
            $stmt = $conn->prepare("INSERT INTO expense_categories (name, max_amount, active) VALUES (?,?,1)");
            $stmt->bind_param("sd", $name, $max_val);
            $stmt->execute() ? set_flash('success', "Category '$name' added.") : set_flash('danger', 'Error: ' . $stmt->error);
            $stmt->close();
        }
    } elseif ($action === 'update_category') {
        $id  = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $max  = trim($_POST['max_amount'] ?? '');
        $max_val = ($max === '' ? null : (float)$max);
        $active = isset($_POST['active']) ? 1 : 0;
        if ($name === '') {
            set_flash('warning', 'Category name is required.');
        } else {
            $stmt = $conn->prepare("UPDATE expense_categories SET name=?, max_amount=?, active=? WHERE id=?");
            $stmt->bind_param("sdii", $name, $max_val, $active, $id);
            $stmt->execute() ? set_flash('success', 'Category updated.') : set_flash('danger', 'Error: ' . $stmt->error);
            $stmt->close();
        }
    } elseif ($action === 'delete_category') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $conn->prepare("DELETE FROM expense_categories WHERE id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute() ? set_flash('success', 'Category removed.') : set_flash('danger', 'Error: ' . $stmt->error);
        $stmt->close();
    }
    header("Location: expense_settings.php");
    exit();
}

$categories = $conn->query("SELECT * FROM expense_categories ORDER BY name")->fetch_all(MYSQLI_ASSOC);

require_once __DIR__ . '/includes/expense_theme.php';
expense_render_head('Settings');
expense_render_sidebar_and_topbar($role, $username, 'expense_settings.php', 'Settings');
?>
  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">Expense Settings</div>
        <div class="page-subtitle">Manage expense categories and per-category claim limits</div>
      </div>
    </div>

    <?php expense_render_flash(); ?>

    <div class="dash-card">
      <div class="dash-card-header"><div class="dash-card-title"><i class="fas fa-circle-plus"></i> Add Category</div></div>
      <div class="dash-card-body">
        <form method="POST" class="filter-bar" style="margin:0;align-items:flex-end">
          <input type="hidden" name="csrf" value="<?= h($csrf_token) ?>">
          <input type="hidden" name="action" value="add_category">
          <div>
            <label class="form-label">Category Name</label>
            <input type="text" name="name" required placeholder="e.g. Internet Reimbursement">
          </div>
          <div>
            <label class="form-label">Max Amount (₹, optional)</label>
            <input type="number" name="max_amount" step="0.01" min="0" placeholder="No limit">
          </div>
          <button type="submit" class="btn-action btn-finish"><i class="fas fa-plus" style="font-size:10px"></i> Add</button>
        </form>
      </div>
    </div>

    <div class="dash-card">
      <div class="dash-card-header"><div class="dash-card-title"><i class="fas fa-sliders"></i> Categories</div></div>
      <div class="dash-card-body" style="padding:0">
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead><tr><th>Name</th><th>Max Amount</th><th>Active</th><th></th></tr></thead>
            <tbody>
              <?php foreach ($categories as $cat): $fid = 'catform' . (int)$cat['id']; ?>
              <tr>
                  <td style="min-width:200px">
                    <input type="text" name="name" form="<?= $fid ?>" value="<?= h($cat['name']) ?>" class="form-control" style="padding:6px 10px">
                  </td>
                  <td style="min-width:140px">
                    <input type="number" name="max_amount" form="<?= $fid ?>" step="0.01" min="0" value="<?= h($cat['max_amount']) ?>" class="form-control" style="padding:6px 10px" placeholder="No limit">
                  </td>
                  <td><input type="checkbox" name="active" form="<?= $fid ?>" <?= $cat['active'] ? 'checked' : '' ?> style="width:18px;height:18px"></td>
                  <td style="white-space:nowrap">
                    <form id="<?= $fid ?>" method="POST" style="display:inline">
                      <input type="hidden" name="csrf" value="<?= h($csrf_token) ?>">
                      <input type="hidden" name="id" value="<?= (int)$cat['id'] ?>">
                      <button type="submit" name="action" value="update_category" class="btn-action btn-remarks" style="padding:5px 12px"><i class="fas fa-save" style="font-size:10px"></i></button>
                      <button type="submit" name="action" value="delete_category" class="btn-action btn-danger" style="padding:5px 12px" onclick="return confirm('Remove this category?')"><i class="fas fa-trash" style="font-size:10px"></i></button>
                    </form>
                  </td>
              </tr>
              <?php endforeach; ?>
              <?php if (empty($categories)): ?>
                <tr><td colspan="4"><div class="empty-state"><i class="fas fa-tags"></i><p>No categories yet.</p></div></td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
<?php expense_render_footer_scripts(); ?>
