<?php
include 'includes/config.php';

$action = $_POST['action'] ?? '';

if ($action == 'fetch') {
    $stmt = $conn->query("SELECT * FROM colors ORDER BY id DESC");
    echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    exit;
}

if ($action == 'add') {
    $name = trim($_POST['name']);
    $color = trim($_POST['color']);
    $stmt = $conn->prepare("INSERT INTO colors (name, product_color) VALUES (?, ?)");
    $stmt->execute([$name, $color]);
    echo "success";
    exit;
}

if ($action == 'get') {
    $id = intval($_POST['id']);
    $stmt = $conn->prepare("SELECT * FROM colors WHERE id = ?");
    $stmt->execute([$id]);
    echo json_encode($stmt->fetch(PDO::FETCH_ASSOC));
    exit;
}

if ($action == 'update') {
    $id = intval($_POST['id']);
    $name = trim($_POST['name']);
    $color = trim($_POST['color']);
    $stmt = $conn->prepare("UPDATE colors SET name = ?, product_color = ? WHERE id = ?");
    $stmt->execute([$name, $color, $id]);
    echo "success";
    exit;
}

if ($action == 'delete') {
    $id = intval($_POST['id']);
    $stmt = $conn->prepare("DELETE FROM colors WHERE id = ?");
    $stmt->execute([$id]);
    echo "success";
    exit;
}
