-- 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;
Assistant
--
-- 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;
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);
// 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();
}
userid=_SESSION['user_id'];
userrole=_SESSION['role']; // 'admin' or 'staff'
$errors = [];
// Pre-fill due_date if passed via GET (e.g., from calendar selection)
prefillduedate=sanitizeinput(_GET['due_date'] ?? '');
if (_SERVER['REQUEST_METHOD'] == 'POST') {
title = sanitize_input(POST[′title′]??′′);description = sanitize_input(POST[′descriptiondue_date = sanitize_input(POST[′duedstatus = 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);
}
}
}
// 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();
}
userid=_SESSION['user_id'];
userrole=_SESSION['role']; // 'admin' or 'staff'
// Get plan ID from GET parameter
planid=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−>bindparam("i",plan_id);
stmt−>execute();result = stmt−>getresult();plan = result−>fetchassoc();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−>bindparam("ii",plan_id, userid);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();
}
}
// 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();
}
userid=_SESSION['user_id'];
userrole=_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−>getresult();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
}
?>
// 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
userid=_SESSION['user_id'];
userrole=_SESSION['role']; // 'admin' or 'staff'
// Get plan ID from GET parameter
planid=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−>bindparam("i",plan_id);
stmt−>execute();stmt->bind_result(audiopath);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−>bindparam("ii",plan_id, userid);stmt->execute();
stmt−>bindresult(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
To enhance your workspace planning system by allowing users to save both descriptions and audio recordings/uploads simultaneously and improve the aesthetic appearance of the audio components, follow the comprehensive steps below. This includes modifying your create_plan.php, view_plan.php, plans.php, and delete_plan.php files, as well as updating your database and ensuring a polished UI for audio interactions.
1. Database Adjustments
Before modifying the PHP files, ensure that your database can accommodate both description and audio_path simultaneously without forcing one to be NULL when the other is present.
Note: This structure already supports both description and audio_path being NULL or non-NULL. Ensure that your application logic allows both fields to be populated independently.
2. Modifying create_plan.php
Objectives:
Allow users (especially admins) to input both a textual description and an audio file (either uploaded or recorded).
Ensure that both are saved to the database without nullifying either field.
Update validation rules to accommodate both inputs.
Improved the table styling for better readability.
Used color-coded badges for status for quick recognition.
Conditional Content Display:
Enhanced logic to display different indicators based on whether a plan has a description, audio, both, or neither.
5. Modifying delete_plan.php
Objectives:
Ensure that when a plan is deleted, both the description and audio (if any) are properly handled.
No additional changes needed since description is stored as text and audio_path is already being deleted. However, you can add confirmation or additional checks if necessary.
Updated delete_plan.php
<?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();
?>
Key Points:
No Additional Changes Needed for Description:
Since description is text-based and stored in the database, deleting it only involves removing the database row. The audio file is already handled by deleting the associated file from the server.
Ensuring Audio File Deletion:
The script ensures that if an audio_path exists, the corresponding file is deleted from the server to prevent orphan files.
6. Additional Enhancements for UI/UX
To make the audio recording/upload experience more intuitive and visually appealing, consider the following UI enhancements:
a. Improved Audio Recording Interface
Enhance the audio recorder in create_plan.php by providing better visual feedback and controls.
Use more stylish confirmation dialogs instead of default browser alerts for better aesthetics.
You can integrate a modal library like Flowbite or use Tailwind CSS to create custom modals. Here's a basic example using Tailwind:
<!-- Add before closing </body> tag in your HTML -->
<!-- Confirmation Modal -->
<div id="confirmModal" class="fixed inset-0 bg-gray-800 bg-opacity-50 flex items-center justify-center hidden">
<div class="bg-white rounded-lg p-6 w-96">
<h2 class="text-xl font-bold mb-4">Confirm Deletion</h2>
<p class="mb-4">Are you sure you want to delete this plan? This action cannot be undone.</p>
<div class="flex justify-end space-x-2">
<button id="cancelDelete" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">Cancel</button>
<a id="confirmDelete" href="#" class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600">Delete</a>
</div>
</div>
</div>
<script>
// Handle custom confirmation for deletion
document.querySelectorAll('a.text-red-500[href^="delete_plan.php"]').forEach(function(el) {
el.addEventListener('click', function(e) {
e.preventDefault();
var planId = this.getAttribute('href').split('=')[1];
document.getElementById('confirmDelete').setAttribute('href', 'delete_plan.php?id=' + planId);
document.getElementById('confirmModal').classList.remove('hidden');
});
});
document.getElementById('cancelDelete').addEventListener('click', function() {
document.getElementById('confirmModal').classList.add('hidden');
});
</script>
Note: This replaces the default confirm() dialog with a custom modal, enhancing the user experience.
7. Final Touches
Consistent Styling: Ensure that all forms, buttons, and elements across different pages maintain a consistent styling language, leveraging Tailwind CSS utility classes.
Accessibility: Incorporate accessibility best practices, such as using appropriate ARIA labels for screen readers, ensuring color contrasts are adequate, and making interactive elements keyboard-navigable.
Responsive Design: Test the application across different devices (mobile, tablet, desktop) to ensure responsiveness and usability.
Optimize Audio Files: Consider implementing server-side checks to optimize and secure audio uploads, preventing malicious files from being uploaded.
8. Testing Your Changes
After implementing the above changes, thoroughly test the application:
Create Plans:
With only a description.
With only an audio upload.
With only an audio recording.
With both a description and an audio file.
View Plans:
Ensure both description and audio are displayed correctly.
Test audio playback across different browsers.
Edit Plans:
Modify descriptions and/or replace audio files.
Delete Plans:
Confirm that both textual and audio data are appropriately removed.
UI/UX:
Verify that all UI elements appear correctly and are responsive.
Test custom confirmation dialogs.
Security:
Ensure that file uploads are secure, preventing unauthorized file types.
Validate that users cannot access or manipulate plans they do not own (for non-admin users).
By following these steps, your workspace planning system will be more flexible, allowing users to provide richer information through both text and audio, while also offering an improved user interface that enhances overall user experience.