please help me optimize my code:
<?php
// Database connection settings
$servername = "localhost";
$username = "tester";
$password = "Baby@0987";
$dbname = "your_database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//register /static/images folder


// Handle form actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];

    switch ($action) {
        case 'add':
            // Enable error reporting for debugging (remove in production)
            ini_set('display_errors', 1);
            ini_set('display_startup_errors', 1);
            error_reporting(E_ALL);
        
            // Ensure all required POST fields are set
            $requiredFields = ['name', 'price', 'stock', 'category', 'description'];
            foreach ($requiredFields as $field) {
                if (!isset($_POST[$field])) {
                    echo json_encode(["status" => "error", "message" => "Missing field: $field"]);
                    exit;
                }
            }
        
            // Sanitize input data
            $name = $conn->real_escape_string($_POST['name']);
            $price = floatval($_POST['price']);
            $stock = intval($_POST['stock']);
            $category = $conn->real_escape_string($_POST['category']);
            $description = $conn->real_escape_string($_POST['description']);
        
            // Handle image uploads
            $newImages = [];
            if (isset($_FILES['images'])) {
                $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/static/images/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
        
                for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
                    // Check for upload errors
                    if ($_FILES['images']['error'][$i] !== UPLOAD_ERR_OK) {
                        echo json_encode(["status" => "error", "message" => "Error uploading image: " . $_FILES['images']['name'][$i]]);
                        exit;
                    }
        
                    $tmpName = $_FILES['images']['tmp_name'][$i];
                    $originalName = basename($_FILES['images']['name'][$i]);
                    $originalName = preg_replace("/[^A-Z0-9._-]/i", "_", $originalName); // Sanitize filename
        
                    // Prevent overwriting existing files
                    $destination = $uploadDir . $originalName;
                    $fileExt = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
                    $allowed = ['jpg', 'jpeg', 'png', 'gif'];
        
                    if (!in_array($fileExt, $allowed)) {
                        echo json_encode(["status" => "error", "message" => "Invalid file type for image: " . $originalName]);
                        exit;
                    }
        
                    // If file exists, append a number to make it unique
                    $counter = 1;
                    while (file_exists($destination)) {
                        $filename = pathinfo($originalName, PATHINFO_FILENAME);
                        $destination = $uploadDir . $filename . '_' . $counter . '.' . $fileExt;
                        $counter++;
                    }
        
                    if (move_uploaded_file($tmpName, $destination)) {
                        $relativePath = '/static/images/' . basename($destination);
                        $newImages[] = $relativePath;
                    } else {
                        echo json_encode(["status" => "error", "message" => "Failed to move uploaded image: " . $originalName]);
                        exit;
                    }
                }
            }
        
            // Encode images as JSON
            $imageJson = json_encode($newImages);
        
            // Prepare the SQL statement to prevent SQL injection
            $stmt = $conn->prepare("INSERT INTO products (name, price, stock, category, images, description) VALUES (?, ?, ?, ?, ?, ?)");
            if ($stmt === false) {
                echo json_encode(["status" => "error", "message" => "Prepare failed: " . $conn->error]);
                exit;
            }
        
            $stmt->bind_param("sdisss", $name, $price, $stock, $category, $imageJson, $description);
        
            if ($stmt->execute()) {
                echo json_encode(["status" => "success", "message" => "Product added successfully"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Error: " . $stmt->error]);
            }
        
            $stmt->close();
            break;

            case 'edit':
                // Enable error reporting for debugging (remove in production)
                ini_set('display_errors', 1);
                ini_set('display_startup_errors', 1);
                error_reporting(E_ALL);
            
                // Ensure all required POST fields are set
                $requiredFields = ['id', 'name', 'price', 'stock', 'category', 'description', 'imagesToRemove'];
                foreach ($requiredFields as $field) {
                    if (!isset($_POST[$field])) {
                        echo json_encode(["status" => "error", "message" => "Missing field: $field"]);
                        exit;
                    }
                }
            
                // Sanitize input data
                $id = intval($_POST['id']);
                $name = $conn->real_escape_string($_POST['name']);
                $price = floatval($_POST['price']);
                $stock = intval($_POST['stock']);
                $category = $conn->real_escape_string($_POST['category']);
                $description = $conn->real_escape_string($_POST['description']);
            
                // Decode images to remove from JSON
                $imagesToRemove = [];
                if (isset($_POST['imagesToRemove'])) {
                    $imagesToRemove = json_decode($_POST['imagesToRemove'], true);
                    if (!is_array($imagesToRemove)) {
                        $imagesToRemove = [];
                    }
                }
            
                // Fetch existing images from the database
                $existingImages = [];
                $result = $conn->query("SELECT images FROM products WHERE id = $id");
                if ($result && $result->num_rows > 0) {
                    $row = $result->fetch_assoc();
                    $existingImages = json_decode($row['images'], true);
                    if (!is_array($existingImages)) {
                        $existingImages = [];
                    }
                } else {
                    echo json_encode(["status" => "error", "message" => "Product not found"]);
                    exit;
                }
            
                // Remove images marked for deletion
                $updatedImages = array_diff($existingImages, $imagesToRemove);
            
                // Handle new image uploads
                $newImages = [];
                if (isset($_FILES['images'])) {
                    $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/static/images/';
                    if (!is_dir($uploadDir)) {
                        mkdir($uploadDir, 0755, true);
                    }
            
                    for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
                        // Check for upload errors
                        if ($_FILES['images']['error'][$i] !== UPLOAD_ERR_OK) {
                            echo json_encode(["status" => "error", "message" => "Error uploading image: " . $_FILES['images']['name'][$i]]);
                            exit;
                        }
            
                        $tmpName = $_FILES['images']['tmp_name'][$i];
                        $originalName = basename($_FILES['images']['name'][$i]);
                        $originalName = preg_replace("/[^A-Z0-9._-]/i", "_", $originalName); // Sanitize filename
            
                        // Prevent overwriting existing files
                        $destination = $uploadDir . $originalName;
                        $fileExt = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
                        $allowed = ['jpg', 'jpeg', 'png', 'gif'];
            
                        if (!in_array($fileExt, $allowed)) {
                            echo json_encode(["status" => "error", "message" => "Invalid file type for image: " . $originalName]);
                            exit;
                        }
            
                        // If file exists, append a number to make it unique
                        $counter = 1;
                        while (file_exists($destination)) {
                            $filename = pathinfo($originalName, PATHINFO_FILENAME);
                            $destination = $uploadDir . $filename . '_' . $counter . '.' . $fileExt;
                            $counter++;
                        }
            
                        if (move_uploaded_file($tmpName, $destination)) {
                            $relativePath = '/static/images/' . basename($destination);
                            $newImages[] = $relativePath;
                        } else {
                            echo json_encode(["status" => "error", "message" => "Failed to move uploaded image: " . $originalName]);
                            exit;
                        }
                    }
                }
            
                // Combine existing images to keep with new images
                $finalImages = array_merge($updatedImages, $newImages);
                $imageJson = json_encode(array_values($finalImages)); // Reindex array
            
                // Prepare the SQL statement to prevent SQL injection
                $stmt = $conn->prepare("UPDATE products SET name=?, price=?, stock=?, category=?, images=?, description=? WHERE id=?");
                if ($stmt === false) {
                    echo json_encode(["status" => "error", "message" => "Prepare failed: " . $conn->error]);
                    exit;
                }
            
                $stmt->bind_param("sdisssi", $name, $price, $stock, $category, $imageJson, $description, $id);
            
                if ($stmt->execute()) {
                    // Optionally, handle deletion of image files from the server if necessary
                    foreach ($imagesToRemove as $imagePath) {
                        $fullPath = $_SERVER['DOCUMENT_ROOT'] . $imagePath;
                        if (file_exists($fullPath)) {
                            unlink($fullPath);
                        }
                    }
            
                    echo json_encode(["status" => "success", "message" => "Product updated successfully"]);
                } else {
                    echo json_encode(["status" => "error", "message" => "Error: " . $stmt->error]);
                }
            
                $stmt->close();
                break;
        case 'delete':
            // Delete product
            $id = intval($_POST['id']);
            $sql = "DELETE FROM products WHERE id=$id";

            if ($conn->query($sql) === TRUE) {
                echo json_encode(["status" => "success", "message" => "Product deleted successfully"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Error: " . $conn->error]);
            }
            break;

        case 'feature':
            // Feature product
            $id = intval($_POST['id']);
            $sql = "UPDATE products SET featured=1 WHERE id=$id";

            if ($conn->query($sql) === TRUE) {
                echo json_encode(["status" => "success", "message" => "Product featured successfully"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Error: " . $conn->error]);
            }
            break;

        default:
            echo json_encode(["status" => "error", "message" => "Unknown action: $action"]);
    }

    // End execution after handling POST request
    $conn->close();
    exit();
}

// Handle GET request to fetch products
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
   
    $sql = "SELECT * FROM products";
    $result = $conn->query($sql);
    $products = array();
    
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $row['price'] = floatval($row['price']); // Convert price to float
            $row['images'] = json_decode($row['images'], true); // Decode JSON images
            $products[] = $row;
        }
        
        // // Debugging printing block
        // echo "Products fetched from the database:\n";
        // print_r($products);
        // // echo "\n";
    }
    echo json_encode($products);
}

// Close the connection
$conn->close();
?>