<?php
require_once __DIR__ . '/../includes/config.php';

if (!isLoggedIn()) {
    redirectWithMessage(APP_URL . '/login.php', 'Unauthorized', 'error');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirectWithMessage(APP_URL . '/admin/settings.php', 'Invalid request', 'error');
}

$type = escape($_POST['type'] ?? '');
$id = $_POST['id'] ?? null;
$name = escape($_POST['name'] ?? '');
$color = escape($_POST['color'] ?? '#4A8FD4');

$tables = [
    'category' => 'categories',
    'order' => 'order_statuses',
    'client' => 'client_statuses'
];

$table = $tables[$type] ?? null;

if (!$table || empty($name)) {
    redirectWithMessage(APP_URL . '/admin/settings.php', 'Eroare: date nevalide', 'error');
}

if ($id) {
    $id = (int)$id;
    $db->query("UPDATE $table SET name='$name', color='$color' WHERE id=$id");
    redirectWithMessage(APP_URL . '/admin/settings.php', 'Actualizat cu succes', 'success');
} else {
    $db->query("INSERT INTO $table (name, color) VALUES ('$name', '$color')");
    redirectWithMessage(APP_URL . '/admin/settings.php', 'Adăugat cu succes', 'success');
}
?>
