this codes manage products (<?php
// public/products/manage_products.php

// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Include authentication and database connection
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';

// Initialize success and error messages
$success = '';
$error = '';

// Function to sanitize input data
function sanitize_input($data) {
    return htmlspecialchars(trim($data));
}

// Handle Add/Edit/Delete actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Add Product
    if (isset($_POST['add_product'])) {
        $name = sanitize_input($_POST['name']);
        $size = sanitize_input($_POST['size']);
        $price = floatval($_POST['price']);
        $category = sanitize_input($_POST['category']);

        // Basic validation
        if (empty($name) || empty($size) || empty($price) || empty($category)) {
            $error = "All fields are required.";
        } else {
            // Prepare and execute the insert statement
            $add_sql = "INSERT INTO products (name, size, price, category) VALUES (?, ?, ?, ?)";
            $stmt = $conn->prepare($add_sql);
            if ($stmt) {
                $stmt->bind_param("ssds", $name, $size, $price, $category);
                if ($stmt->execute()) {
                    $success = "Product added successfully!";
                } else {
                    $error = "Error adding product: " . $stmt->error;
                }
                $stmt->close();
            } else {
                $error = "Prepare statement failed: " . $conn->error;
            }
        }
    }
    // Edit Product
    elseif (isset($_POST['edit_product'])) {
        $id = intval($_POST['id']);
        $name = sanitize_input($_POST['name']);
        $size = sanitize_input($_POST['size']);
        $price = floatval($_POST['price']);
        $category = sanitize_input($_POST['category']);

        // Basic validation
        if (empty($name) || empty($size) || empty($price) || empty($category)) {
            $error = "All fields are required.";
        } else {
            // Prepare and execute the update statement
            $edit_sql = "UPDATE products SET name=?, size=?, price=?, category=? WHERE id=?";
            $stmt = $conn->prepare($edit_sql);
            if ($stmt) {
                $stmt->bind_param("ssdsi", $name, $size, $price, $category, $id);
                if ($stmt->execute()) {
                    $success = "Product updated successfully!";
                } else {
                    $error = "Error updating product: " . $stmt->error;
                }
                $stmt->close();
            } else {
                $error = "Prepare statement failed: " . $conn->error;
            }
        }
    }
    // Delete Product
    elseif (isset($_POST['delete_product'])) {
        $id = intval($_POST['id']);

        // Check if the product is referenced in any orders
        $check_sql = "SELECT COUNT(*) AS count FROM orders WHERE product_id = ?";
        $stmt = $conn->prepare($check_sql);
        if ($stmt) {
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $stmt->bind_result($count);
            $stmt->fetch();
            $stmt->close();

            if ($count > 0) {
                $error = "Cannot delete product because it is associated with existing orders.";
            } else {
                // Proceed to delete the product
                $delete_sql = "DELETE FROM products WHERE id = ?";
                $stmt = $conn->prepare($delete_sql);
                if ($stmt) {
                    $stmt->bind_param("i", $id);
                    if ($stmt->execute()) {
                        $success = "Product deleted successfully!";
                    } else {
                        $error = "Error deleting product: " . $stmt->error;
                    }
                    $stmt->close();
                } else {
                    $error = "Prepare statement failed: " . $conn->error;
                }
            }
        } else {
            $error = "Prepare statement failed: " . $conn->error;
        }
    }
}

// Fetch all products
$products_sql = "SELECT * FROM products ORDER BY name ASC";
$products_result = $conn->query($products_sql);

