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 11, 2024 at 06:48 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,
  `audio_path` varchar(255) 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 */;)  on this create plan page (<?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()

// 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'
$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');

    // Determine if audio was uploaded via file input or via recording
    $use_audio_upload = isset($_FILES['audio_file']) && $_FILES['audio_file']['error'] !== UPLOAD_ERR_NO_FILE;
    $use_audio_recording = isset($_POST['audio_data']) && !empty($_POST['audio_data']);

    $audio_path = null;

    // 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.";
    }

    // Handle audio upload if admin opted to upload a file
    if ($user_role === 'admin' && $use_audio_upload) {
        $allowed_types = ['audio/mpeg', 'audio/wav', 'audio/mp3'];
        $max_size = 5 * 1024 * 1024; // 5 MB

        if ($_FILES['audio_file']['error'] !== UPLOAD_ERR_OK) {
            $errors[] = "Error uploading audio file.";
        } elseif (!in_array($_FILES['audio_file']['type'], $allowed_types)) {
            $errors[] = "Invalid audio file type. Only MP3 and WAV are allowed.";
        } elseif ($_FILES['audio_file']['size'] > $max_size) {
            $errors[] = "Audio file size exceeds the 5MB limit.";
        } else {
            // Create uploads directory if not exists
            $upload_dir = __DIR__ . '/../../uploads/audio_plans/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            // Generate a unique file name
            $file_ext = pathinfo($_FILES['audio_file']['name'], PATHINFO_EXTENSION);
            $file_name = uniqid('plan_audio_', true) . '.' . $file_ext;
            $destination = $upload_dir . $file_name;

            // Move the uploaded file
            if (move_uploaded_file($_FILES['audio_file']['tmp_name'], $destination)) {
                $audio_path = 'uploads/audio_plans/' . $file_name;
                // Clear description if audio is uploaded
                $description = null;
            } else {
                $errors[] = "Failed to save the uploaded audio file.";
            }
        }
    }

    // Handle audio recording if admin opted to record
    if ($user_role === 'admin' && $use_audio_recording && empty($use_audio_upload)) {
        // Decode the base64 audio data
        $audio_base64 = $_POST['audio_data'];
        $audio_binary = base64_decode(preg_replace('#^data:\w+/\w+;base64,#i', '', $audio_base64));

        if ($audio_binary === false) {
            $errors[] = "Invalid audio data.";
        } else {
            // Create uploads directory if not exists
            $upload_dir = __DIR__ . '/../../uploads/audio_plans/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            // Generate a unique file name
            $file_name = uniqid('plan_audio_', true) . '.webm'; // Assuming webm format from MediaRecorder
            $file_path = $upload_dir . $file_name;

            // Save the audio file
            if (file_put_contents($file_path, $audio_binary)) {
                $audio_path = 'uploads/audio_plans/' . $file_name;
                // Clear description if audio is recorded
                $description = null;
            } else {
                $errors[] = "Failed to save the recorded audio.";
            }
        }
    }

    // If audio is either uploaded or recorded, clear the description
    if (($use_audio_upload || $use_audio_recording) && $audio_path) {
        $description = null;
    }

    // Ensure that either description or audio is provided
    if (!$use_audio_upload && !$use_audio_recording && empty($description)) {
        $errors[] = "Either description or audio recording is required.";
    }

    if (($use_audio_upload || $use_audio_recording) && empty($audio_path)) {
        $errors[] = "Audio recording/upload is required when audio is selected.";
    }

    if (empty($errors)) {
        // Insert plan into database
        $sql = "INSERT INTO workspace_plans (user_id, title, description, audio_path, due_date, status) VALUES (?, ?, ?, ?, ?, ?)";

        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("isssss", $user_id, $title, $description, $audio_path, $due_date, $status);
            if ($stmt->execute()) {
                header("Location: plans.php?message=Plan+created+successfully");
                exit();
            } else {
                $errors[] = "Failed to create plan. Please try again.";
                // If audio was uploaded or recorded, delete the file to prevent orphan files
                if ($audio_path) {
                    unlink(__DIR__ . '/../../' . $audio_path);
                }
            }
            $stmt->close();
        } else {
            $errors[] = "Database error: Unable to prepare statement.";
            // If audio was uploaded or recorded, delete the file to prevent orphan files
            if ($audio_path) {
                unlink(__DIR__ . '/../../' . $audio_path);
            }
        }
    }
}
?>
<!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">
    <!-- Custom Styles -->
    <style>
        /* Custom styles for audio recorder */
        #audio_recorder_section {
            display: none;
        }
        .hidden {
            display: none;
        }
    </style>
