based on thsi info database (-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Nov 11, 2024 at 06:01 AM
-- 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;

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

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

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

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

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

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

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

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

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

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

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

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

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

--
-- 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 for table `ad_spend_logs`
--
ALTER TABLE `ad_spend_logs`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

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

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

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

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

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

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

--
-- 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 want to add new feature on this codes (<?php
// /public/workspace/create_plan.php

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

// Start output buffering to prevent "headers already sent" errors
ob_start();

// Include authentication, database connection, and utility functions
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php'; // Contains sanitize_input()

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

// Pre-fill due_date if passed via GET (e.g., from calendar selection)
$pre_fill_due_date = sanitize_input($_GET['due_date'] ?? '');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = sanitize_input($_POST['title'] ?? '');
    $description = sanitize_input($_POST['description'] ?? '');
    $due_date = sanitize_input($_POST['due_date'] ?? '');
    $status = sanitize_input($_POST['status'] ?? 'Not Started');

    // Validation
    if (empty($title)) {
        $errors[] = "Title is required.";
    }
    if (empty($due_date)) {
        $errors[] = "Due date is required.";
    }

    // Validate status
    $valid_statuses = ['Not Started', 'In Progress', 'Completed'];
    if (!in_array($status, $valid_statuses)) {
        $errors[] = "Invalid status selected.";
    }

    // Validate due_date format
    if (!strtotime($due_date)) {
        $errors[] = "Invalid due date format.";
    }

    if (empty($errors)) {
        $sql = "INSERT INTO workspace_plans (user_id, title, description, due_date, status) VALUES (?, ?, ?, ?, ?)";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("issss", $user_id, $title, $description, $due_date, $status);
            if ($stmt->execute()) {
                header("Location: plans.php");
                exit();
            } else {
                $errors[] = "Failed to create plan. Please try again.";
            }
            $stmt->close();
        } else {
            $errors[] = "Database error: Unable to prepare statement.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Plan - Workspace</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">
</head>
<body class="bg-gray-100 min-h-screen flex flex-col">
    <!-- Header -->
    <?php include __DIR__ . '/../../includes/header.php'; ?>

    <!-- Main Content -->
    <main class="container mx-auto p-6 mt-24 flex-grow">
        <h1 class="text-2xl font-bold mb-6">Create New Plan</h1>

        <!-- Display Errors -->
        <?php if(!empty($errors)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                <ul>
                    <?php foreach($errors as $error): ?>
                        <li><?= htmlspecialchars($error) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <!-- Plan Creation Form -->
        <form action="create_plan.php" method="POST" class="bg-white p-6 rounded shadow-md">
            <div class="mb-4">
                <label class="block text-gray-700">Title<span class="text-red-500">*</span></label>
                <input type="text" name="title" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300" required value="<?= isset($_POST['title']) ? htmlspecialchars($_POST['title']) : '' ?>">
            </div>
            <div class="mb-4">
                <label class="block text-gray-700">Description</label>
                <textarea name="description" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300" rows="4"><?= isset($_POST['description']) ? htmlspecialchars($_POST['description']) : '' ?></textarea>
            </div>
            <div class="mb-4">
                <label class="block text-gray-700">Due Date<span class="text-red-500">*</span></label>
                <input type="datetime-local" name="due_date" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300" required value="<?= isset($_POST['due_date']) ? htmlspecialchars($_POST['due_date']) : $pre_fill_due_date ?>">
            </div>
            <div class="mb-4">
                <label class="block text-gray-700">Status</label>
                <select name="status" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300">
                    <option value="Not Started" <?= (isset($_POST['status']) && $_POST['status'] == 'Not Started') ? 'selected' : '' ?>>Not Started</option>
                    <option value="In Progress" <?= (isset($_POST['status']) && $_POST['status'] == 'In Progress') ? 'selected' : '' ?>>In Progress</option>
                    <option value="Completed" <?= (isset($_POST['status']) && $_POST['status'] == 'Completed') ? 'selected' : '' ?>>Completed</option>
                </select>
            </div>
            <div class="flex justify-between">
                <a href="plans.php" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">Cancel</a>
                <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">Create Plan</button>
            </div>
        </form>
    </main>

    <!-- Footer -->
    <footer class="bg-gray-800 text-white text-center p-4">
        &copy; 2024 Kaak Alia Bakery. All rights reserved.
    </footer>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
?>) in this codes plan, i want to add record audio, and make it optiaonal choose and i want this feature if admin user wants to make record instead of type descpption and easy for them and this view plan (<?php
// /public/workspace/view_plan.php

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

// Start output buffering to prevent "headers already sent" errors
ob_start();

// Include authentication, database connection, and utility functions
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php'; // Contains sanitize_input()

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

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role']; // 'admin' or 'staff'

// Get plan ID from GET parameter
$plan_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($plan_id <= 0) {
    // Invalid plan ID
    header("Location: plans.php?error=Invalid+plan+ID");
    exit();
}

$plan = [];
$errors = [];

// Fetch plan details
try {
    if ($user_role === 'admin') {
        // Admin can view any plan
        $sql = "SELECT wp.id, wp.title, wp.description, wp.due_date, wp.status, wp.created_at, wp.updated_at, u.username 
                FROM workspace_plans wp
                JOIN users u ON wp.user_id = u.id
                WHERE wp.id = ?";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param("i", $plan_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $plan = $result->fetch_assoc();
            if (!$plan) {
                $errors[] = "Plan not found.";
            }
            $stmt->close();
        } else {
            throw new Exception("Prepare statement failed: " . $conn->error);
        }
    } else {
        // Regular user: Can only view their own plans
        $sql = "SELECT wp.id, wp.title, wp.description, wp.due_date, wp.status, wp.created_at, wp.updated_at, u.username 
                FROM workspace_plans wp
                JOIN users u ON wp.user_id = u.id
                WHERE wp.id = ? AND wp.user_id = ?";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param("ii", $plan_id, $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $plan = $result->fetch_assoc();
            if (!$plan) {
                $errors[] = "Plan not found or you do not have permission to view this plan.";
            }
            $stmt->close();
        } else {
            throw new Exception("Prepare statement failed: " . $conn->error);
        }
    }
} catch (Exception $e) {
    $errors[] = $e->getMessage();
}

// Handle status update if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $new_status = sanitize_input($_POST['status'] ?? '');
    $valid_statuses = ['Not Started', 'In Progress', 'Completed'];

    // Validate new status
    if (!in_array($new_status, $valid_statuses)) {
        $errors[] = "Invalid status selected.";
    }

    if (empty($errors)) {
        try {
            if ($user_role === 'admin') {
                // Admin can update any plan
                $update_sql = "UPDATE workspace_plans SET status = ?, updated_at = CURRENT_TIMESTAMP() WHERE id = ?";
                $stmt = $conn->prepare($update_sql);
                if ($stmt) {
                    $stmt->bind_param("si", $new_status, $plan_id);
                    if ($stmt->execute()) {
                        // Success, redirect with success message
                        header("Location: view_plan.php?id=$plan_id&message=Plan+status+updated+successfully");
                        exit();
                    } else {
                        throw new Exception("Failed to update plan status.");
                    }
                } else {
                    throw new Exception("Prepare statement failed: " . $conn->error);
                }
            } else {
                // Regular user: Can only update their own plans
                $update_sql = "UPDATE workspace_plans SET status = ?, updated_at = CURRENT_TIMESTAMP() WHERE id = ? AND user_id = ?";
                $stmt = $conn->prepare($update_sql);
                if ($stmt) {
                    $stmt->bind_param("sii", $new_status, $plan_id, $user_id);
                    if ($stmt->execute()) {
                        if ($stmt->affected_rows > 0) {
                            // Success, redirect with success message
                            header("Location: view_plan.php?id=$plan_id&message=Plan+status+updated+successfully");
                            exit();
                        } else {
                            throw new Exception("Failed to update plan status or no changes made.");
                        }
                    } else {
                        throw new Exception("Failed to update plan status.");
                    }
                } else {
                    throw new Exception("Prepare statement failed: " . $conn->error);
                }
            }
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }

    // Refresh plan details after update
    if (empty($errors)) {
        // Re-fetch the updated plan details
        try {
            if ($user_role === 'admin') {
                // Admin can view any plan
                $sql = "SELECT wp.id, wp.title, wp.description, wp.due_date, wp.status, wp.created_at, wp.updated_at, u.username 
                        FROM workspace_plans wp
                        JOIN users u ON wp.user_id = u.id
                        WHERE wp.id = ?";
                $stmt = $conn->prepare($sql);
                if ($stmt) {
                    $stmt->bind_param("i", $plan_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    $plan = $result->fetch_assoc();
                    if (!$plan) {
                        $errors[] = "Plan not found.";
                    }
                    $stmt->close();
                } else {
                    throw new Exception("Prepare statement failed: " . $conn->error);
                }
            } else {
                // Regular user: Can only view their own plans
                $sql = "SELECT wp.id, wp.title, wp.description, wp.due_date, wp.status, wp.created_at, wp.updated_at, u.username 
                        FROM workspace_plans wp
                        JOIN users u ON wp.user_id = u.id
                        WHERE wp.id = ? AND wp.user_id = ?";
                $stmt = $conn->prepare($sql);
                if ($stmt) {
                    $stmt->bind_param("ii", $plan_id, $user_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    $plan = $result->fetch_assoc();
                    if (!$plan) {
                        $errors[] = "Plan not found or you do not have permission to view this plan.";
                    }
                    $stmt->close();
                } else {
                    throw new Exception("Prepare statement failed: " . $conn->error);
                }
            }
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

// Fetch messages from query parameters
$success_message = isset($_GET['message']) ? sanitize_input($_GET['message']) : '';
$error_message = isset($_GET['error']) ? sanitize_input($_GET['error']) : '';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>View Plan - Workspace</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">
</head>
<body class="bg-gray-100 min-h-screen flex flex-col">
    <!-- Header -->
    <?php include __DIR__ . '/../../includes/header.php'; ?>

    <!-- Main Content -->
    <main class="container mx-auto p-6 mt-24 flex-grow">
        <?php if ($success_message): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
                <?= htmlspecialchars($success_message) ?>
            </div>
        <?php endif; ?>
        <?php if ($error_message): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                <?= htmlspecialchars($error_message) ?>
            </div>
        <?php endif; ?>

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

        <?php if ($plan): ?>
            <div class="bg-white p-6 rounded-lg shadow-md">
                <h1 class="text-3xl font-bold mb-4"><?= htmlspecialchars($plan['title']) ?></h1>
                <p class="text-gray-700 mb-4"><?= nl2br(htmlspecialchars($plan['description'])) ?></p>
                <div class="mb-4">
                    <span class="font-semibold">Due Date:</span>
                    <span><?= htmlspecialchars(date("d M Y, h:i A", strtotime($plan['due_date']))) ?></span>
                </div>
                <div class="mb-4">
                    <span class="font-semibold">Status:</span>
                    <span class="text-sm px-2 py-1 rounded <?= 
                        $plan['status'] === 'Not Started' ? 'bg-yellow-200 text-yellow-800' :
                        ($plan['status'] === 'In Progress' ? 'bg-blue-200 text-blue-800' :
                        ($plan['status'] === 'Completed' ? 'bg-green-200 text-green-800' : 'bg-gray-200 text-gray-800'))
                    ?>">
                        <?= htmlspecialchars($plan['status']) ?>
                    </span>
                </div>
                <div class="mb-4">
                    <span class="font-semibold">Created By:</span>
                    <span><?= htmlspecialchars($plan['username']) ?></span>
                </div>
                <div class="mb-4">
                    <span class="font-semibold">Created At:</span>
                    <span><?= htmlspecialchars(date("d M Y, h:i A", strtotime($plan['created_at']))) ?></span>
                </div>
                <div class="mb-4">
                    <span class="font-semibold">Last Updated:</span>
                    <span><?= htmlspecialchars(date("d M Y, h:i A", strtotime($plan['updated_at']))) ?></span>
                </div>

                <!-- Status Update Form -->
                <div class="mt-6">
                    <h2 class="text-xl font-semibold mb-2">Update Status</h2>
                    <form action="view_plan.php?id=<?= htmlspecialchars($plan_id) ?>" method="POST" class="flex items-center">
                        <select name="status" class="w-1/2 px-3 py-2 border rounded-l focus:outline-none focus:ring focus:border-blue-300" required>
                            <option value="">-- Select Status --</option>
                            <option value="Not Started" <?= ($plan['status'] === 'Not Started') ? 'selected' : '' ?>>Not Started</option>
                            <option value="In Progress" <?= ($plan['status'] === 'In Progress') ? 'selected' : '' ?>>In Progress</option>
                            <option value="Completed" <?= ($plan['status'] === 'Completed') ? 'selected' : '' ?>>Completed</option>
                        </select>
                        <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded-r hover:bg-blue-600">
                            <i class="bi bi-pencil-square"></i> Update
                        </button>
                    </form>
                </div>

                <!-- Action Buttons -->
                <div class="mt-6 flex space-x-4">
                    <a href="edit_plan.php?id=<?= htmlspecialchars($plan_id) ?>" class="px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600 flex items-center">
                        <i class="bi bi-pencil-square mr-2"></i> Edit Plan
                    </a>
                    <a href="plans.php" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 flex items-center">
                        <i class="bi bi-arrow-left mr-2"></i> Back to Plans
                    </a>
                </div>
            </div>
        <?php else: ?>
            <div class="text-center text-gray-600">
                <p>No plan details to display.</p>
                <a href="plans.php" class="mt-4 inline-block px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">
                    Back to Plans
                </a>
            </div>
        <?php endif; ?>
    </main>

    <!-- Footer -->
    <footer class="bg-gray-800 text-white text-center p-4">
        &copy; 2024 Kaak Alia Bakery. All rights reserved.
    </footer>
</body>
</html>

<?php
// Flush the output buffer
ob_end_flush();
?>) and delete (<?php
// /public/workspace/delete_plan.php

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

// Start output buffering to prevent "headers already sent" errors
ob_start();

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

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

// Get user details from session
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role']; // 'admin' or 'staff'

// Get plan ID from GET parameter
$plan_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($plan_id > 0) {
    // Verify that the plan belongs to the user or the user is admin
    if ($user_role === 'admin') {
        // Admin can delete any plan
        $sql = "SELECT id FROM workspace_plans WHERE id = ?";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param("i", $plan_id);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                $stmt->close();
                // Proceed to delete
                $delete_sql = "DELETE FROM workspace_plans WHERE id = ?";
                $delete_stmt = $conn->prepare($delete_sql);
                if ($delete_stmt) {
                    $delete_stmt->bind_param("i", $plan_id);
                    if ($delete_stmt->execute()) {
                        // Success, redirect to plans.php with success message
                        header("Location: plans.php?message=Plan+deleted+successfully");
                        exit();
                    } else {
                        // Deletion failed
                        header("Location: plans.php?error=Failed+to+delete+plan");
                        exit();
                    }
                } else {
                    // Prepare failed
                    header("Location: plans.php?error=Database+error");
                    exit();
                }
            } else {
                // Plan not found
                header("Location: plans.php?error=Plan+not+found");
                exit();
            }
        } else {
            // Prepare failed
            header("Location: plans.php?error=Database+error");
            exit();
        }
    } else {
        // Regular user: Verify ownership
        $sql = "SELECT id FROM workspace_plans WHERE id = ? AND user_id = ?";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("ii", $plan_id, $user_id);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                // Proceed to delete
                $stmt->close();
                $delete_sql = "DELETE FROM workspace_plans WHERE id = ? AND user_id = ?";
                $delete_stmt = $conn->prepare($delete_sql);
                if ($delete_stmt) {
                    $delete_stmt->bind_param("ii", $plan_id, $user_id);
                    if ($delete_stmt->execute()) {
                        // Success, redirect to plans.php with success message
                        header("Location: plans.php?message=Plan+deleted+successfully");
                        exit();
                    } else {
                        // Deletion failed
                        header("Location: plans.php?error=Failed+to+delete+plan");
                        exit();
                    }
                } else {
                    // Prepare failed
                    header("Location: plans.php?error=Database+error");
                    exit();
                }
            } else {
                // Plan not found or doesn't belong to user
                header("Location: plans.php?error=Plan+not+found");
                exit();
            }
        } else {
            // Prepare failed
            header("Location: plans.php?error=Database+error");
            exit();
        }
    }
} else {
    // Invalid plan ID
    header("Location: plans.php?error=Invalid+plan+ID");
    exit();
}

// Flush the output buffer
ob_end_flush();
?>) and type full codes with guides