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

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

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

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

if ($action == 'get') {
    $id = intval($_POST['id']);
    $stmt = $conn->prepare("SELECT * FROM sizes 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']);
    $size = trim($_POST['size']);
    $stmt = $conn->prepare("UPDATE sizes SET name = ?, product_size = ? WHERE id = ?");
    $stmt->execute([$name, $size, $id]);
    echo "success";
    exit;
}

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