</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" enctype="multipart/form-data" 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>
            <?php if ($user_role === 'admin'): ?>
                <div class="mb-4">
                    <label class="block text-gray-700">Audio Option</label>
                    <div class="flex items-center">
                        <input type="radio" id="audio_option_none" name="audio_option" value="none" checked class="mr-2" onchange="toggleAudioOptions('none')">
                        <label for="audio_option_none" class="mr-4">None</label>

                        <input type="radio" id="audio_option_upload" name="audio_option" value="upload" class="mr-2" onchange="toggleAudioOptions('upload')">
                        <label for="audio_option_upload" class="mr-4">Upload Audio File</label>

                        <input type="radio" id="audio_option_record" name="audio_option" value="record" class="mr-2" onchange="toggleAudioOptions('record')">
                        <label for="audio_option_record">Record Audio</label>
                    </div>
                </div>

                <!-- Audio Upload Section -->
                <div class="mb-4 hidden" id="audio_upload_section">
                    <label class="block text-gray-700">Upload Audio File<span class="text-red-500">*</span></label>
                    <input type="file" name="audio_file" accept="audio/*" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300">
                    <small class="text-gray-500">Accepted formats: MP3, WAV. Max size: 5MB.</small>
                </div>

                <!-- Audio Recorder Section -->
                <div class="mb-4 hidden" id="audio_recorder_section">
                    <label class="block text-gray-700">Record Audio<span class="text-red-500">*</span></label>
                    <button type="button" id="start_recording" class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600">Start Recording</button>
                    <button type="button" id="stop_recording" class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 hidden">Stop Recording</button>
                    <div id="recording_indicator" class="text-red-500 mt-2 hidden">Recording...</div>
                    <audio id="recorded_audio" class="mt-4" controls></audio>
                    <input type="hidden" name="audio_data" id="audio_data">
                </div>
            <?php endif; ?>
            <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>

    <!-- JavaScript for Audio Recording -->
    <?php if ($user_role === 'admin'): ?>
        <script>
            /**
             * Toggle visibility of audio options based on selected radio button.
             * @param {string} option - The selected audio option ('none', 'upload', 'record').
             */
            function toggleAudioOptions(option) {
                document.getElementById('audio_upload_section').style.display = (option === 'upload') ? 'block' : 'none';
                document.getElementById('audio_recorder_section').style.display = (option === 'record') ? 'block' : 'none';

                // Clear audio data if switching options
                if (option !== 'record') {
                    document.getElementById('audio_data').value = '';
                    document.getElementById('recorded_audio').src = '';
                }
                if (option !== 'upload') {
                    document.querySelector('input[name="audio_file"]').value = '';
                }
            }

            // Initialize media recorder variables
            let mediaRecorder;
            let recordedChunks = [];

            const startButton = document.getElementById('start_recording');
            const stopButton = document.getElementById('stop_recording');
            const recordingIndicator = document.getElementById('recording_indicator');
            const recordedAudio = document.getElementById('recorded_audio');
            const audioDataInput = document.getElementById('audio_data');

            // Check for MediaRecorder API support
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                startButton.addEventListener('click', startRecording);
                stopButton.addEventListener('click', stopRecording);
            } else {
                alert('Your browser does not support audio recording.');
                startButton.disabled = true;
                stopButton.disabled = true;
            }

            /**
             * Start recording audio using MediaRecorder API.
             */
            function startRecording() {
                navigator.mediaDevices.getUserMedia({ audio: true })
                    .then(stream => {
                        mediaRecorder = new MediaRecorder(stream);
                        mediaRecorder.start();
                        recordingIndicator.style.display = 'block';
                        startButton.classList.add('hidden');
                        stopButton.classList.remove('hidden');

                        mediaRecorder.ondataavailable = function(e) {
                            recordedChunks.push(e.data);
                        };

                        mediaRecorder.onstop = function() {
                            const blob = new Blob(recordedChunks, { type: 'audio/webm' });
                            recordedChunks = [];

                            // Create a URL for the recorded audio and set it to the audio element
                            const audioURL = URL.createObjectURL(blob);
                            recordedAudio.src = audioURL;

                            // Convert the blob to base64 and set it to the hidden input
                            const reader = new FileReader();
                            reader.readAsDataURL(blob);
                            reader.onloadend = function() {
                                const base64data = reader.result;
                                audioDataInput.value = base64data;
                            };

                            recordingIndicator.style.display = 'none';
                            startButton.classList.remove('hidden');
                            stopButton.classList.add('hidden');
                        };
                    })
                    .catch(err => {
                        console.error('The following error occurred:', err);
                        alert('Could not access the microphone. Please check your permissions.');
                    });
            }

            /**
             * Stop recording audio.
             */
            function stopRecording() {
                mediaRecorder.stop();
                mediaRecorder.stream.getTracks().forEach(track => track.stop());
            }

            // Maintain the audio options state on form submission errors
            window.onload = function() {
                <?php
                if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                    if ($user_role === 'admin') {
                        if ($use_audio_upload) {
                            echo "toggleAudioOptions('upload');";
                        } elseif ($use_audio_recording) {
                            echo "toggleAudioOptions('record');";
                        } else {
                            echo "toggleAudioOptions('none');";
                        }
                    }
                }
                ?>
            }
        </script>
    <?php endif; ?>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
