<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
include '../connection.php';

$id = $_POST['id'];
$name = $_POST['name'];
$icon = '';

if (isset($_FILES['icon'])) {
    $target_dir = "../uploadicon/product_icons/";
    if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
    $file_name = time() . "_" . basename($_FILES["icon"]["name"]);
    $target_file = $target_dir . $file_name;
    if (move_uploaded_file($_FILES["icon"]["tmp_name"], $target_file)) {
        $icon = $file_name;
        $sql = "UPDATE tbl_product_type SET name=?, icon=? WHERE id=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssi", $name, $icon, $id);
    }
} else {
    $sql = "UPDATE tbl_product_type SET name=? WHERE id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("si", $name, $id);
}

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Product type updated successfully"]);
} else {
    echo json_encode(["success" => false, "message" => $stmt->error]);
}

$stmt->close();
$conn->close();
?>
