based on this inof database (-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Nov 10, 2024 at 09:21 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 `ads`
--

CREATE TABLE `ads` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `ad_type` enum('Post','Story') NOT NULL,
  `related_id` int(11) NOT NULL,
  `budget` decimal(10,2) NOT NULL,
  `total_spent` decimal(10,2) DEFAULT 0.00,
  `start_date` date NOT NULL,
  `end_date` date NOT NULL,
  `status` enum('Active','Paused','Completed') DEFAULT 'Active',
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

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

--
-- Table structure for table `ad_spend_logs`
--

CREATE TABLE `ad_spend_logs` (
  `id` int(11) NOT NULL,
  `ad_id` int(11) NOT NULL,
  `amount` decimal(10,2) NOT NULL,
  `spend_date` datetime DEFAULT current_timestamp(),
  `description` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

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

--
-- 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;

--
-- Dumping data for table `customers`
--

INSERT INTO `customers` (`id`, `name`, `contact`, `delivery_address`) VALUES
(1, 'Order_3121', '012345689', 'Qena'),
(2, 'order_3212', '51648963', 'Luxor'),
(3, 'Order_323', '01119235049', 'Qena, Egypt'),
(4, 'Order_3231', '0155648963', 'Luxor'),
(5, 'Order_3548464852', '0110215489', 'Qena');

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

--
-- Table structure for table `drivers`
--

CREATE TABLE `drivers` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `number` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `drivers`
--

INSERT INTO `drivers` (`id`, `name`, `number`) VALUES
(1, 'Fox توصيل', '+965 9944 6116'),
(2, 'Perfect M توصيل 3kd', '+965 555 72147'),
(3, 'توصيل ٥', '+965 505 02769'),
(4, 'Shipping Company توصيل Delivery', '+965 9940 7010'),
(5, 'توصيلكم توصيل Delivery', '+965 517 66244'),
(6, 'توصيل الكويت ٢', '+965 557 25712'),
(7, 'توصيل الكويت 2.5kd', '+965 6049 4960'),
(8, 'كلاسك توصيل', '+965 6969 1459'),
(9, 'سايق On Call5 Delivery Freelance', '+965 6698 8976'),
(10, 'سايق On Call 3 Delivery Freelance', '+965 555 86442'),
(11, 'سايق On Call 2 Delivery Freelance', '+965 555 12101'),
(12, 'Delivery توصيل', '+965 9851 8182'),
(13, 'Kumar Driver', '+965 6673 8688'),
(14, 'Pawan Driver', '+965 9733 1565'),
(15, 'توصيل - صلاح', '+965 6576 2337');

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

--
-- Table structure for table `notifications`
--

CREATE TABLE `notifications` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `type` enum('order','post','plan','note') NOT NULL,
  `message` varchar(255) NOT NULL,
  `link` varchar(255) NOT NULL,
  `created_at` datetime DEFAULT current_timestamp()
) 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,
  `status` enum('Pending','In Progress','Completed','Delivered') DEFAULT 'Pending',
  `priority` enum('Normal','Important','Quick') DEFAULT 'Normal',
  `order_date` datetime DEFAULT current_timestamp(),
  `delivery_datetime` datetime DEFAULT NULL,
  `delivery_date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `orders`
--

INSERT INTO `orders` (`id`, `customer_id`, `status`, `priority`, `order_date`, `delivery_datetime`, `delivery_date`) VALUES
(4, 4, 'Completed', 'Important', '2024-11-09 14:48:25', '2024-11-16 08:50:00', NULL),
(5, 5, 'Pending', 'Normal', '2024-11-09 18:28:01', '2024-11-10 09:00:00', NULL);

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

--
-- 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 DEFAULT 1,
  `packaging_preferences` varchar(255) DEFAULT NULL,
  `discount_percentage` decimal(5,2) DEFAULT 0.00,
  `discount_reason` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `order_items`
--

INSERT INTO `order_items` (`id`, `order_id`, `product_id`, `quantity`, `packaging_preferences`, `discount_percentage`, `discount_reason`) VALUES
(5, 4, 10, 1, '0', 0.00, NULL),
(6, 5, 2, 1, '0', 20.00, 'خصم مشرف');

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

--
-- 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;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `name`, `size`, `price`, `category`, `thumbnail`) VALUES
(1, 'Shabora', 'Half Kilo', 6.00, 'Cakes', NULL),
(2, 'Shabora', 'One Kilo', 8.00, 'Cakes', NULL),
(3, 'Shabora', 'Small Basket', 8.00, 'Cakes', NULL),
(4, 'Shabora', 'Large Basket', 10.00, 'Cakes', NULL),
(5, 'Shabora', 'Presentation Plate (Ivory)', 14.00, 'Cakes', NULL),
(6, 'Mahalbiya Crunch', '12 Pieces', 12.00, 'Desserts', NULL),
(7, 'Monkey Bread', 'Large', 12.00, 'Breads', NULL),
(8, 'Monkey Bread Mini', '12 Pieces', 6.00, 'Breads', NULL),
(9, 'Monkey Bread Mini', '9 Pieces', 9.00, 'Breads', NULL),
(10, 'Monkey Bread Mini', '12 Pieces', 12.00, 'Breads', NULL),
(11, 'Monkey Bread', 'Presentation Plate', 16.00, 'Breads', NULL);

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

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

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

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `username`, `email`, `password`, `role`, `profile_image`) VALUES
(1, 'kaakalia', 'user@example.com', '$2y$10$tEdSPRwL8WTXljuAxNh.m.af/8sHd/ouDB21Bgs1bC7GkbRq/h0D6', 'admin', 'uploads/profile_images/profile_1_1731273254.png'),
(2, 'mahmoudtawfik', NULL, '$2y$10$0yxg1R.kfbVV7GL4G9/Q3u5PK.cvv8p29R3ggkfUMC2.aRiAXb2cO', 'admin', NULL),
(3, 'haya', NULL, '$2y$10$H8cgWomjii3I8rgl7VScRuc1y3n0aMxtLxV/KjUerU9a8YrYpydCS', 'admin', NULL);

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

--
-- Table structure for table `workspace_notes`
--

CREATE TABLE `workspace_notes` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `content` text NOT NULL,
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

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

--
-- Table structure for table `workspace_plans`
--

CREATE TABLE `workspace_plans` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  `due_date` datetime DEFAULT NULL,
  `status` enum('Not Started','In Progress','Completed') DEFAULT 'Not Started',
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `workspace_plans`
--

INSERT INTO `workspace_plans` (`id`, `user_id`, `title`, `description`, `due_date`, `status`, `created_at`, `updated_at`) VALUES
(5, 2, 'صواني كعك عالية', 'create new post about it and make it as ad', '2024-11-11 03:41:00', 'Completed', '2024-11-10 10:41:46', '2024-11-10 10:46:33');

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

--
-- Table structure for table `workspace_posts`
--

CREATE TABLE `workspace_posts` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `platform` enum('Instagram','Facebook','Twitter','Other') NOT NULL,
  `content` text NOT NULL,
  `media_url` varchar(255) DEFAULT NULL,
  `scheduled_datetime` datetime DEFAULT NULL,
  `status` enum('Scheduled','Posted','Failed') DEFAULT 'Scheduled',
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `type` enum('Post','Story') DEFAULT 'Post'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `workspace_posts`
--

INSERT INTO `workspace_posts` (`id`, `user_id`, `platform`, `content`, `media_url`, `scheduled_datetime`, `status`, `created_at`, `updated_at`, `type`) VALUES
(2, 1, 'Instagram', 'Hello', NULL, '2024-11-11 01:19:00', 'Scheduled', '2024-11-10 11:16:10', '2024-11-10 11:16:10', 'Post');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `ads`
--
ALTER TABLE `ads`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `related_id` (`related_id`);

--
-- Indexes for table `ad_spend_logs`
--
ALTER TABLE `ad_spend_logs`
  ADD PRIMARY KEY (`id`),
  ADD KEY `ad_id` (`ad_id`);

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

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

--
-- Indexes for table `notifications`
--
ALTER TABLE `notifications`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `created_at` (`created_at`);

--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
  ADD PRIMARY KEY (`id`),
  ADD KEY `customer_id` (`customer_id`),
  ADD KEY `idx_orders_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`),
  ADD KEY `idx_order_items_order_id` (`order_id`),
  ADD KEY `idx_order_items_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`);

--
-- Indexes for table `workspace_notes`
--
ALTER TABLE `workspace_notes`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`);

