in this codes edit plan (<?php
// /public/workspace/edit_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'
$plan_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$errors = [];
$title = '';
$description = '';
$due_date = '';
$status = 'Not Started';

// Handle GET request to fetch existing plan data
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if ($plan_id > 0) {
        if ($user_role === 'admin') {
            // Admin can edit any plan
            $sql = "SELECT title, description, due_date, status FROM workspace_plans WHERE id = ?";
            if ($stmt = $conn->prepare($sql)) {
                $stmt->bind_param("i", $plan_id);
                $stmt->execute();
                $stmt->bind_result($title, $description, $due_date, $status);
                if (!$stmt->fetch()) {
                    $errors[] = "Plan not found.";
                }
                $stmt->close();
            } else {
                $errors[] = "Database error: Unable to prepare statement.";
            }
        } else {
            // Regular user: Verify ownership
            $sql = "SELECT title, description, due_date, status FROM workspace_plans WHERE id = ? AND user_id = ?";
            if ($stmt = $conn->prepare($sql)) {
                $stmt->bind_param("ii", $plan_id, $user_id);
                $stmt->execute();
                $stmt->bind_result($title, $description, $due_date, $status);
                if (!$stmt->fetch()) {
                    $errors[] = "Plan not found or you do not have permission to edit this plan.";
                }
                $stmt->close();
            } else {
                $errors[] = "Database error: Unable to prepare statement.";
            }
        }
    } else {
        $errors[] = "Invalid plan ID.";
    }
}