// Now include the header after handling actions
require_once __DIR__ . '/../../includes/header.php';
?>
<!-- Main Content Container -->
<div class="container mx-auto mt-24 px-4">
    <!-- Display Success or Error Messages -->
    <?php if ($success): ?>
        <div class="bg-green-500 text-white px-4 py-3 rounded mb-4">
            <?= htmlspecialchars($success) ?>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="bg-red-500 text-white px-4 py-3 rounded mb-4">
            <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <!-- Add Product Form -->
    <div class="bg-white shadow rounded-lg p-6 mb-8">
        <h3 class="text-2xl font-semibold mb-4 text-gray-800">Add New Product</h3>
        <form method="POST" action="">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Product Name -->
                <div>
                    <label for="name" class="block text-gray-700">Name <span class="text-red-500">*</span></label>
                    <input type="text" id="name" name="name" class="mt-1 p-2 w-full border rounded" 
                           value="<?= isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '' ?>" 
                           required>
                </div>
                <!-- Product Size -->
                <div>
                    <label for="size" class="block text-gray-700">Size <span class="text-red-500">*</span></label>
                    <input type="text" id="size" name="size" class="mt-1 p-2 w-full border rounded" 
                           value="<?= isset($_POST['size']) ? htmlspecialchars($_POST['size']) : '' ?>" 
                           required>
                </div>
                <!-- Product Price -->
                <div>
                    <label for="price" class="block text-gray-700">Price (KD) <span class="text-red-500">*</span></label>
                    <input type="number" id="price" name="price" class="mt-1 p-2 w-full border rounded" 
                           step="0.01" 
                           value="<?= isset($_POST['price']) ? htmlspecialchars($_POST['price']) : '' ?>" 
                           required>
                </div>
                <!-- Product Category -->
                <div>
                    <label for="category" class="block text-gray-700">Category <span class="text-red-500">*</span></label>
                    <input type="text" id="category" name="category" class="mt-1 p-2 w-full border rounded" 
                           value="<?= isset($_POST['category']) ? htmlspecialchars($_POST['category']) : '' ?>" 
                           required>
                </div>
            </div>
            <!-- Submit Button -->
            <div class="mt-6 text-center">
                <button type="submit" name="add_product" class="bg-yellow-500 text-white px-6 py-2 rounded hover:bg-yellow-400 transition">
                    Add Product
                </button>
            </div>
        </form>
    </div>

    <!-- Products List Table -->
    <div class="bg-white shadow rounded-lg p-6">
        <h4 class="text-xl font-semibold mb-4 text-gray-800">All Products</h4>
        <div class="overflow-x-auto">
            <table class="min-w-full bg-white">
                <thead>
                    <tr>
                        <th class="px-6 py-3 border-b border-gray-300 text-left text-blue-500">ID</th>
                        <th class="px-6 py-3 border-b border-gray-300 text-left text-blue-500">Name</th>
                        <th class="px-6 py-3 border-b border-gray-300 text-left text-blue-500">Size</th>
                        <th class="px-6 py-3 border-b border-gray-300 text-left text-blue-500">Price (KD)</th>
                        <th class="px-6 py-3 border-b border-gray-300 text-left text-blue-500">Category</th>
                        <th class="px-6 py-3 border-b border-gray-300 text-left text-blue-500">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($products_result && $products_result->num_rows > 0): ?>
                        <?php while($product = $products_result->fetch_assoc()): ?>
                            <tr class="hover:bg-gray-100">
                                <td class="px-6 py-4 whitespace-no-wrap border-b border-gray-500"><?= htmlspecialchars($product['id']) ?></td>
                                <td class="px-6 py-4 whitespace-no-wrap border-b border-gray-500"><?= htmlspecialchars($product['name']) ?></td>
                                <td class="px-6 py-4 whitespace-no-wrap border-b border-gray-500"><?= htmlspecialchars($product['size']) ?></td>
                                <td class="px-6 py-4 whitespace-no-wrap border-b border-gray-500"><?= number_format($product['price'], 2) ?></td>
                                <td class="px-6 py-4 whitespace-no-wrap border-b border-gray-500"><?= htmlspecialchars($product['category']) ?></td>
                                <td class="px-6 py-4 whitespace-no-wrap border-b border-gray-500">
                                    <!-- Edit Button triggers modal -->
                                    <button type="button" class="text-blue-500 hover:text-blue-700 mr-2" data-bs-toggle="modal" data-bs-target="#editModal<?= $product['id'] ?>" title="Edit Product">
                                        <i class="bi bi-pencil-fill text-lg"></i>
                                    </button>
                                    <!-- Delete Form -->
                                    <form method="POST" action="" class="inline" onsubmit="return confirm('Are you sure you want to delete this product?');">
                                        <input type="hidden" name="id" value="<?= $product['id'] ?>">
                                        <button type="submit" name="delete_product" class="text-red-500 hover:text-red-700" title="Delete Product">
                                            <i class="bi bi-trash-fill text-lg"></i>
                                        </button>
                                    </form>

                                    <!-- Edit Modal -->
                                    <div class="modal fade" id="editModal<?= $product['id'] ?>" tabindex="-1" aria-labelledby="editModalLabel<?= $product['id'] ?>" aria-hidden="true">
                                      <div class="modal-dialog">
                                        <div class="modal-content">
                                          <form method="POST" action="">
                                              <div class="modal-header bg-yellow-500 text-white">
                                                <h5 class="modal-title" id="editModalLabel<?= $product['id'] ?>">Edit Product</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                              </div>
                                              <div class="modal-body">
                                                  <input type="hidden" name="id" value="<?= $product['id'] ?>">
                                                  <!-- Product Name -->
                                                  <div class="mb-3">
                                                      <label for="edit_name_<?= $product['id'] ?>" class="block text-gray-700">Name <span class="text-red-500">*</span></label>
                                                      <input type="text" id="edit_name_<?= $product['id'] ?>" name="name" class="mt-1 p-2 w-full border rounded" 
                                                             value="<?= htmlspecialchars($product['name']) ?>" required>
                                                  </div>
                                                  <!-- Product Size -->
                                                  <div class="mb-3">
                                                      <label for="edit_size_<?= $product['id'] ?>" class="block text-gray-700">Size <span class="text-red-500">*</span></label>
                                                      <input type="text" id="edit_size_<?= $product['id'] ?>" name="size" class="mt-1 p-2 w-full border rounded" 
                                                             value="<?= htmlspecialchars($product['size']) ?>" required>
                                                  </div>
                                                  <!-- Product Price -->
                                                  <div class="mb-3">
                                                      <label for="edit_price_<?= $product['id'] ?>" class="block text-gray-700">Price (KD) <span class="text-red-500">*</span></label>
                                                      <input type="number" id="edit_price_<?= $product['id'] ?>" name="price" class="mt-1 p-2 w-full border rounded" 
                                                             step="0.01" 
                                                             value="<?= htmlspecialchars($product['price']) ?>" 
                                                             required>
                                                  </div>
                                                  <!-- Product Category -->
                                                  <div class="mb-3">
                                                      <label for="edit_category_<?= $product['id'] ?>" class="block text-gray-700">Category <span class="text-red-500">*</span></label>
                                                      <input type="text" id="edit_category_<?= $product['id'] ?>" name="category" class="mt-1 p-2 w-full border rounded" 
                                                             value="<?= htmlspecialchars($product['category']) ?>" 
                                                             required>
                                                  </div>
                                              </div>
                                              <div class="modal-footer">
                                                <button type="button" class="bg-gray-300 text-gray-700 px-4 py-2 rounded hover:bg-gray-400" data-bs-dismiss="modal">Close</button>
                                                <button type="submit" name="edit_product" class="bg-yellow-500 text-white px-4 py-2 rounded hover:bg-yellow-400">Save Changes</button>
                                              </div>
                                          </form>
                                        </div>
                                      </div>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" class="text-center text-gray-500">No products found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
            <div class="mt-4 text-right">
                <a href="/public/orders/view_orders.php" class="text-blue-500 hover:underline">View All Orders</a>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <div class="footer mt-10">
        &copy; 2024 Kaak Alia Bakery. All rights reserved.
    </div>

    <!-- Initialize Bootstrap Tooltips (Optional) -->
    <script>
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'))
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl)
        })
    </script>