--
-- Indexes for table `workspace_plans`
--
ALTER TABLE `workspace_plans`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`);

--
-- Indexes for table `workspace_posts`
--
ALTER TABLE `workspace_posts`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `ads`
--
ALTER TABLE `ads`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `ad_spend_logs`
--
ALTER TABLE `ad_spend_logs`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

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

--
-- AUTO_INCREMENT for table `drivers`
--
ALTER TABLE `drivers`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;

--
-- AUTO_INCREMENT for table `notifications`
--
ALTER TABLE `notifications`
  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=6;

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

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

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

--
-- AUTO_INCREMENT for table `workspace_notes`
--
ALTER TABLE `workspace_notes`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `workspace_plans`
--
ALTER TABLE `workspace_plans`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

--
-- AUTO_INCREMENT for table `workspace_posts`
--
ALTER TABLE `workspace_posts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `ads`
--
ALTER TABLE `ads`
  ADD CONSTRAINT `fk_ads_related_id` FOREIGN KEY (`related_id`) REFERENCES `workspace_posts` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `fk_ads_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `ad_spend_logs`
--
ALTER TABLE `ad_spend_logs`
  ADD CONSTRAINT `fk_ad_spend_logs_ad_id` FOREIGN KEY (`ad_id`) REFERENCES `ads` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `notifications`
--
ALTER TABLE `notifications`
  ADD CONSTRAINT `notifications_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `orders`