// Handle POST request to update the plan
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 ($plan_id > 0) {
        if ($user_role === 'admin') {
            // Admin can update any plan
            // Verify that the plan exists
            $sql_check = "SELECT id FROM workspace_plans WHERE id = ?";
            if ($stmt_check = $conn->prepare($sql_check)) {
                $stmt_check->bind_param("i", $plan_id);
                $stmt_check->execute();
                $stmt_check->store_result();
                if ($stmt_check->num_rows > 0) {
                    $stmt_check->close();
                    // Update the plan
                    $update_sql = "UPDATE workspace_plans SET title = ?, description = ?, due_date = ?, status = ?, updated_at = CURRENT_TIMESTAMP() WHERE id = ?";
                    if ($stmt_update = $conn->prepare($update_sql)) {
                        $stmt_update->bind_param("sssii", $title, $description, $due_date, $status, $plan_id);
                        if ($stmt_update->execute()) {
                            // Success, redirect to view_plan.php with success message
                            header("Location: view_plan.php?id=$plan_id&message=Plan+updated+successfully");
                            exit();
                        } else {
                            $errors[] = "Failed to update plan. Please try again.";
                        }
                        $stmt_update->close();
                    } else {
                        $errors[] = "Database error: Unable to prepare update statement.";
                    }
                } else {
                    $errors[] = "Plan not found or you do not have permission to edit this plan.";
                }
            } else {
                $errors[] = "Database error: Unable to prepare statement.";
            }
        } else {
            // Regular user: Verify ownership
            $sql_check = "SELECT id FROM workspace_plans WHERE id = ? AND user_id = ?";
            if ($stmt_check = $conn->prepare($sql_check)) {
                $stmt_check->bind_param("ii", $plan_id, $user_id);
                $stmt_check->execute();
                $stmt_check->store_result();
                if ($stmt_check->num_rows > 0) {
                    $stmt_check->close();
                    // Update the plan
                    $update_sql = "UPDATE workspace_plans SET title = ?, description = ?, due_date = ?, status = ?, updated_at = CURRENT_TIMESTAMP() WHERE id = ? AND user_id = ?";
                    if ($stmt_update = $conn->prepare($update_sql)) {
                        $stmt_update->bind_param("sssiii", $title, $description, $due_date, $status, $plan_id, $user_id);
                        if ($stmt_update->execute()) {
                            // Success, redirect to view_plan.php with success message
                            header("Location: view_plan.php?id=$plan_id&message=Plan+updated+successfully");
                            exit();
                        } else {
                            $errors[] = "Failed to update plan. Please try again.";
                        }
                        $stmt_update->close();
                    } else {
                        $errors[] = "Database error: Unable to prepare update statement.";
                    }
                } else {
                    $errors[] = "Plan not found or you do not have permission to edit this plan.";
                }
            } else {
                $errors[] = "Database error: Unable to prepare statement.";
            }
        }
    } else {
        $errors[] = "Invalid plan ID.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit 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">Edit 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 Edit Form -->
        <?php if(empty($errors) || $_SERVER['REQUEST_METHOD'] === 'POST'): ?>
            <form action="edit_plan.php?id=<?= htmlspecialchars($plan_id) ?>" 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="<?= htmlspecialchars($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"><?= htmlspecialchars($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="<?= htmlspecialchars($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" <?= ($status === 'Not Started') ? 'selected' : '' ?>>Not Started</option>
                        <option value="In Progress" <?= ($status === 'In Progress') ? 'selected' : '' ?>>In Progress</option>
                        <option value="Completed" <?= ($status === 'Completed') ? 'selected' : '' ?>>Completed</option>
                    </select>
                </div>
                <div class="flex justify-between">
                    <a href="view_plan.php?id=<?= htmlspecialchars($plan_id) ?>" 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">Update Plan</button>
                </div>
            </form>
        <?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();
?>) i want to update it based on this create plan (<?php
// /public/workspace/create_plan.php

// Disable error reporting in production
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

// 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');
    $priority = sanitize_input($_POST['priority'] ?? 'Normal');

    // 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 priority
    $valid_priorities = ['Normal', 'Important', 'Critical'];
    if (!in_array($priority, $valid_priorities)) {
        $errors[] = "Invalid priority 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', 'audio/webm'];
        $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, WAV, and WEBM 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;
            } else {
                $errors[] = "Failed to save the uploaded audio file.";
            }
        }
    }

    // Handle audio recording if admin opted to record
    if ($user_role === 'admin' && $use_audio_recording && !$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_ext = 'webm'; // Assuming webm format from MediaRecorder
            $file_name = uniqid('plan_audio_', true) . '.' . $file_ext;
            $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;
            } else {
                $errors[] = "Failed to save the recorded audio.";
            }
        }
    }

    // Optional: Validate that at least a description or audio is provided
    if (empty($description) && empty($audio_path)) {
        $errors[] = "Either description or audio recording/upload is required.";
    }

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

        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("issssss", $user_id, $title, $description, $audio_path, $due_date, $status, $priority);
            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;
        }
        /* Priority Badge Styles */
        .priority-normal {
            background-color: #3B82F6; /* Blue */
        }
        .priority-important {
            background-color: #F59E0B; /* Yellow */
        }
        .priority-critical {
            background-color: #EF4444; /* Red */
        }
        /* Status Badge Styles */
        .status-completed {
            background-color: #10B981; /* Green */
        }
        .status-in-progress {
            background-color: #FBBF24; /* Amber */
        }
        .status-pending {
            background-color: #EF4444; /* Red */
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex flex-col dark:bg-gray-900">
    <!-- Header -->
    <?php include __DIR__ . '/../../includes/header.php'; ?>

    <!-- Dark Mode Toggle Script -->
    <script>
        // On load, check local storage for theme
        document.addEventListener('DOMContentLoaded', function() {
            if(localStorage.getItem('theme') === 'dark') {
                document.body.classList.add('dark-mode');
                document.getElementById('theme-toggle').checked = true;
            }
        });

        function toggleDarkMode() {
            const toggle = document.getElementById('theme-toggle');
            if(toggle.checked) {
                document.body.classList.add('dark-mode');
                localStorage.setItem('theme', 'dark');
            } else {
                document.body.classList.remove('dark-mode');
                localStorage.setItem('theme', 'light');
            }
        }
    </script>

    <!-- Main Content -->
    <main class="container mx-auto p-6 mt-24 flex-grow mb-16"> <!-- Added mb-16 to prevent overlap with fixed footer -->
        <h1 class="text-3xl 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 dark:bg-gray-800 p-6 rounded-lg shadow-md">
            <div class="mb-4">
                <label class="block text-gray-700 dark:text-gray-200">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-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200" required value="<?= isset($_POST['title']) ? htmlspecialchars($_POST['title']) : '' ?>">
            </div>
            <div class="mb-4">
                <label class="block text-gray-700 dark:text-gray-200">Description</label>
                <textarea name="description" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200" 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 dark:text-gray-200">Audio Option</label>
                    <div class="flex items-center space-x-4 mt-2">
                        <div class="flex items-center">
                            <input type="radio" id="audio_option_none" name="audio_option" value="none" checked class="form-radio h-4 w-4 text-blue-600" onchange="toggleAudioOptions('none')">
                            <label for="audio_option_none" class="ml-2 text-gray-700 dark:text-gray-200">None</label>
                        </div>

                        <div class="flex items-center">
                            <input type="radio" id="audio_option_upload" name="audio_option" value="upload" class="form-radio h-4 w-4 text-blue-600" onchange="toggleAudioOptions('upload')">
                            <label for="audio_option_upload" class="ml-2 text-gray-700 dark:text-gray-200">Upload Audio File</label>
                        </div>

                        <div class="flex items-center">
                            <input type="radio" id="audio_option_record" name="audio_option" value="record" class="form-radio h-4 w-4 text-blue-600" onchange="toggleAudioOptions('record')">
                            <label for="audio_option_record" class="ml-2 text-gray-700 dark:text-gray-200">Record Audio</label>
                        </div>
                    </div>
                </div>

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

                <!-- Audio Recorder Section -->
                <div class="mb-4 hidden" id="audio_recorder_section">
                    <label class="block text-gray-700 dark:text-gray-200">Record Audio</label>
                    <div class="flex space-x-2 mt-2">
                        <button type="button" id="start_recording" class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 flex items-center">
                            <i class="bi bi-play-fill mr-2"></i> Start Recording
                        </button>
                        <button type="button" id="stop_recording" class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 flex items-center hidden">
                            <i class="bi bi-stop-fill mr-2"></i> Stop Recording
                        </button>
                    </div>
                    <div id="recording_indicator" class="text-red-500 mt-2 hidden">Recording...</div>
                    <audio id="recorded_audio" class="mt-4 w-full" controls></audio>
                    <input type="hidden" name="audio_data" id="audio_data">
                </div>
            <?php endif; ?>

            <div class="mb-4">
                <label class="block text-gray-700 dark:text-gray-200">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-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200" 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 dark:text-gray-200">Status</label>
                <select name="status" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200">
                    <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>

            <!-- Priority Field -->
            <div class="mb-4">
                <label class="block text-gray-700 dark:text-gray-200">Priority</label>
                <select name="priority" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200">
                    <option value="Normal" <?= (isset($_POST['priority']) && $_POST['priority'] == 'Normal') ? 'selected' : '' ?>>Normal</option>
                    <option value="Important" <?= (isset($_POST['priority']) && $_POST['priority'] == 'Important') ? 'selected' : '' ?>>Important</option>
                    <option value="Critical" <?= (isset($_POST['priority']) && $_POST['priority'] == 'Critical') ? 'selected' : '' ?>>Critical</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 fixed bottom-0 left-0 w-full">
        &copy; 2024 Kaak Alia Bakery. All rights reserved.
    </footer>

    <!-- JavaScript for Audio Recording and Enhanced UI -->
    <?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.classList.remove('hidden');
                        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.classList.add('hidden');
                            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();
?>) so type full codes of edit plan