upload of images seems not to work here please help:
admin.php:
<?php
header('Content-Type: application/json');
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Database configuration
$host = "localhost";
$user = "loveesse_tester";
$password = "Baby@0987#";
$dbname = "loveesse_shop";

// Establish database connection
$conn = new mysqli($host, $user, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die(json_encode(['status' => 'error', 'message' => 'Connection failed: ' . $conn->connect_error]));
}

// Handle different types of requests
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (isset($_GET['action']) && $_GET['action'] === 'get_product' && isset($_GET['id'])) {
        handleGetSingleProduct($conn);
    } else {
        handleGetAllProducts($conn);
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'add':
        case 'edit':
            handleProductSave($conn, $action);
            break;
        case 'delete':
            handleProductDelete($conn);
            break;
        case 'feature':
            handleProductFeature($conn);
            break;
        default:
            echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
    }
}

$conn->close();

function handleGetSingleProduct($conn) {
    $productId = intval($_GET['id']);
    $stmt = $conn->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->bind_param("i", $productId);
    $stmt->execute();
    $result = $stmt->get_result();
    $product = $result->fetch_assoc();
    
    if ($product) {
        $product['images'] = json_decode($product['images']);
        echo json_encode(['status' => 'success', 'product' => $product]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Product not found']);
    }
    $stmt->close();
}

function handleGetAllProducts($conn) {
    $result = $conn->query("SELECT * FROM products");
    $products = [];
    while ($row = $result->fetch_assoc()) {
        $row['images'] = json_decode($row['images']);
        $products[] = $row;
    }
    echo json_encode(['status' => 'success', 'products' => $products]);
}

function handleProductSave($conn, $action) {
    $id = isset($_POST['id']) ? intval($_POST['id']) : null;
    $name = $_POST['productName'] ?? '';
    $price = floatval($_POST['productPrice'] ?? 0);
    $stock = intval($_POST['productStock'] ?? 0);
    $category = $_POST['productCategory'] ?? '';
    $description = $_POST['productDescription'] ?? '';
    $color = $_POST['productColor'] ?? '';  // Added color handling
    
    // Handle image uploads
    $uploadDir = '../static/images/';
    $existingImages = [];
    $newImages = [];
    
    if ($action === 'edit' && $id) {
        // Get existing images
        $stmt = $conn->prepare("SELECT images FROM products WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $product = $result->fetch_assoc();
        if ($product) {
            $existingImages = json_decode($product['images'], true) ?? [];
        }
        $stmt->close();
        
        // Handle image removals
        if (isset($_POST['imagesToRemove'])) {
            $imagesToRemove = json_decode($_POST['imagesToRemove'], true) ?? [];
            $existingImages = array_values(array_diff($existingImages, $imagesToRemove));
        }
    }
    
    // Handle new image uploads
    if (isset($_FILES['images'])) {
        $fileCount = count($_FILES['images']['name']);
        for ($i = 0; $i < $fileCount; $i++) {
            if ($_FILES['images']['error'][$i] === 0) {
                $tempName = $_FILES['images']['tmp_name'][$i];
                $originalName = $_FILES['images']['name'][$i];
                $fileExtension = pathinfo($originalName, PATHINFO_EXTENSION);
                $newFileName = uniqid() . '.' . $fileExtension;
                $uploadPath = $uploadDir . $newFileName;
                
                if (move_uploaded_file($tempName, $uploadPath)) {
                    $newImages[] = '/static/images/' . $newFileName;
                }
            }
        }
    }
    
    // Combine existing and new images
    $allImages = array_values(array_merge($existingImages, $newImages));
    $imagesJson = json_encode($allImages);
    
    if ($action === 'edit' && $id) {
        $stmt = $conn->prepare("UPDATE products SET name=?, price=?, stock=?, category=?, description=?, images=?, color=? WHERE id=?");
        $stmt->bind_param("sdissssi", $name, $price, $stock, $category, $description, $imagesJson, $color, $id);
    } else {
        $stmt = $conn->prepare("INSERT INTO products (name, price, stock, category, description, images, color) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sdissss", $name, $price, $stock, $category, $description, $imagesJson, $color);
    }
    
    if ($stmt->execute()) {
        $response = [
            'status' => 'success',
            'message' => $action === 'edit' ? 'Product updated successfully' : 'Product added successfully',
            'id' => $action === 'edit' ? $id : $stmt->insert_id,
            'images' => $allImages
        ];
    } else {
        $response = ['status' => 'error', 'message' => $stmt->error];
    }
    
    $stmt->close();
    echo json_encode($response);
}

function handleProductDelete($conn) {
    $id = intval($_POST['id'] ?? 0);
    
    // First, get the images to delete them from the server
    $stmt = $conn->prepare("SELECT images FROM products WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $product = $result->fetch_assoc();
    $stmt->close();
    
    if ($product) {
        $images = json_decode($product['images'], true) ?? [];
        foreach ($images as $image) {
            $fullPath = $_SERVER['DOCUMENT_ROOT'] . $image;
            if (file_exists($fullPath)) {
                unlink($fullPath);
            }
        }
    }
    
    $stmt = $conn->prepare("DELETE FROM products WHERE id = ?");
    $stmt->bind_param("i", $id);
    
    if ($stmt->execute()) {
        $response = ['status' => 'success', 'message' => 'Product deleted successfully'];
    } else {
        $response = ['status' => 'error', 'message' => $stmt->error];
    }
    
    $stmt->close();
    echo json_encode($response);
}

function handleProductFeature($conn) {
    $id = intval($_POST['id'] ?? 0);
    
    $stmt = $conn->prepare("UPDATE products SET featured = NOT featured WHERE id = ?");
    $stmt->bind_param("i", $id);
    
    if ($stmt->execute()) {
        $response = ['status' => 'success', 'message' => 'Product feature status toggled successfully'];
    } else {
        $response = ['status' => 'error', 'message' => $stmt->error];
    }
    
    $stmt->close();
    echo json_encode($response);
}
?>
admin.js:
// Global Variables
let isLoggedIn = false;
let productCache = new Map();

// DOM Elements
const loginForm = document.getElementById('loginForm');
const adminSection = document.getElementById('adminSection');
const loginSection = document.getElementById('loginSection');
const productFormElement = document.getElementById('productFormElement');
const productTable = document.getElementById('productTable');

// Event Listeners
document.addEventListener('DOMContentLoaded', () => {
    initializeApp();
    if (loginForm) loginForm.addEventListener('submit', handleLogin);
    if (productFormElement) productFormElement.addEventListener('submit', handleProductSubmit);
    if (productTable) productTable.addEventListener('click', handleProductTableActions);
});

// Initialize App
function initializeApp() {
    hideForm();
    setupTabNavigation();
    const addProductButton = document.querySelector('#addProductButton');
    if (addProductButton) addProductButton.onclick = showAddForm;
}

function hideForm() {
    const productForm = document.getElementById('productForm');
    if (productForm) productForm.classList.add('d-none');
}

function showAddForm() {
    const productForm = document.getElementById('productForm');
    const productAction = document.getElementById('productAction');
    const formTitle = document.getElementById('formTitle');
    const imagePreviewContainer = document.getElementById('imagePreviewContainer');

    if (productForm && productAction && formTitle) {
        formTitle.textContent = 'Add Product';
        productAction.value = 'add';
        productFormElement.reset();
        if (imagePreviewContainer) imagePreviewContainer.innerHTML = '';
        productForm.classList.remove('d-none');
    }
}

function handleLogin(e) {
    e.preventDefault();
    const username = document.getElementById('username')?.value.trim();
    const password = document.getElementById('password')?.value.trim();

    if (username === 'admin' && password === 'admin') {
        isLoggedIn = true;
        loginSection.style.display = 'none';
        adminSection.style.display = 'block';
        renderProducts();
    } else {
        alert('Invalid credentials');
    }
}

async function handleProductSubmit(e) {
    e.preventDefault();
    const form = productFormElement;
    const formData = new FormData(form);

    // Handle images to remove
    const imagesToRemove = [];
    document.querySelectorAll('input[name="existingImagesToRemove[]"]:checked').forEach(checkbox => {
        imagesToRemove.push(checkbox.value);
    });
    formData.append('imagesToRemove', JSON.stringify(imagesToRemove));

    // Handle new images
    const imageFiles = document.getElementById('productImage').files;
    for (let i = 0; i < imageFiles.length; i++) {
        formData.append('images[]', imageFiles[i]);
    }

    const action = document.getElementById('productAction').value;
    formData.append('action', action);

    try {
        const response = await fetch('/php/admin.php', {
            method: 'POST',
            body: formData
        });
        const data = await response.json();

        if (data.status === 'success') {
            alert(data.message);
            hideForm();
            renderProducts();
        } else {
            alert(`Error: ${data.message}`);
        }
    } catch (error) {
        console.error('Error during product save operation:', error);
        alert('Failed to save product. Please try again.');
    }
}

function handleProductTableActions(e) {
    const btn = e.target;
    const productId = btn.dataset.id;
    
    if (!productId) return;

    if (btn.classList.contains('edit-btn')) {
        editProduct(productId);
    } else if (btn.classList.contains('delete-btn')) {
        if (confirm('Are you sure you want to delete this product?')) {
            deleteProduct(productId);
        }
    } else if (btn.classList.contains('feature-btn')) {
        featureProduct(productId);
    }
}

async function renderProducts() {
    try {
        const response = await fetch('/php/admin.php');
        const data = await response.json();

        if (!data.status === 'success' || !Array.isArray(data.products)) {
            throw new Error('Invalid data received from server');
        }

        productTable.innerHTML = '';
        data.products.forEach(product => {
            productCache.set(product.id, product);
            
            const imagesHtml = product.images && product.images.length > 0
                ? product.images.map(imagePath => 
                    `<img src="${imagePath}" alt="Product Image" style="width: 50px; height: 50px; margin: 2px;">`)
                    .join('')
                : 'No Image';

            const row = document.createElement('tr');
            row.innerHTML = `
                <td data-label="ID">${product.id}</td>
                <td data-label="Image">${imagesHtml}</td>
                <td data-label="Name">${product.name}</td>
                <td data-label="Price">${parseFloat(product.price).toFixed(2)} Ksh</td>
                <td data-label="Stock">${product.stock}</td>
                <td data-label="Category">${product.category}</td>
                <td data-label="Color">${product.color || 'N/A'}</td>
                <td data-label="Actions">
                    <button class="btn btn-success edit-btn" data-id="${product.id}">Edit</button>
                    <button class="btn btn-danger delete-btn" data-id="${product.id}">Delete</button>
                    <button class="btn btn-warning feature-btn" data-id="${product.id}">
                        ${product.featured ? 'Unfeature' : 'Feature'}
                    </button>
                </td>
            `;

            productTable.appendChild(row);
        });
    } catch (error) {
        console.error('Error fetching products:', error);
        productTable.innerHTML = '<tr><td colspan="8">Error loading products. Please try again.</td></tr>';
    }
}

async function editProduct(productId) {
    try {
        const response = await fetch(`/php/admin.php?action=get_product&id=${productId}`);
        const data = await response.json();

        if (data.status !== 'success' || !data.product) {
            throw new Error(data.message || 'Failed to fetch product');
        }

        const product = data.product;

        // Update form fields
        document.getElementById('formTitle').textContent = 'Edit Product';
        document.getElementById('productAction').value = 'edit';
        document.getElementById('productId').value = product.id;
        document.getElementById('productName').value = product.name;
        document.getElementById('productPrice').value = product.price;
        document.getElementById('productStock').value = product.stock;
        document.getElementById('productCategory').value = product.category;
        document.getElementById('productDescription').value = product.description;
        document.getElementById('productColor').value = product.color || '';

        // Handle existing images
        const imagePreviewContainer = document.getElementById('imagePreviewContainer');
        if (imagePreviewContainer) {
            imagePreviewContainer.innerHTML = '';
            if (product.images && product.images.length > 0) {
                product.images.forEach((imagePath, index) => {
                    const imgWrapper = document.createElement('div');
                    imgWrapper.className = 'existing-image-wrapper';
                    imgWrapper.innerHTML = `
                        <img src="${imagePath}" alt="Product Image ${index + 1}" style="width: 100px; height: 100px; object-fit: cover;">
                        <input type="checkbox" name="existingImagesToRemove[]" value="${imagePath}" title="Remove this image">
                    `;
                    imagePreviewContainer.appendChild(imgWrapper);
                });
            }
        }

        document.getElementById('productImage').value = '';
        document.getElementById('productForm').classList.remove('d-none');
    } catch (error) {
        console.error('Error editing product:', error);
        alert('Failed to load product details. Please try again.');
    }
}

async function deleteProduct(id) {
    const formData = new FormData();
    formData.append('action', 'delete');
    formData.append('id', id);

    try {
        const response = await fetch('/php/admin.php', {
            method: 'POST',
            body: formData
        });
        const data = await response.json();
        
        if (data.status === 'success') {
            alert(data.message);
            renderProducts();
        } else {
            alert(`Error: ${data.message}`);
        }
    } catch (error) {
        console.error('Error during deletion:', error);
        alert('Failed to delete product. Please try again.');
    }
}

async function featureProduct(id) {
    const formData = new FormData();
    formData.append('action', 'feature');
    formData.append('id', id);

    try {
        const response = await fetch('/php/admin.php', {
            method: 'POST',
            body: formData
        });
        const data = await response.json();
        
        if (data.status === 'success') {
            alert(data.message);
            renderProducts();
        } else {
            alert(`Error: ${data.message}`);
        }
    } catch (error) {
        console.error('Error updating feature status:', error);
        alert('Failed to update product feature status. Please try again.');
    }
}

function setupTabNavigation() {
    const tabs = document.querySelectorAll('.tab');
    if (tabs.length === 0) return;

    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            tabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');

            const tabContents = document.querySelectorAll('.tab-content');
            tabContents.forEach(content => content.classList.remove('active'));

            const targetTabContent = document.getElementById(`${this.dataset.tab}Tab`);
            if (targetTabContent) targetTabContent.classList.add('active');
        });
    });
}