?>) i want when enter description, and make a record or upload the record, save both them in plan and don't remove other if made one of 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.audio_path, 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.audio_path, 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.audio_path, 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.audio_path, 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 mb-16"> <!-- Added mb-16 to prevent overlap with fixed footer -->
        <?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>
                
                <?php if (!empty($plan['audio_path'])): ?>
                    <div class="mb-4">
                        <span class="block text-gray-700 font-semibold mb-2">Audio Description:</span>
                        <?php
                            // Ensure the audio file exists
                            $audio_full_path = __DIR__ . '/../../' . $plan['audio_path'];
                            if (file_exists($audio_full_path)):
                                // Get the MIME type
                                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                                $mime_type = finfo_file($finfo, $audio_full_path);
                                finfo_close($finfo);
                        ?>
                            <audio controls class="w-full">
                                <source src="<?= htmlspecialchars('/' . $plan['audio_path']) ?>" type="<?= htmlspecialchars($mime_type) ?>">
                                Your browser does not support the audio element.
                            </audio>
                        <?php else: ?>
                            <p class="text-red-500">Audio file not found.</p>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <p class="text-gray-700 mb-4"><?= nl2br(htmlspecialchars($plan['description'] ?? '')) ?></p>
                <?php endif; ?>

                <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 fixed bottom-0 left-0 w-full">
        &copy; 2024 Kaak Alia Bakery. All rights reserved.
    </footer>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