--
ALTER TABLE `orders`
  ADD CONSTRAINT `fk_orders_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `order_items`
--
ALTER TABLE `order_items`
  ADD CONSTRAINT `fk_order_items_order_id` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `fk_order_items_product_id` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  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;

--
-- Constraints for table `workspace_notes`
--
ALTER TABLE `workspace_notes`
  ADD CONSTRAINT `fk_workspace_notes_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `workspace_plans`
--
ALTER TABLE `workspace_plans`
  ADD CONSTRAINT `fk_workspace_plans_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `workspace_posts`
--
ALTER TABLE `workspace_posts`
  ADD CONSTRAINT `fk_workspace_posts_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`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 */;) i wnat to fix this (<?php
// includes/user_settings.php

// Enable error reporting for debugging (Remove or comment out in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

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

// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
    header("Location: /public/login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$errors = [];
$success = "";

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize inputs
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Validate inputs
    if (empty($username)) {
        $errors[] = "Username cannot be empty.";
    }

    if (empty($email)) {
        $errors[] = "Email cannot be empty.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format.";
    }

    // Password update logic
    $update_password = false;
    if (!empty($password) || !empty($confirm_password)) {
        if ($password !== $confirm_password) {
            $errors[] = "Passwords do not match.";
        } elseif (strlen($password) < 6) {
            $errors[] = "Password must be at least 6 characters long.";
        } else {
            $update_password = true;
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        }
    }

    // Handle profile image upload
    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] !== UPLOAD_ERR_NO_FILE) {
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
        $max_size = 2 * 1024 * 1024; // 2MB

        if ($_FILES['profile_image']['error'] !== UPLOAD_ERR_OK) {
            $errors[] = "Error uploading file.";
        } elseif (!in_array($_FILES['profile_image']['type'], $allowed_types)) {
            $errors[] = "Only JPG, PNG, and GIF files are allowed.";
        } elseif ($_FILES['profile_image']['size'] > $max_size) {
            $errors[] = "File size must be less than 2MB.";
        } else {
            // Generate a unique file name based on username
            $ext = strtolower(pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION));
            // Validate extension
            if (!in_array($ext, $allowed_extensions)) {
                $errors[] = "Invalid file extension.";
            } else {
                // Sanitize username for file naming
                $sanitized_username = preg_replace("/[^a-zA-Z0-9_-]/", "_", $username);
                $new_filename = 'profile_' . $sanitized_username . '.' . $ext;
                $upload_dir = __DIR__ . '/images_profile/';

                // Create upload directory if it doesn't exist
                if (!is_dir($upload_dir)) {
                    if (!mkdir($upload_dir, 0755, true)) {
                        $errors[] = "Failed to create upload directory.";
                    }
                }

                $destination = $upload_dir . $new_filename;

                if (!move_uploaded_file($_FILES['profile_image']['tmp_name'], $destination)) {
                    $errors[] = "Failed to move uploaded file.";
                } else {
                    // Optionally, delete the old profile image if it's different
                    $stmt_old = $conn->prepare("SELECT profile_image FROM users WHERE id = ?");
                    if ($stmt_old) {
                        $stmt_old->bind_param("i", $user_id);
                        $stmt_old->execute();
                        $result_old = $stmt_old->get_result();
                        if ($result_old && $result_old->num_rows === 1) {
                            $user = $result_old->fetch_assoc();
                            if (!empty($user['profile_image'])) {
                                $old_image_path = __DIR__ . '/' . $user['profile_image'];
                                if (file_exists($old_image_path) && $user['profile_image'] !== 'images_profile/' . $new_filename) {
                                    unlink($old_image_path);
                                }
                            }
                        }
                        $stmt_old->close();
                    }

                    // Set the new profile image path relative to includes/
                    $profile_image_path = 'images_profile/' . $new_filename;
                }
            }
        }
    }

    // If no errors, update the database
    if (empty($errors)) {
        // Start building the update query
        $update_fields = "username = ?, email = ?";
        $types = "ss";
        $params = [$username, $email];

        if ($update_password) {
            $update_fields .= ", password = ?";
            $types .= "s";
            $params[] = $hashed_password;
        }

        if (isset($profile_image_path)) {
            $update_fields .= ", profile_image = ?";
            $types .= "s";
            $params[] = $profile_image_path;
        }

        $params[] = $user_id;
        $types .= "i";

        $sql = "UPDATE users SET $update_fields WHERE id = ?";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param($types, ...$params);
            if ($stmt->execute()) {
                // Successful update; implement Post/Redirect/Get
                $_SESSION['success_message'] = "Settings updated successfully.";
                header("Location: /includes/user_settings.php");
                exit();
            } else {
                $errors[] = "Failed to update settings. Please try again.";
            }
            $stmt->close();
        } else {
            $errors[] = "Database error: Unable to prepare statement.";
        }
    } else {
        // Store errors in session to persist after redirect
        $_SESSION['error_messages'] = $errors;
        // Preserve input data
        $_SESSION['form_data'] = [
            'username' => htmlspecialchars($username, ENT_QUOTES, 'UTF-8'),
            'email' => htmlspecialchars($email, ENT_QUOTES, 'UTF-8'),
        ];
        header("Location: /includes/user_settings.php");
        exit();
    }
}

// Fetch current user data
$stmt = $conn->prepare("SELECT username, email, profile_image FROM users WHERE id = ?");
if ($stmt) {
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $current_user = $result->fetch_assoc();
    $stmt->close();
} else {
    // Handle error if statement preparation fails
    $errors[] = "Database error: Unable to fetch user data.";
    $current_user = ['username' => '', 'email' => '', 'profile_image' => ''];
}

// Retrieve messages and form data from session
if (isset($_SESSION['error_messages'])) {
    $errors = $_SESSION['error_messages'];
    unset($_SESSION['error_messages']);
}

if (isset($_SESSION['success_message'])) {
    $success = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

$form_data = $_SESSION['form_data'] ?? [];
unset($_SESSION['form_data']);

// Use form data if available (in case of errors)
$username = htmlspecialchars($form_data['username'] ?? $current_user['username'], ENT_QUOTES, 'UTF-8');
$email = htmlspecialchars($form_data['email'] ?? $current_user['email'], ENT_QUOTES, 'UTF-8');
$profile_image = !empty($current_user['profile_image']) ? '/' . htmlspecialchars($current_user['profile_image'], ENT_QUOTES, 'UTF-8') : '/assets/images/user-placeholder.png';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Settings</title>
    <!-- Include Tailwind CSS -->
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body>
    <!-- Include the header -->
    <?php include __DIR__ . '/header.php'; ?>

    <div class="container mx-auto mt-24 px-4">
        <div class="max-w-xl mx-auto bg-white shadow-md rounded-lg p-6">
            <h2 class="text-2xl font-semibold mb-6">User Settings</h2>

            <?php if (!empty($errors)): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                    <ul class="list-disc pl-5">
                        <?php foreach ($errors as $error): ?>
                            <li><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
                    <?= htmlspecialchars($success, ENT_QUOTES, 'UTF-8') ?>
                </div>
            <?php endif; ?>

            <form action="" method="POST" enctype="multipart/form-data" class="space-y-6">
                <!-- Profile Image -->
                <div class="flex items-center space-x-4">
                    <img src="<?= htmlspecialchars($profile_image, ENT_QUOTES, 'UTF-8') ?>" alt="Profile Image" class="h-24 w-24 rounded-full object-cover">
                    <label class="cursor-pointer bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition-colors">
                        Change Profile Image
                        <input type="file" name="profile_image" accept="image/*" class="hidden">
                    </label>
                </div>

                <!-- Username -->
                <div>
                    <label for="username" class="block text-gray-700 font-medium mb-2">Username</label>
                    <input type="text" id="username" name="username" value="<?= $username ?>" required
                           class="w-full border border-gray-300 px-4 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>

                <!-- Email -->
                <div>
                    <label for="email" class="block text-gray-700 font-medium mb-2">Email</label>
                    <input type="email" id="email" name="email" value="<?= $email ?>" required
                           class="w-full border border-gray-300 px-4 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>

                <!-- Password -->
                <div>
                    <label for="password" class="block text-gray-700 font-medium mb-2">New Password</label>
                    <input type="password" id="password" name="password"
                           class="w-full border border-gray-300 px-4 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="Leave blank to keep current password">
                </div>

                <!-- Confirm Password -->
                <div>
                    <label for="confirm_password" class="block text-gray-700 font-medium mb-2">Confirm New Password</label>
                    <input type="password" id="confirm_password" name="confirm_password"
                           class="w-full border border-gray-300 px-4 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="Leave blank to keep current password">
                </div>

                <!-- Submit Button -->
                <div>
                    <button type="submit" class="w-full bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition-colors">
                        Update Settings
                    </button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>) when i update or add image profile it can't to add i dont know why and this header that include the profile image (<?php
// includes/header.php

// Enable error reporting for debugging (Remove or comment out in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
    header("Location: /public/login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$last_order_id = 0;

// Fetch the last pending order ID to initialize polling
$initial_pending_sql = "
    SELECT o.id 
    FROM orders o
    WHERE o.status = 'Pending' 
    ORDER BY o.id DESC 
    LIMIT 1
";
$initial_result = $conn->query($initial_pending_sql);
if ($initial_result && $initial_result->num_rows > 0) {
    $row = $initial_result->fetch_assoc();
    $last_order_id = intval($row['id']);
}

// Fetch the logged-in user's profile information
$username = 'User'; // Default username
$profile_image = '/assets/images/user-placeholder.png'; // Default profile image

$stmt = $conn->prepare("SELECT username, profile_image FROM users WHERE id = ?");
if ($stmt) {
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result_user = $stmt->get_result();
    if ($result_user && $result_user->num_rows === 1) {
        $user = $result_user->fetch_assoc();
        $username = htmlspecialchars($user['username'], ENT_QUOTES, 'UTF-8');
        if (!empty($user['profile_image']) && file_exists(__DIR__ . '/../public/' . $user['profile_image'])) {
            // Append file modification time to prevent caching
            $mod_time = filemtime(__DIR__ . '/../public/' . $user['profile_image']);
            $profile_image = '/' . htmlspecialchars($user['profile_image'], ENT_QUOTES, 'UTF-8') . '?v=' . $mod_time;
        }
    }
    $stmt->close();
} else {
    // Log error or handle accordingly
    error_log("Failed to prepare statement for fetching user data.");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Meta Tags for Responsiveness and Accessibility -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    
    <!-- Tailwind CSS -->
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <!-- Bootstrap JS Bundle with Popper (Loaded Defer for Performance) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" defer></script>
    <!-- Alpine.js for Interactivity -->
    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.10.3/dist/cdn.min.js" defer></script>
    
    <!-- Custom Styles for Notification Links -->
    <style>
        .notification-link {
            display: block;
            color: inherit;
            text-decoration: none;
        }
        .notification-link:hover {
            background-color: #4a5568; /* Tailwind's gray-700 */
        }
        .notification-badge {
            position: absolute;
            top: 0;
            right: 0;
            width: 0.75rem;
            height: 0.75rem;
            background-color: #f56565; /* Tailwind's red-500 */
            border-radius: 9999px;
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0%, 100% { transform: scale(0.75); opacity: 1; }
            50% { transform: scale(1.25); opacity: 0.5; }
        }
    </style>
</head>
<body class="bg-gray-100">

    <!-- Audio Element for New Order Alert -->
    <audio id="newOrderAudio" src="/assets/audio/you_have_a_new_order.mp3" preload="auto"></audio>

    <!-- Header -->
    <header class="bg-gray-800 text-white py-4 border-b-4 border-yellow-400 shadow-lg fixed top-0 left-0 right-0 z-50">
        <div class="container mx-auto px-4 flex justify-between items-center">
            <!-- Logo -->
            <div class="flex items-center">
                <a href="/public/dashboard.php" class="flex items-center">
                    <img src="/assets/img/logo.png" alt="Kaak Alia Logo" class="h-12 w-auto mr-2">
                    <span class="text-xl font-bold">Admin Panel</span>
                </a>
            </div>

            <!-- Navigation Links (Desktop) -->
            <nav class="hidden md:flex space-x-4">
                <a href="/public/orders/add_order.php" class="flex items-center bg-yellow-400 text-gray-800 px-4 py-2 rounded-lg hover:bg-yellow-300 shadow transition-all duration-300">
                    <i class="bi bi-plus-circle-fill mr-2"></i> Add Order
                </a>
                <a href="/public/orders/view_orders.php" class="flex items-center bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-400 shadow transition-all duration-300">
                    <i class="bi bi-eye-fill mr-2"></i> View Orders
                </a>
                <a href="/public/products/manage_products.php" class="flex items-center bg-green-400 text-white px-4 py-2 rounded-lg hover:bg-green-300 shadow transition-all duration-300">
                    <i class="bi bi-box-seam-fill mr-2"></i> Manage Products
                </a>
                <a href="/public/users/manage_users.php" class="flex items-center bg-orange-500 text-white px-4 py-2 rounded-lg hover:bg-orange-400 shadow transition-all duration-300">
                    <i class="bi bi-people-fill mr-2"></i> Manage Users
                </a>
                <a href="/public/reports/generate_reports.php" class="flex items-center bg-pink-500 text-white px-4 py-2 rounded-lg hover:bg-pink-400 shadow transition-all duration-300">
                    <i class="bi bi-bar-chart-fill mr-2"></i> Reports
                </a>
            </nav>

            <!-- Right Side Icons -->
            <div class="flex items-center space-x-4">
                <!-- Notifications Dropdown -->
                <div class="relative" x-data="{ open: false }">
                    <button @click="open = !open" class="relative text-white hover:text-yellow-400 focus:outline-none" aria-haspopup="true" aria-expanded="false" aria-controls="notification-menu" aria-label="Notifications">
                        <i class="bi bi-bell-fill text-2xl"></i>
                        <?php if ($last_order_id > 0): ?>
                            <!-- Notification Badge -->
                            <span class="absolute top-0 right-0 inline-block w-3 h-3 bg-red-500 rounded-full"></span>
                        <?php endif; ?>
                    </button>
                    <!-- Dropdown Menu -->
                    <div x-show="open" @click.away="open = false" id="notification-menu" class="absolute right-0 mt-2 w-80 bg-gray-800 text-white rounded-lg shadow-lg z-50">
                        <div class="py-2 px-4 border-b border-yellow-400">
                            <h3 class="text-lg font-semibold">Notifications</h3>
                        </div>
                        <ul class="max-h-64 overflow-y-auto" id="notificationsList">
                            <?php
                            // Fetch the latest 5 pending orders with their items
                            $notifications_sql = "
                                SELECT DISTINCT o.id, o.order_date, c.name AS customer_name
                                FROM orders o
                                JOIN customers c ON o.customer_id = c.id
                                JOIN order_items oi ON oi.order_id = o.id
                                WHERE o.status = 'Pending'
                                ORDER BY o.id DESC
                                LIMIT 5
                            ";
                            $notifications_result = $conn->query($notifications_sql);
                            if ($notifications_result && $notifications_result->num_rows > 0):
                                while($notification = $notifications_result->fetch_assoc()):
                            ?>
                                    <li class="px-4 py-2 hover:bg-gray-700 cursor-pointer">
                                        <a href="/public/orders/view_order_customer.php?order_id=<?= htmlspecialchars($notification['id'], ENT_QUOTES, 'UTF-8') ?>" class="notification-link flex items-center">
                                            <span class="inline-block w-2 h-2 bg-red-500 rounded-full mr-2"></span>
                                            New Order: <?= htmlspecialchars($notification['customer_name'], ENT_QUOTES, 'UTF-8'); ?> placed on <?= date("d M Y, h:i A", strtotime($notification['order_date'])) ?>
                                        </a>
                                    </li>
                            <?php
                                endwhile;
                            else:
                            ?>
                                <li class="px-4 py-2 text-gray-400">No new notifications</li>
                            <?php endif; ?>
                        </ul>
                        <div class="py-2 px-4 border-t border-yellow-400 text-center">
                            <a href="/public/notifications.php" class="text-yellow-400 hover:underline">View All</a>
                        </div>
                    </div>
                </div>

                <!-- User Profile Dropdown -->
                <div class="relative" x-data="{ open: false }">
                    <button @click="open = !open" class="flex items-center focus:outline-none" aria-haspopup="true" aria-expanded="false" aria-controls="profile-menu">
                        <img src="<?= $profile_image ?>" alt="User Avatar" class="h-10 w-10 rounded-full border-2 border-white hover:border-yellow-400 transition-colors duration-300">
                        <span class="ml-2 hidden lg:inline-block">
                            <?= $username ?>
                        </span>
                        <i class="bi bi-caret-down-fill ml-1 hidden lg:inline-block"></i>
                    </button>
                    <!-- Dropdown Menu -->
                    <div x-show="open" @click.away="open = false" id="profile-menu" class="absolute right-0 mt-2 w-48 bg-gray-800 text-white rounded-lg shadow-lg z-50">
                        <a href="/public/workspace/index.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
                            <i class="bi bi-laptop mr-2"></i> WorkSpace
                        </a>
                        
                        <a href="/public/drivers/drivers_list.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
                            <i class="bi bi-car-front mr-2"></i> Drivers
                        </a>

                        <a href="/includes/user_settings.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
                            <i class="bi bi-gear-fill mr-2"></i> Settings
                        </a>
                        <a href="/public/about_kaakalia/index.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
                            <i class="bi bi-info-circle mr-2"></i> About Kaak Alia
                        </a>
                        
                        
                        <a href="/public/logout.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
                            <i class="bi bi-box-arrow-right mr-2"></i> Logout
                        </a>
                    </div>
                </div>

                <!-- Mobile Menu Button -->
                <div class="md:hidden">
                    <button id="mobile-menu-button" class="text-white focus:outline-none" aria-label="Toggle Mobile Menu">
                        <i class="bi bi-list text-2xl"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- Mobile Navigation Menu -->
        <nav id="mobile-menu" class="hidden md:hidden mt-4">
            <ul class="flex flex-col space-y-2">
                <li>
                    <a href="/public/orders/add_order.php" class="flex items-center bg-yellow-400 text-gray-800 px-4 py-2 rounded-lg hover:bg-yellow-300 transition-all duration-300">
                        <i class="bi bi-plus-circle-fill mr-2"></i> Add Order
                    </a>
                </li>
                <li>
                    <a href="/public/orders/view_orders.php" class="flex items-center bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-400 transition-all duration-300">
                        <i class="bi bi-eye-fill mr-2"></i> View Orders
                    </a>
                </li>
                <li>
                    <a href="/public/products/manage_products.php" class="flex items-center bg-green-400 text-white px-4 py-2 rounded-lg hover:bg-green-300 transition-all duration-300">
                        <i class="bi bi-box-seam-fill mr-2"></i> Manage Products
                    </a>
                </li>
                <li>
                    <a href="/public/users/manage_users.php" class="flex items-center bg-orange-500 text-white px-4 py-2 rounded-lg hover:bg-orange-400 transition-all duration-300">
                        <i class="bi bi-people-fill mr-2"></i> Manage Users
                    </a>
                </li>
                <li>
                    <a href="/public/reports/generate_reports.php" class="flex items-center bg-pink-500 text-white px-4 py-2 rounded-lg hover:bg-pink-400 transition-all duration-300">
                        <i class="bi bi-bar-chart-fill mr-2"></i> Reports
                    </a>
                </li>
                <!-- Additional Mobile Links -->
                <li>
                    <a href="/public/notifications.php" class="flex items-center bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-all duration-300">
                        <i class="bi bi-bell-fill mr-2"></i> Notifications
                    </a>
                </li>
                <li>
                    <a href="/includes/user_settings.php" class="flex items-center bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-all duration-300">
                        <i class="bi bi-gear-fill mr-2"></i> Settings
                    </a>
                </li>
                <li>
                    <a href="/public/about_kaakalia/index.php" class="flex items-center bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-all duration-300">
                        <i class="bi bi-info-circle mr-2"></i> About Kaak Alia
                    </a>
                </li>
            </ul>
        </nav>
    </header>

    <!-- JavaScript for Real-Time Notifications and Mobile Menu Toggle -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const mobileMenuButton = document.getElementById('mobile-menu-button');
            const mobileMenu = document.getElementById('mobile-menu');

            // Toggle mobile menu on button click
            mobileMenuButton.addEventListener('click', function() {
                mobileMenu.classList.toggle('hidden');
            });

            let lastOrderId = <?= $last_order_id ?>;
            const audio = document.getElementById('newOrderAudio');

            // Function to fetch new orders
            function fetchNewOrders() {
                fetch(`/includes/get_new_orders.php?last_order_id=${lastOrderId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.orders && data.orders.length > 0) {
                            data.orders.forEach(order => {
                                // Update lastOrderId if needed
                                if (order.id > lastOrderId) {
                                    lastOrderId = order.id;
                                }

                                // Create a new notification item
                                const notificationsList = document.getElementById('notificationsList');
                                const li = document.createElement('li');
                                li.className = 'px-4 py-2 hover:bg-gray-700 cursor-pointer';
                                
                                // Create a link to the order details page
                                const a = document.createElement('a');
                                a.href = `/public/orders/view_order_customer.php?order_id=${encodeURIComponent(order.id)}`;
                                a.className = 'notification-link flex items-center';
                                a.innerHTML = `
                                    <span class="inline-block w-2 h-2 bg-red-500 rounded-full mr-2"></span>
                                    New Order: ${sanitizeHTML(order.customer_name)} placed on ${sanitizeHTML(order.order_date)}
                                `;

                                li.appendChild(a);
                                // Insert the new notification at the top
                                notificationsList.insertBefore(li, notificationsList.firstChild);

                                // Play the audio alert
                                if (audio) {
                                    audio.play().catch(function(error) {
                                        console.log('Audio playback failed:', error);
                                    });
                                }

                                // Optionally, update the notification badge
                                const bellIcon = document.querySelector('header .bi-bell-fill');
                                const existingBadge = bellIcon.parentNode.querySelector('.notification-badge');
                                if (!existingBadge) {
                                    const badge = document.createElement('span');
                                    badge.className = 'notification-badge';
                                    bellIcon.parentNode.appendChild(badge);
                                }
                            });
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching new orders:', error);
                    });
            }

            // Function to sanitize HTML to prevent XSS
            function sanitizeHTML(str) {
                var temp = document.createElement('div');
                temp.textContent = str;
                return temp.innerHTML;
            }

            // Poll every 10 seconds for new orders
            setInterval(fetchNewOrders, 10000); // 10000 ms = 10 seconds

            // Fetch immediately on page load
            fetchNewOrders();
        });
    </script>
</body>
</html>) and type full codes