<?php
include 'connect.php';
    $categoryName = $_POST['categoryName'];
    $categoryColor = $_POST['categoryColor'];
    $categoryID=$_POST['cat_id'];
    // Check if the 'categoryImage' field is set (user has changed the image)
    if (isset($_FILES['categoryImage'])) {
        $imageName = $_FILES['categoryImage']['name'];
        $imageTmp = $_FILES['categoryImage']['tmp_name'];
        $imageExtension = pathinfo($imageName, PATHINFO_EXTENSION); // Get the file extension
        
        $folderName = "../images/categories/";
        $newImageName = uniqid() . '.' . $imageExtension;
        $destination = $folderName . $newImageName;
        $image = "images/categories/" . $newImageName;
        
        // Check if the uploaded file is a PNG image
        if (strtolower($imageExtension) != 'png') {
            echo "Only PNG images are accepted.";
            exit;
        }
        
        if (move_uploaded_file($imageTmp, $destination)) {
            // Update all fields
            $sql = "UPDATE a_categories SET CategoryName = '$categoryName', CategoryImage = '$image', CategoryColor = '$categoryColor' WHERE CategoryID=$categoryID";
        } else {
            echo "Error uploading the image.";
        }
    } else {
        // User hasn't changed the image, update only specific fields
        $sql = "UPDATE a_categories SET CategoryName = '$categoryName', CategoryColor = '$categoryColor' WHERE CategoryID=$categoryID";
    }

    // Execute the SQL query
    $result = mysqli_query($con, $sql);

    if ($result) {
        echo "Category updated successfully.";
    } else {
        echo "Error updating category: " . mysqli_error($con);
    }

?>
