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

$name = trim($_POST['name'] ?? '');
$icon = '';

if (empty($name)) {
    echo json_encode(["success" => false, "message" => "Product type name is required"]);
    exit;
}

// Step 1: Check if name already exists
$checkQuery = "SELECT id FROM tbl_product_type WHERE LOWER(name) = LOWER(?)";
$stmt = $conn->prepare($checkQuery);
$stmt->bind_param("s", $name);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    echo json_encode(["success" => false, "message" => "This product type already exists"]);
    $stmt->close();
    $conn->close();
    exit;
}
$stmt->close();

// Step 2: Handle image upload
if (isset($_FILES['icon']) && $_FILES['icon']['error'] === UPLOAD_ERR_OK) {
    $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;
    }
}

// Step 3: Insert new record
$sql = "INSERT INTO tbl_product_type (name, icon) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $name, $icon);

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

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