</body>
</html>)when i press delete button it gets erorr please fix it (Fatal error: Uncaught mysqli_sql_exception: Cannot delete or update a parent row: a foreign key constraint fails (`u406552082_kaakalia`.`orders`, CONSTRAINT `orders_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`)) in /home/u406552082/domains/longevacare.com/public_html/kaakalia/public/products/manage_products.php:101 Stack trace: #0 /home/u406552082/domains/longevacare.com/public_html/kaakalia/public/products/manage_products.php(101): mysqli_stmt->execute() #1 {main} thrown in /home/u406552082/domains/longevacare.com/public_html/kaakalia/public/products/manage_products.php on line 101) and this info database(-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Nov 08, 2024 at 03:05 PM
-- Server version: 10.11.9-MariaDB
-- PHP Version: 7.2.34

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `u406552082_kaakalia`
--

-- --------------------------------------------------------

--
-- Table structure for table `customers`
--

CREATE TABLE `customers` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `contact` varchar(50) DEFAULT NULL,
  `delivery_address` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `orders`
--

CREATE TABLE `orders` (
  `id` int(11) NOT NULL,
  `customer_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `status` enum('Pending','In Progress','Completed','Delivered') DEFAULT 'Pending',
  `order_date` datetime DEFAULT current_timestamp(),
  `delivery_datetime` datetime DEFAULT NULL,
  `delivery_date` date DEFAULT NULL,
  `quantity` int(11) NOT NULL DEFAULT 1,
  `packaging_preferences` varchar(255) DEFAULT NULL,
  `discount_amount` decimal(10,2) DEFAULT 0.00,
  `discount_reason` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `order_items`
--

CREATE TABLE `order_items` (
  `id` int(11) NOT NULL,
  `order_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  `packaging_preferences` varchar(255) DEFAULT NULL,
  `discount_amount` decimal(10,2) DEFAULT 0.00,
  `discount_reason` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `size` varchar(50) DEFAULT NULL,
  `price` decimal(10,2) NOT NULL,
  `category` varchar(50) DEFAULT NULL,
  `thumbnail` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `role` enum('admin','staff') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
  ADD PRIMARY KEY (`id`),
  ADD KEY `customer_id` (`customer_id`);

--
-- Indexes for table `order_items`
--
ALTER TABLE `order_items`
  ADD PRIMARY KEY (`id`),
  ADD KEY `order_id` (`order_id`),
  ADD KEY `product_id` (`product_id`);

--
-- Indexes for table `products`
--
ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `username` (`username`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `customers`
--
ALTER TABLE `customers`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `order_items`
--
ALTER TABLE `order_items`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `orders`
--
ALTER TABLE `orders`
  ADD CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`),
  ADD CONSTRAINT `orders_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`);

--
-- Constraints for table `order_items`
--
ALTER TABLE `order_items`
  ADD CONSTRAINT `order_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `order_items_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;)