<?php
/**
 * POST /api/admin/categories_update.php
 * Body (JSON): { id, name?, is_active? }
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

only_post_allowed();
require_login();
require_role(['admin']);

$input = get_json_input();
$id = (int) ($input['id'] ?? 0);
if ($id <= 0) {
    send_error('A valid category id is required.', 422);
}

$set = [];
$params = [];
if (array_key_exists('name', $input)) {
    $name = trim($input['name']);
    if ($name === '') {
        send_error('Category name cannot be empty.', 422);
    }
    $set[] = 'name = ?';
    $params[] = $name;
}
if (array_key_exists('is_active', $input)) {
    $set[] = 'is_active = ?';
    $params[] = !empty($input['is_active']) ? 1 : 0;
}

if (!$set) {
    send_error('Nothing to update.', 422);
}

$pdo = Database::connect();
$params[] = $id;
$stmt = $pdo->prepare('UPDATE categories SET ' . implode(', ', $set) . ' WHERE id = ?');
$stmt->execute($params);

send_json(true, 'Category updated.');
