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

$type = $_GET['type'] ?? 'category';
$id = $_GET['id'] ?? null;
$item = null;
$page_title = 'Nou';

$type_names = [
    'category' => 'Categorie',
    'order' => 'Status Comandă',
    'client' => 'Status Client'
];

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

$table = $tables[$type] ?? 'categories';
$type_name = $type_names[$type] ?? 'Element';

if ($id) {
    $id = (int)$id;
    $result = $db->query("SELECT * FROM $table WHERE id = $id");
    $item = $result ? $result->fetch_assoc() : null;
    
    if (!$item) {
        redirectWithMessage(APP_URL . '/admin/settings.php', 'Element nu a fost găsit', 'error');
    }
    $page_title = 'Editează: ' . htmlspecialchars($item['name']);
}

require_once __DIR__ . '/../includes/header.php';
?>

<div class="card" style="max-width:500px">
    <div class="card-header">
        <div class="card-title"><?php echo $item ? 'Editează ' . $type_name : $type_name . ' nou(ă)'; ?></div>
    </div>
    <div class="card-body">
        <form method="POST" action="<?php echo APP_URL; ?>/api/save-status.php" style="display:grid;gap:14px">
            <input type="hidden" name="type" value="<?php echo htmlspecialchars($type); ?>">
            <?php if ($item): ?>
                <input type="hidden" name="id" value="<?php echo $item['id']; ?>">
            <?php endif; ?>

            <div class="form-group full">
                <label class="form-label">Nume *</label>
                <input class="form-input" name="name" value="<?php echo $item ? htmlspecialchars($item['name']) : ''; ?>" placeholder="Ex: Activ" required autofocus>
            </div>

            <div class="form-group full">
                <label class="form-label">Culoare</label>
                <input class="form-input" type="color" name="color" value="<?php echo $item ? htmlspecialchars($item['color']) : '#4A8FD4'; ?>" style="height:42px;cursor:pointer">
            </div>

            <div style="display:flex;gap:10px;margin-top:20px">
                <a href="<?php echo APP_URL; ?>/admin/settings.php" class="btn btn-ghost" style="flex:1;text-align:center;text-decoration:none">Anulează</a>
                <button type="submit" class="btn btn-primary" style="flex:1">✓ Salvează</button>
            </div>
        </form>
    </div>
</div>

<?php
require_once __DIR__ . '/../includes/footer.php';
?>