?>) and and this plan page (<?php
// /public/workspace/plans.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'

// Fetch all plans along with the creator's username
$sql = "SELECT wp.*, u.username 
        FROM workspace_plans wp
        JOIN users u ON wp.user_id = u.id
        ORDER BY wp.due_date ASC";

$plans = [];
if ($stmt = $conn->prepare($sql)) {
    // No parameters to bind since we're fetching all plans
    if ($stmt->execute()) {
        $result = $stmt->get_result();
        while ($plan = $result->fetch_assoc()) {
            $plans[] = $plan;
        }
    } else {
        // Handle execution error if needed
        // For example, log the error or display a user-friendly message
    }
    $stmt->close();
} else {
    // Handle preparation error if needed
    // For example, log the error or display a user-friendly message
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Plans & Tasks - 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 mb-16"> <!-- Added mb-16 to prevent overlap with fixed footer -->
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold">Plans & Tasks</h1>
            <a href="create_plan.php" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 flex items-center">
                <i class="bi bi-plus-lg mr-2"></i> Add New Plan
            </a>
        </div>

        <!-- Plans Listing -->
        <?php if(!empty($plans)): ?>
            <div class="overflow-x-auto">
                <table class="min-w-full bg-white rounded shadow-md">
                    <thead>
                        <tr class="bg-gray-200">
                            <th class="px-4 py-2 text-left">Title</th>
                            <th class="px-4 py-2 text-left">Description</th>
                            <th class="px-4 py-2 text-left">Due Date</th>
                            <th class="px-4 py-2 text-left">Status</th>
                            <th class="px-4 py-2 text-left">Creator</th>
                            <th class="px-4 py-2 text-left">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($plans as $plan): ?>
                            <tr class="border-b hover:bg-gray-100">
                                <td class="px-4 py-2"><?= htmlspecialchars($plan['title'] ?? '') ?></td>
                                <td class="px-4 py-2">
                                    <?php if (!empty($plan['audio_path'])): ?>
                                        <span class="text-blue-500">Audio Available</span>
                                    <?php else: ?>
                                        <?= nl2br(htmlspecialchars($plan['description'] ?? '')) ?>
                                    <?php endif; ?>
                                </td>
                                <td class="px-4 py-2"><?= htmlspecialchars(date("d M Y, h:i A", strtotime($plan['due_date']))) ?></td>
                                <td class="px-4 py-2">
                                    <span class="px-2 py-1 rounded <?= 
                                        $plan['status'] == 'Completed' ? 'bg-green-500 text-white' :
                                        ($plan['status'] == 'In Progress' ? 'bg-yellow-500 text-white' : 'bg-red-500 text-white') ?>">
                                        <?= htmlspecialchars($plan['status']) ?>
                                    </span>
                                </td>
                                <td class="px-4 py-2"><?= htmlspecialchars($plan['username'] ?? '') ?></td>
                                <td class="px-4 py-2">
                                    <a href="view_plan.php?id=<?= htmlspecialchars($plan['id']) ?>" class="text-blue-500 hover:underline mr-2">View</a>
                                    <a href="edit_plan.php?id=<?= htmlspecialchars($plan['id']) ?>" class="text-blue-500 hover:underline mr-2">Edit</a>
                                    <a href="delete_plan.php?id=<?= htmlspecialchars($plan['id']) ?>" class="text-red-500 hover:underline" onclick="return confirm('Are you sure you want to delete this plan?');">Delete</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <p class="text-center text-gray-500">No plans found. Start by adding a new plan.</p>
        <?php endif; ?>
    </main>

    <!-- Footer -->
    <footer class="bg-gray-800 text-white text-center p-4 fixed bottom-0 left-0 w-full">
        &copy; 2024 Kaak Alia Bakery. All rights reserved.
    </footer>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
?>) and this 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) {
    // Fetch the audio_path before deleting
    $audio_path = null;
    if ($user_role === 'admin') {
        $sql = "SELECT audio_path FROM workspace_plans WHERE id = ?";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param("i", $plan_id);
            $stmt->execute();
            $stmt->bind_result($audio_path);
            $stmt->fetch();
            $stmt->close();
        } else {
            // Prepare failed
            header("Location: plans.php?error=Database+error");
            exit();
        }
    } else {
        // Regular user: Verify ownership and fetch audio_path
        $sql = "SELECT audio_path FROM workspace_plans WHERE id = ? AND user_id = ?";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param("ii", $plan_id, $user_id);
            $stmt->execute();
            $stmt->bind_result($audio_path);
            $stmt->fetch();
            $stmt->close();
        } else {
            // Prepare failed
            header("Location: plans.php?error=Database+error");
            exit();
        }
    }

    // Verify that the plan exists
    if (($user_role === 'admin' && ($audio_path !== null || $audio_path === null)) || ($user_role !== 'admin' && $audio_path !== null)) {
        // 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()) {
                // If an audio file was associated, delete it from the server
                if (!empty($audio_path)) {
                    $full_audio_path = __DIR__ . '/../../' . $audio_path;
                    if (file_exists($full_audio_path)) {
                        unlink($full_audio_path);
                    }
                }
                // 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 user does not have permission
        header("Location: plans.php?error=Plan+not+found");
        exit();
    }
} else {
    // Invalid plan ID
    header("Location: plans.php?error=Invalid+plan+ID");
    exit();
}

// Flush the output buffer
ob_end_flush();
?>)  and make style look great and mkae it cool design on audio design