<?php
include "../db.php";

if($_SERVER['REQUEST_METHOD'] !== 'POST'){
    echo json_encode(["error"=>"Invalid request"]);
    exit;
}

$id = $_POST['id'] ?? '';
$name = $_POST['name'] ?? '';
$price = $_POST['price'] ?? '';
$description = $_POST['description'] ?? '';
$category = $_POST['category'] ?? '';

if(!$id){
    echo json_encode(["error"=>"Missing ID"]);
    exit;
}

if(empty($name) || empty($price)){
    echo json_encode(["error"=>"Missing fields"]);
    exit;
}

if(!empty($_FILES['image']['name'])){

    $imageName = time().'_'.$_FILES['image']['name'];
    move_uploaded_file($_FILES['image']['tmp_name'], "uploads/".$imageName);

    $stmt = $conn->prepare("UPDATE merch_items SET name=?,price=?,description=?,image=?,category=? WHERE id=?");
    $stmt->bind_param("sdsssi",$name,$price,$description,$imageName,$category,$id);

} else {

    $stmt = $conn->prepare("UPDATE merch_items SET name=?,price=?,description=?,category=? WHERE id=?");
    $stmt->bind_param("sdssi",$name,$price,$description,$category,$id);
}

$stmt->execute();

echo json_encode(["success"=>true]);
