<?php
// POST /api/slips/categories.php
// action: list | add | delete
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user   = requireAuth();
$db     = getDB();
$action = post('action', 'list');

// Only admin/management can add/delete
if (in_array($action, ['add','delete']) && !in_array($user['role_id'], [1, 5])) {
    apiError('Not authorised.', 403);
}

if ($action === 'list') {
    $rows = $db->query("SELECT * FROM slip_categories ORDER BY sort_order ASC, name ASC")->fetchAll();
    apiSuccess(['categories' => $rows]);
}

if ($action === 'add') {
    $name = trim(post('name', ''));
    if (!$name) apiError('Category name required.', 422);
    // Check duplicate
    $dup = $db->prepare("SELECT id FROM slip_categories WHERE LOWER(name) = LOWER(?) LIMIT 1");
    $dup->execute([$name]);
    if ($dup->fetch()) apiError('Category already exists.', 409);

    $db->prepare("INSERT INTO slip_categories (name) VALUES (?)")->execute([$name]);
    $id = (int)$db->lastInsertId();
    apiSuccess(['id' => $id, 'name' => $name], 'Category added.');
}

if ($action === 'delete') {
    $id = (int)post('id', 0);
    if (!$id) apiError('ID required.', 422);

    // Fetch name first
    $row = $db->prepare("SELECT name FROM slip_categories WHERE id = ? LIMIT 1");
    $row->execute([$id]);
    $cat = $row->fetch();
    if (!$cat) apiError('Category not found.', 404);

    // Check if any slips use this category
    $used = $db->prepare("SELECT COUNT(*) FROM slips WHERE category = ? LIMIT 1");
    $used->execute([$cat['name']]);
    if ((int)$used->fetchColumn() > 0) {
        apiError("Cannot delete — slips exist with category \"{$cat['name']}\". Reassign them first.", 409);
    }

    $db->prepare("DELETE FROM slip_categories WHERE id = ?")->execute([$id]);
    apiSuccess([], 'Category deleted.');
}

apiError('Unknown action.', 422);