<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user   = requireAuth();
$db     = getDB();
$action = post('action', 'list');

if ($action === 'list') {
    $stmt = $db->query("SELECT id, name, description FROM stock_categories ORDER BY name");
    apiSuccess(['categories' => $stmt->fetchAll()]);
}
requireRole([1]);
if ($action === 'save') {
    $id   = (int)post('id', 0);
    $name = trim(post('name', ''));
    if (!$name) apiError('Name required.', 422);
    if ($id) {
        $db->prepare("UPDATE stock_categories SET name=?, description=? WHERE id=?")->execute([$name, post('description'), $id]);
        apiSuccess(['id' => $id], 'Updated.');
    } else {
        $db->prepare("INSERT INTO stock_categories (name, description) VALUES (?,?)")->execute([$name, post('description')]);
        apiSuccess(['id' => (int)$db->lastInsertId()], 'Category created.');
    }
}
if ($action === 'delete') {
    $db->prepare("UPDATE stock_items SET category_id=NULL WHERE category_id=?")->execute([(int)post('id')]);
    $db->prepare("DELETE FROM stock_categories WHERE id=?")->execute([(int)post('id')]);
    apiSuccess([], 'Deleted.');
}
apiError('Unknown action.', 400);
