based on this codes (Certainly! Below is a comprehensive guide to building your PHP-based web application for Advanced Health Solutions (Longeva). This guide includes full code snippets for each part of the application, organized according to your specified folder structure. The application focuses on internal collaboration, enabling effective team management, task handling, document sharing, and communication.

1. Folder Structure Overview
Here's the directory structure we'll be following:


/app.longevacare.com
├── index.php
├── login.php
├── register.php
├── dashboard.php
├── employees/
│   ├── add_employee.php
│   ├── manage_employees.php
│   └── edit_employee.php
├── tasks/
│   ├── add_task.php
│   ├── manage_tasks.php
│   └── edit_task.php
├── documents/
│   ├── upload_document.php
│   ├── manage_documents.php
│   └── view_document.php
├── chat/
│   ├── chat.php
│   └── send_message.php
├── includes/
│   ├── db_connect.php
│   ├── header.php
│   ├── footer.php
│   └── functions.php
├── assets/
│   ├── css/
│   │   └── styles.css
│   ├── js/
│   │   └── scripts.js
│   └── uploads/
│       └── profile_pictures/
└── .htaccess
2. Setting Up the Database
First, create a MySQL database named longevacare_app. Then, execute the following SQL scripts to create the necessary tables.

A. users Table

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    phone VARCHAR(15),
    department VARCHAR(100),
    date_of_joining DATE,
    status ENUM('active', 'inactive') DEFAULT 'active',
    role ENUM('admin', 'manager', 'staff', 'receptionist') DEFAULT 'staff',
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    profile_picture VARCHAR(255) DEFAULT 'default_profile.png',
    specialization VARCHAR(100),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
B. tasks Table

CREATE TABLE tasks (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    description TEXT,
    assigned_to INT,
    status ENUM('To Do', 'In Progress', 'Completed') DEFAULT 'To Do',
    due_date DATE,
    created_by INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (assigned_to) REFERENCES users(id) ON DELETE SET NULL,
    FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
);
C. messages Table

CREATE TABLE messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    sender_id INT NOT NULL,
    receiver_id INT,
    message TEXT NOT NULL,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (sender_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (receiver_id) REFERENCES users(id) ON DELETE CASCADE
);
D. documents Table

CREATE TABLE documents (
    id INT AUTO_INCREMENT PRIMARY KEY,
    file_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(255) NOT NULL,
    uploaded_by INT,
    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    category VARCHAR(100),
    FOREIGN KEY (uploaded_by) REFERENCES users(id) ON DELETE SET NULL
);
3. Core Files and Their Implementations
A. includes/db_connect.php
Handles the database connection using PDO.


<?php
// includes/db_connect.php

$host = 'localhost';
$db   = 'longevacare_app';
$user = 'your_db_username'; // Replace with your DB username
$pass = 'your_db_password'; // Replace with your DB password
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
     die("Database connection failed: " . $e->getMessage());
}
?>
Make sure to replace your_db_username and your_db_password with your actual database credentials.

B. includes/functions.php
Contains utility functions for authentication and access control.


<?php
// includes/functions.php

// Check if user is logged in
function is_logged_in() {
    return isset($_SESSION['user_id']);
}

// Redirect to login if not authenticated
function ensure_logged_in() {
    if (!is_logged_in()) {
        header("Location: login.php");
        exit();
    }
}

// Check if user has a specific role
function has_role($role) {
    return isset($_SESSION['role']) && $_SESSION['role'] === $role;
}

// Redirect if user does not have required role
function ensure_role($role) {
    if (!has_role($role)) {
        header("Location: dashboard.php?error=Access denied.");
        exit();
    }
}
?>
C. includes/header.php
Shared header with navigation links.


<?php
// includes/header.php
session_start();
require_once 'db_connect.php';
require_once 'functions.php';

// Define the base URL
$base_url = "https://longevacare.com/app"; // Change to your actual base URL

// Define subdomain
$subdomain = "app.longevacare.com";

// Redirect to login if not authenticated and not on login or register page
$public_pages = ['login.php', 'register.php'];
$current_page = basename($_SERVER['PHP_SELF']);

if (!is_logged_in() && !in_array($current_page, $public_pages)) {
    header("Location: login.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Longeva Dashboard</title>
    <link rel="stylesheet" href="/assets/css/styles.css">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" rel="stylesheet">
</head>
<body>
    <?php if (is_logged_in()): ?>
    <header class="header">
        <h2>Longeva Dashboard</h2>
        <nav>
            <a href="/dashboard.php">Dashboard</a>
            <a href="/employees/manage_employees.php">Employees</a>
            <a href="/tasks/manage_tasks.php">Tasks</a>
            <a href="/documents/manage_documents.php">Documents</a>
            <a href="/chat/chat.php">Chat</a>
            <a href="/logout.php">Logout</a>
        </nav>
    </header>
    <?php endif; ?>
    <main class="container">
D. includes/footer.php
Shared footer section.


<?php
// includes/footer.php
?>
    </main>
    <?php if (is_logged_in()): ?>
    <footer class="footer">
        <p>&copy; <?= date("Y"); ?> Longeva Care. All rights reserved.</p>
    </footer>
    <?php endif; ?>
    <script src="/assets/js/scripts.js"></script>
</body>
</html>
E. assets/css/styles.css
Your provided CSS, enhanced for better compatibility.


/* assets/css/styles.css */

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap');

:root {
    --primary-color: #4F3F02;
    --secondary-color: #D1C287;
    --background-color: #f9f9f9;
    --text-color: #333;
    --error-color: #dc3545;
    --success-color: #28a745;
}

body {
    font-family: 'Roboto', sans-serif;
    background-color: var(--background-color);
    color: var(--text-color);
    margin: 0;
    padding: 0;
}

.header {
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
    color: white;
    padding: 20px;
    text-align: center;
    border-bottom: 2px solid var(--primary-color);
}

.header h2 {
    margin: 0;
    font-size: 32px;
    font-weight: 700;
}

.header nav {
    margin-top: 10px;
}

.header nav a {
    color: white;
    text-decoration: none;
    margin: 0 15px;
    font-weight: 500;
}

.header nav a:hover {
    text-decoration: underline;
}

.container {
    max-width: 900px;
    margin: 40px auto;
    padding: 20px;
    background-color: white;
    border-radius: 20px;
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

.footer {
    text-align: center;
    padding: 20px;
    background-color: var(--secondary-color);
    color: var(--primary-color);
    position: fixed;
    width: 100%;
    bottom: 0;
}

.form-group {
    margin-bottom: 20px;
}

label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: var(--primary-color);
}

input[type="text"], input[type="email"], input[type="password"], input[type="date"], select, textarea {
    width: 100%;
    padding: 12px;
    border-radius: 8px;
    border: 1px solid #ccc;
    box-sizing: border-box;
    font-size: 16px;
}

textarea {
    resize: vertical;
}

.error, .success {
    padding: 10px;
    margin-bottom: 20px;
    border-radius: 5px;
}

.error {
    background-color: #f8d7da;
    color: var(--error-color);
}

.success {
    background-color: #d4edda;
    color: var(--success-color);
}

.actions {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 20px;
}

.actions a, .actions button {
    background-color: var(--primary-color);
    color: white;
    padding: 10px 20px;
    text-decoration: none;
    border: none;
    border-radius: 30px;
    font-weight: 700;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.actions a:hover, .actions button:hover {
    background-color: var(--secondary-color);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
}

table, th, td {
    border: 1px solid #ddd;
}

th, td {
    padding: 12px;
    text-align: left;
}

th {
    background-color: var(--secondary-color);
    color: var(--primary-color);
}

tr:nth-child(even) {
    background-color: #f2f2f2;
}

@media (max-width: 600px) {
    .actions {
        flex-direction: column;
    }

    .footer {
        position: static;
    }

    table, th, td {
        font-size: 14px;
    }
}
F. login.php
User login page.


<?php
// login.php
require_once 'includes/db_connect.php';
include 'includes/header.php';

$username = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Collect and sanitize form data
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    // Validation
    if (empty($username)) {
        $errors[] = 'Username is required.';
    }
    if (empty($password)) {
        $errors[] = 'Password is required.';
    }

    if (empty($errors)) {
        // Fetch user from database
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            // Set session variables
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];

            // Redirect to dashboard
            header("Location: dashboard.php");
            exit();
        } else {
            $errors[] = 'Invalid username or password.';
        }
    }
}
?>

<h2>Login to Longeva Dashboard</h2>

<?php if (!empty($errors)): ?>
    <div class="error">
        <ul>
        <?php foreach ($errors as $error): ?>
            <li><?= htmlspecialchars($error) ?></li>
        <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<form action="login.php" method="post">
    <div class="form-group">
        <label for="username">Username<span class="text-danger">*</span></label>
        <input type="text" name="username" value="<?= htmlspecialchars($username) ?>" required>
    </div>
    <div class="form-group">
        <label for="password">Password<span class="text-danger">*</span></label>
        <input type="password" name="password" required>
    </div>
    <div class="actions">
        <button type="submit">Login</button>
        <a href="register.php">Register</a>
    </div>
</form>

<?php include 'includes/footer.php'; ?>
G. register.php
User registration page.


<?php
// register.php
require_once 'includes/db_connect.php';
include 'includes/header.php';

$name = $email = $phone = $department = $date_of_joining = $status = $role = $username = '';
$specialization = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Collect and sanitize form data
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $department = trim($_POST['department']);
    $date_of_joining = $_POST['date_of_joining'];
    $status = $_POST['status'] ?? 'active';
    $role = $_POST['role'];
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $specialization = trim($_POST['specialization']);

    // Validation
    if (empty($name)) $errors[] = 'Name is required.';
    if (empty($email)) $errors[] = 'Email is required.';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Invalid email format.';
    if (empty($username)) $errors[] = 'Username is required.';
    if (empty($password)) $errors[] = 'Password is required.';
    if ($password !== $confirm_password) $errors[] = 'Passwords do not match.';
    if (empty($specialization)) $errors[] = 'Specialization is required.';
    if (empty($role)) $errors[] = 'Role is required.';

    // Check for existing username or email
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ? OR email = ?");
    $stmt->execute([$username, $email]);
    if ($stmt->fetchColumn() > 0) {
        $errors[] = 'Username or email already exists.';
    }

    // Profile picture handling (optional)
    $profile_picture = 'default_profile.png';
    if (!empty($_FILES['profile_picture']['name'])) {
        $target_dir = "assets/uploads/profile_pictures/";
        $imageFileType = strtolower(pathinfo($_FILES["profile_picture"]["name"], PATHINFO_EXTENSION));
        $new_file_name = $username . '_' . time() . '.' . $imageFileType;
        $target_file = $target_dir . $new_file_name;
        $uploadOk = 1;

        // Check if image
        $check = getimagesize($_FILES["profile_picture"]["tmp_name"]);
        if ($check === false) {
            $errors[] = "File is not an image.";
            $uploadOk = 0;
        }

        // Check file size (max 2MB)
        if ($_FILES["profile_picture"]["size"] > 2000000) {
            $errors[] = "File is too large.";
            $uploadOk = 0;
        }

        // Allow only specific formats
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        if (!in_array($imageFileType, $allowed_types)) {
            $errors[] = "Only JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }

        // Move file if no errors
        if ($uploadOk) {
            if (move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $target_file)) {
                $profile_picture = $new_file_name;
            } else {
                $errors[] = "Error uploading the file.";
            }
        }
    }

    if (empty($errors)) {
        // Hash password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        // Insert into database
        try {
            $stmt = $pdo->prepare("INSERT INTO users (name, role, email, phone, department, date_of_joining, status, username, password, profile_picture, specialization) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $role, $email, $phone, $department, $date_of_joining, $status, $username, $hashed_password, $profile_picture, $specialization]);
            $success = "Registration successful. You can now <a href='login.php'>login</a>.";
            // Optionally, send a notification or email
        } catch (Exception $e) {
            $errors[] = "Error: " . $e->getMessage();
        }
    }
}
?>

<h2>Register New Account</h2>

<?php if (!empty($errors)): ?>
    <div class="error">
        <ul>
        <?php foreach ($errors as $error): ?>
            <li><?= htmlspecialchars($error) ?></li>
        <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (!empty($success)): ?>
    <div class="success">
        <?= $success ?>
    </div>
<?php endif; ?>

<form action="register.php" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="name">Full Name<span class="text-danger">*</span></label>
        <input type="text" name="name" value="<?= htmlspecialchars($name) ?>" required>
    </div>
    <div class="form-group">
        <label for="role">Role<span class="text-danger">*</span></label>
        <select name="role" required>
            <option value="">Select Role</option>
            <option value="admin" <?= $role == 'admin' ? 'selected' : '' ?>>Admin</option>
            <option value="manager" <?= $role == 'manager' ? 'selected' : '' ?>>Manager</option>
            <option value="staff" <?= $role == 'staff' ? 'selected' : '' ?>>Staff</option>
            <option value="receptionist" <?= $role == 'receptionist' ? 'selected' : '' ?>>Receptionist</option>
        </select>
    </div>
    <div class="form-group">
        <label for="specialization">Specialization<span class="text-danger">*</span></label>
        <input type="text" name="specialization" value="<?= htmlspecialchars($specialization) ?>" required>
    </div>
    <div class="form-group">
        <label for="email">Email<span class="text-danger">*</span></label>
        <input type="email" name="email" value="<?= htmlspecialchars($email) ?>" required>
    </div>
    <div class="form-group">
        <label for="phone">Phone</label>
        <input type="text" name="phone" value="<?= htmlspecialchars($phone) ?>">
    </div>
    <div class="form-group">
        <label for="department">Department</label>
        <input type="text" name="department" value="<?= htmlspecialchars($department) ?>">
    </div>
    <div class="form-group">
        <label for="date_of_joining">Date of Joining</label>
        <input type="date" name="date_of_joining" value="<?= htmlspecialchars($date_of_joining) ?>">
    </div>
    <div class="form-group">
        <label for="status">Status</label>
        <select name="status">
            <option value="active" <?= $status == 'active' ? 'selected' : '' ?>>Active</option>
            <option value="inactive" <?= $status == 'inactive' ? 'selected' : '' ?>>Inactive</option>
        </select>
    </div>
    <div class="form-group">
        <label for="profile_picture">Profile Picture</label>
        <input type="file" name="profile_picture" accept="image/*">
    </div>
    <h3>Login Details</h3>
    <div class="form-group">
        <label for="username">Username<span class="text-danger">*</span></label>
        <input type="text" name="username" value="<?= htmlspecialchars($username) ?>" required>
    </div>
    <div class="form-group">
        <label for="password">Password<span class="text-danger">*</span></label>
        <input type="password" name="password" required>
    </div>
    <div class="form-group">
        <label for="confirm_password">Confirm Password<span class="text-danger">*</span></label>
        <input type="password" name="confirm_password" required>
    </div>
    <div class="actions">
        <button type="submit">Register</button>
        <a href="login.php">Cancel</a>
    </div>
</form>

<?php include 'includes/footer.php'; ?>
H. logout.php
Handles user logout.


<?php
// logout.php
session_start();
session_unset();
session_destroy();
header("Location: login.php");
exit();
?>
I. dashboard.php
User dashboard displaying welcome message and tasks.


<?php
// dashboard.php
include 'includes/header.php';
require_once 'includes/db_connect.php';

// Fetch user information
$user_id = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Fetch tasks assigned to the user
$stmt = $pdo->prepare("SELECT tasks.*, users.name as assigned_name FROM tasks JOIN users ON tasks.assigned_to = users.id WHERE tasks.assigned_to = ?");
$stmt->execute([$user_id]);
$tasks = $stmt->fetchAll();
?>

<h2>Welcome, <?= htmlspecialchars($user['name']) ?>!</h2>

<section>
    <h3>Your Tasks</h3>
    <?php if (empty($tasks)): ?>
        <p>No tasks assigned.</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Status</th>
                    <th>Due Date</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($tasks as $task): ?>
                    <tr>
                        <td><?= htmlspecialchars($task['title']) ?></td>
                        <td><?= htmlspecialchars($task['status']) ?></td>
                        <td><?= htmlspecialchars($task['due_date']) ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</section>

<?php include 'includes/footer.php'; ?>
J. employees/add_employee.php
Add a new employee (admin only).


<?php
// employees/add_employee.php
include '../includes/header.php';
require_once '../includes/db_connect.php';
require_once '../includes/functions.php';

// Ensure the user is an admin
ensure_role('admin');

$name = $email = $phone = $department = $date_of_joining = $status = $role = $username = '';
$specialization = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Collect and sanitize form data
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $department = trim($_POST['department']);
    $date_of_joining = $_POST['date_of_joining'];
    $status = $_POST['status'] ?? 'active';
    $role = $_POST['role'];
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $specialization = trim($_POST['specialization']);

    // Validation
    if (empty($name)) $errors[] = 'Name is required.';
    if (empty($email)) $errors[] = 'Email is required.';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Invalid email format.';
    if (empty($username)) $errors[] = 'Username is required.';
    if (empty($password)) $errors[] = 'Password is required.';
    if ($password !== $confirm_password) $errors[] = 'Passwords do not match.';
    if (empty($specialization)) $errors[] = 'Specialization is required.';
    if (empty($role)) $errors[] = 'Role is required.';

    // Check for existing username or email
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ? OR email = ?");
    $stmt->execute([$username, $email]);
    if ($stmt->fetchColumn() > 0) {
        $errors[] = 'Username or email already exists.';
    }

    // Profile picture handling (optional)
    $profile_picture = 'default_profile.png';
    if (!empty($_FILES['profile_picture']['name'])) {
        $target_dir = "../assets/uploads/profile_pictures/";
        $imageFileType = strtolower(pathinfo($_FILES["profile_picture"]["name"], PATHINFO_EXTENSION));
        $new_file_name = $username . '_' . time() . '.' . $imageFileType;
        $target_file = $target_dir . $new_file_name;
        $uploadOk = 1;

        // Check if image
        $check = getimagesize($_FILES["profile_picture"]["tmp_name"]);
        if ($check === false) {
            $errors[] = "File is not an image.";
            $uploadOk = 0;
        }

        // Check file size (max 2MB)
        if ($_FILES["profile_picture"]["size"] > 2000000) {
            $errors[] = "File is too large.";
            $uploadOk = 0;
        }

        // Allow only specific formats
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        if (!in_array($imageFileType, $allowed_types)) {
            $errors[] = "Only JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }

        // Move file if no errors
        if ($uploadOk) {
            if (move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $target_file)) {
                $profile_picture = $new_file_name;
            } else {
                $errors[] = "Error uploading the file.";
            }
        }
    }

    if (empty($errors)) {
        // Hash password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        // Insert into database
        try {
            $stmt = $pdo->prepare("INSERT INTO users (name, role, email, phone, department, date_of_joining, status, username, password, profile_picture, specialization) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $role, $email, $phone, $department, $date_of_joining, $status, $username, $hashed_password, $profile_picture, $specialization]);
            $success = "Employee added successfully.";
            // Reset form fields
            $name = $email = $phone = $department = $date_of_joining = $status = $role = $username = '';
            $specialization = '';
        } catch (Exception $e) {
            $errors[] = "Error: " . $e->getMessage();
        }
    }
}
?>

<h2>Add New Employee</h2>

<?php if (!empty($errors)): ?>
    <div class="error">
        <ul>
        <?php foreach ($errors as $error): ?>
            <li><?= htmlspecialchars($error) ?></li>
        <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (!empty($success)): ?>
    <div class="success">
        <?= $success ?>
    </div>
<?php endif; ?>

<form action="add_employee.php" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="name">Full Name<span class="text-danger">*</span></label>
        <input type="text" name="name" value="<?= htmlspecialchars($name) ?>" required>
    </div>
    <div class="form-group">
        <label for="role">Role<span class="text-danger">*</span></label>
        <select name="role" required>
            <option value="">Select Role</option>
            <option value="admin" <?= $role == 'admin' ? 'selected' : '' ?>>Admin</option>
            <option value="manager" <?= $role == 'manager' ? 'selected' : '' ?>>Manager</option>
            <option value="staff" <?= $role == 'staff' ? 'selected' : '' ?>>Staff</option>
            <option value="receptionist" <?= $role == 'receptionist' ? 'selected' : '' ?>>Receptionist</option>
        </select>
    </div>
    <div class="form-group">
        <label for="specialization">Specialization<span class="text-danger">*</span></label>
        <input type="text" name="specialization" value="<?= htmlspecialchars($specialization) ?>" required>
    </div>
    <div class="form-group">
        <label for="email">Email<span class="text-danger">*</span></label>
        <input type="email" name="email" value="<?= htmlspecialchars($email) ?>" required>
    </div>
    <div class="form-group">
        <label for="phone">Phone</label>
        <input type="text" name="phone" value="<?= htmlspecialchars($phone) ?>">
    </div>
    <div class="form-group">
        <label for="department">Department</label>
        <input type="text" name="department" value="<?= htmlspecialchars($department) ?>">
    </div>
    <div class="form-group">
        <label for="date_of_joining">Date of Joining</label>
        <input type="date" name="date_of_joining" value="<?= htmlspecialchars($date_of_joining) ?>">
    </div>
    <div class="form-group">
        <label for="status">Status</label>
        <select name="status">
            <option value="active" <?= $status == 'active' ? 'selected' : '' ?>>Active</option>
            <option value="inactive" <?= $status == 'inactive' ? 'selected' : '' ?>>Inactive</option>
        </select>
    </div>
    <div class="form-group">
        <label for="profile_picture">Profile Picture</label>
        <input type="file" name="profile_picture" accept="image/*">
    </div>
    <h3>Login Details</h3>
    <div class="form-group">
        <label for="username">Username<span class="text-danger">*</span></label>
        <input type="text" name="username" value="<?= htmlspecialchars($username) ?>" required>
    </div>
    <div class="form-group">
        <label for="password">Password<span class="text-danger">*</span></label>
        <input type="password" name="password" required>
    </div>
    <div class="form-group">
        <label for="confirm_password">Confirm Password<span class="text-danger">*</span></label>
        <input type="password" name="confirm_password" required>
    </div>
    <div class="actions">
        <button type="submit">Add Employee</button>
        <a href="manage_employees.php">Cancel</a>
    </div>
</form>

<?php include '../includes/footer.php'; ?>
K. employees/manage_employees.php
Manage (view, edit, delete) employees (admin only).


<?php
// employees/manage_employees.php
include '../includes/header.php';
require_once '../includes/db_connect.php';
require_once '../includes/functions.php';

// Ensure the user is an admin
ensure_role('admin');

// Handle deletion if requested
if (isset($_GET['delete'])) {
    $delete_id = intval($_GET['delete']);
    // Prevent admin from deleting themselves
    if ($delete_id == $_SESSION['user_id']) {
        $error = "You cannot delete your own account.";
    } else {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        if ($stmt->execute([$delete_id])) {
            $success = "Employee deleted successfully.";
        } else {
            $error = "Failed to delete employee.";
        }
    }
}

// Fetch all employees
$stmt = $pdo->query("SELECT * FROM users");
$employees = $stmt->fetchAll();
?>

<h2>Manage Employees</h2>

<div class="actions">
    <a href="add_employee.php">Add New Employee</a>
</div>

<?php if (isset($error)): ?>
    <div class="error">
        <?= htmlspecialchars($error) ?>
    </div>
<?php endif; ?>

<?php if (isset($success)): ?>
    <div class="success">
        <?= htmlspecialchars($success) ?>
    </div>
<?php endif; ?>

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Role</th>
            <th>Email</th>
            <th>Department</th>
            <th>Status</th>
            <th>Specialization</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($employees as $emp): ?>
        <tr>
            <td><?= htmlspecialchars($emp['name']) ?></td>
            <td><?= htmlspecialchars(ucfirst($emp['role'])) ?></td>
            <td><?= htmlspecialchars($emp['email']) ?></td>
            <td><?= htmlspecialchars($emp['department']) ?></td>
            <td><?= htmlspecialchars(ucfirst($emp['status'])) ?></td>
            <td><?= htmlspecialchars($emp['specialization']) ?></td>
            <td>
                <a href="edit_employee.php?id=<?= $emp['id'] ?>">Edit</a> |
                <?php if ($emp['id'] != $_SESSION['user_id']): ?>
                    <a href="manage_employees.php?delete=<?= $emp['id'] ?>" onclick="return confirm('Are you sure you want to delete this employee?');">Delete</a>
                <?php else: ?>
                    <span style="color: gray;">Delete</span>
                <?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<?php include '../includes/footer.php'; ?>
L. employees/edit_employee.php
Edit employee details (admin only).


<?php
// employees/edit_employee.php
include '../includes/header.php';
require_once '../includes/db_connect.php';
require_once '../includes/functions.php';

// Ensure the user is an admin
ensure_role('admin');

// Get employee ID from URL
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: manage_employees.php?error=Invalid employee ID.");
    exit();
}
$employee_id = intval($_GET['id']);

// Fetch employee data
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$employee_id]);
$employee = $stmt->fetch();

if (!$employee) {
    header("Location: manage_employees.php?error=Employee not found.");
    exit();
}

$name = $employee['name'];
$email = $employee['email'];
$phone = $employee['phone'];
$department = $employee['department'];
$date_of_joining = $employee['date_of_joining'];
$status = $employee['status'];
$role = $employee['role'];
$username = $employee['username'];
$specialization = $employee['specialization'];
$profile_picture = $employee['profile_picture'];
$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Collect and sanitize form data
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $department = trim($_POST['department']);
    $date_of_joining = $_POST['date_of_joining'];
    $status = $_POST['status'] ?? 'active';
    $role = $_POST['role'];
    $username = trim($_POST['username']);
    $specialization = trim($_POST['specialization']);

    // Validation
    if (empty($name)) $errors[] = 'Name is required.';
    if (empty($email)) $errors[] = 'Email is required.';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Invalid email format.';
    if (empty($username)) $errors[] = 'Username is required.';
    if (empty($specialization)) $errors[] = 'Specialization is required.';
    if (empty($role)) $errors[] = 'Role is required.';

    // Check for existing username or email excluding current employee
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE (username = ? OR email = ?) AND id != ?");
    $stmt->execute([$username, $email, $employee_id]);
    if ($stmt->fetchColumn() > 0) {
        $errors[] = 'Username or email already exists.';
    }

    // Profile picture handling (optional)
    if (!empty($_FILES['profile_picture']['name'])) {
        $target_dir = "../assets/uploads/profile_pictures/";
        $imageFileType = strtolower(pathinfo($_FILES["profile_picture"]["name"], PATHINFO_EXTENSION));
        $new_file_name = $username . '_' . time() . '.' . $imageFileType;
        $target_file = $target_dir . $new_file_name;
        $uploadOk = 1;

        // Check if image
        $check = getimagesize($_FILES["profile_picture"]["tmp_name"]);
        if ($check === false) {
            $errors[] = "File is not an image.";
            $uploadOk = 0;
        }

        // Check file size (max 2MB)
        if ($_FILES["profile_picture"]["size"] > 2000000) {
            $errors[] = "File is too large.";
            $uploadOk = 0;
        }

        // Allow only specific formats
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        if (!in_array($imageFileType, $allowed_types)) {
            $errors[] = "Only JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }

        // Move file if no errors
        if ($uploadOk) {
            if (move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $target_file)) {
                // Optionally delete old profile picture if not default
                if ($profile_picture != 'default_profile.png' && file_exists("../assets/uploads/profile_pictures/$profile_picture")) {
                    unlink("../assets/uploads/profile_pictures/$profile_picture");
                }
                $profile_picture = $new_file_name;
            } else {
                $errors[] = "Error uploading the file.";
            }
        }
    }

    if (empty($errors)) {
        // Update database
        try {
            $stmt = $pdo->prepare("UPDATE users SET name = ?, role = ?, email = ?, phone = ?, department = ?, date_of_joining = ?, status = ?, username = ?, profile_picture = ?, specialization = ? WHERE id = ?");
            $stmt->execute([$name, $role, $email, $phone, $department, $date_of_joining, $status, $username, $profile_picture, $specialization, $employee_id]);
            $success = "Employee updated successfully.";
        } catch (Exception $e) {
            $errors[] = "Error: " . $e->getMessage();
        }
    }
}
?>

<h2>Edit Employee</h2>

<?php if (!empty($errors)): ?>
    <div class="error">
        <ul>
        <?php foreach ($errors as $error): ?>
            <li><?= htmlspecialchars($error) ?></li>
        <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (isset($success)): ?>
    <div class="success">
        <?= htmlspecialchars($success) ?>
    </div>
<?php endif; ?>

<form action="edit_employee.php?id=<?= $employee_id ?>" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="name">Full Name<span class="text-danger">*</span></label>
        <input type="text" name="name" value="<?= htmlspecialchars($name) ?>" required>
    </div>
    <div class="form-group">
        <label for="role">Role<span class="text-danger">*</span></label>
        <select name="role" required>
            <option value="">Select Role</option>
            <option value="admin" <?= $role == 'admin' ? 'selected' : '' ?>>Admin</option>
            <option value="manager" <?= $role == 'manager' ? 'selected' : '' ?>>Manager</option>
            <option value="staff" <?= $role == 'staff' ? 'selected' : '' ?>>Staff</option>
            <option value="receptionist" <?= $role == 'receptionist' ? 'selected' : '' ?>>Receptionist</option>
        </select>
    </div>
    <div class="form-group">
        <label for="specialization">Specialization<span class="text-danger">*</span></label>
        <input type="text" name="specialization" value="<?= htmlspecialchars($specialization) ?>" required>
    </div>
    <div class="form-group">
        <label for="email">Email<span class="text-danger">*</span></label>
        <input type="email" name="email" value="<?= htmlspecialchars($email) ?>" required>
    </div>
    <div class="form-group">
        <label for="phone">Phone</label>
        <input type="text" name="phone" value="<?= htmlspecialchars($phone) ?>">
    </div>
    <div class="form-group">
        <label for="department">Department</label>
        <input type="text" name="department" value="<?= htmlspecialchars($department) ?>">
    </div>
    <div class="form-group">
        <label for="date_of_joining">Date of Joining</label>
        <input type="date" name="date_of_joining" value="<?= htmlspecialchars($date_of_joining) ?>">
    </div>
    <div class="form-group">
        <label for="status">Status</label>
        <select name="status">
            <option value="active" <?= $status == 'active' ? 'selected' : '' ?>>Active</option>
            <option value="inactive" <?= $status == 'inactive' ? 'selected' : '' ?>>Inactive</option>
        </select>
    </div>
    <div class="form-group">
        <label for="profile_picture">Profile Picture</label>
        <input type="file" name="profile_picture" accept="image/*">
        <?php if ($profile_picture != 'default_profile.png'): ?>
            <p>Current Picture:</p>
            <img src="../assets/uploads/profile_pictures/<?= htmlspecialchars($profile_picture) ?>" alt="Profile Picture" width="100">
        <?php endif; ?>
    </div>
    <div class="actions">
        <button type="submit">Update Employee</button>
        <a href="manage_employees.php">Cancel</a>
    </div>
</form>

<?php include '../includes/footer.php'; ?>
M. tasks/add_task.php
Add a new task (admin and manager).


<?php
// tasks/add_task.php
include '../includes/header.php';
require_once '../includes/db_connect.php';
require_once '../includes/functions.php';

// Ensure the user is admin or manager
if (!in_array($_SESSION['role'], ['admin', 'manager'])) {
    echo "<div class='error'>Access denied. You do not have permission to view this page.</div>";
    include '../includes/footer.php';
    exit();
}

$title = $description = $assigned_to = $status = $due_date = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Collect and sanitize form data
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $assigned_to = $_POST['assigned_to'];
    $status = $_POST['status'] ?? 'To Do';
    $due_date = $_POST['due_date'];

    // Validation
    if (empty($title)) $errors[] = 'Task title is required.';
    if (empty($assigned_to)) $errors[] = 'Please assign the task to someone.';
    if (empty($due_date)) $errors[] = 'Due date is required.';

    // Check if assigned user exists
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE id = ?");
    $stmt->execute([$assigned_to]);
    if ($stmt->fetchColumn() == 0) {
        $errors[] = 'Assigned user does not exist.';
    }

    if (empty($errors)) {
        // Insert into database
        try {
            $stmt = $pdo->prepare("INSERT INTO tasks (title, description, assigned_to, status, due_date, created_by) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$title, $description, $assigned_to, $status, $due_date, $_SESSION['user_id']]);
            $success = "Task added successfully.";
            // Reset form fields
            $title = $description = $assigned_to = $status = $due_date = '';
        } catch (Exception $e) {
            $errors[] = "Error: " . $e->getMessage();
        }
    }
}

// Fetch all active users for assignment
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE status = 'active'");
$stmt->execute();
$users = $stmt->fetchAll();
?>

<h2>Add New Task</h2>

<?php if (!empty($errors)): ?>
    <div class="error">
        <ul>
        <?php foreach ($errors as $error): ?>
            <li><?= htmlspecialchars($error) ?></li>
        <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (isset($success)): ?>
    <div class="success">
        <?= htmlspecialchars($success) ?>
    </div>
<?php endif; ?>

<form action="add_task.php" method="post">
    <div class="form-group">
        <label for="title">Task Title<span class="text-danger">*</span></label>
        <input type="text" name="title" value="<?= htmlspecialchars($title) ?>" required>
    </div>
    <div class="form-group">
        <label for="description">Description</label>
        <textarea name="description"><?= htmlspecialchars($description) ?></textarea>
    </div>
    <div class="form-group">
        <label for="assigned_to">Assign To<span class="text-danger">*</span></label>
        <select name="assigned_to" required>
            <option value="">Select Employee</option>
            <?php foreach ($users as $user): ?>
                <option value="<?= $user['id'] ?>" <?= $assigned_to == $user['id'] ? 'selected' : '' ?>><?= htmlspecialchars($user['name']) ?></option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="form-group">
        <label for="status">Status</label>
        <select name="status">
            <option value="To Do" <?= $status == 'To Do' ? 'selected' : '' ?>>To Do</option>
            <option value="In Progress" <?= $status == 'In Progress' ? 'selected' : '' ?>>In Progress</option>
            <option value="Completed" <?= $status == 'Completed' ? 'selected' : '' ?>>Completed</option>
        </select>
    </div>
    <div class="form-group">
        <label for="due_date">Due Date<span class="text-danger">*</span></label>
        <input type="date" name="due_date" value="<?= htmlspecialchars($due_date) ?>" required>
    </div>
    <div class="actions">
        <button type="submit">Add Task</button>
        <a href="manage_tasks.php">Cancel</a>
    </div>
</form>

<?php include '../includes/footer.php'; ?>
N. tasks/manage_tasks.php
Manage (view, edit, delete) tasks.


<?php
// tasks/manage_tasks.php
include '../includes/header.php';
require_once '../includes/db_connect.php';
require_once '../includes/functions.php';

// Ensure the user is at least a manager
if (!in_array($_SESSION['role'], ['admin', 'manager'])) {
    echo "<div class='error'>Access denied. You do not have permission to view this page.</div>";
    include '../includes/footer.php';
    exit();
}

// Handle deletion if requested
if (isset($_GET['delete'])) {
    $delete_id = intval($_GET['delete']);
    $stmt = $pdo->prepare("DELETE FROM tasks WHERE id = ?");
    if ($stmt->execute([$delete_id])) {
        $success = "Task deleted successfully.";
    } else {
        $error = "Failed to delete task.";
    }
}

// Fetch all tasks, optionally based on role
if ($_SESSION['role'] == 'admin' || $_SESSION['role'] == 'manager') {
    $stmt = $pdo->query("SELECT tasks.*, users.name as assigned_name, creator.name as creator_name FROM tasks LEFT JOIN users ON tasks.assigned_to = users.id LEFT JOIN users as creator ON tasks.created_by = creator.id");
} elseif ($_SESSION['role'] == 'staff') {
    $stmt = $pdo->prepare("SELECT tasks.*, users.name as assigned_name, creator.name as creator_name FROM tasks LEFT JOIN users ON tasks.assigned_to = users.id LEFT JOIN users as creator ON tasks.created_by = creator.id WHERE tasks.assigned_to = ?");
    $stmt->execute([$_SESSION['user_id']]);
}
$tasks = isset($stmt) ? $stmt->fetchAll() : [];
?>

<h2>Manage Tasks</h2>

<div class="actions">
    <a href="add_task.php">Add New Task</a>
</div>

<?php if (isset($error)): ?>
    <div class="error">
        <?= htmlspecialchars($error) ?>
    </div>
<?php endif; ?>

<?php if (isset($success)): ?>
    <div class="success">
        <?= htmlspecialchars($success) ?>
    </div>
<?php endif; ?>

<table>
    <thead>
        <tr>
            <th>Title</th>
            <th>Assigned To</th>
            <th>Creator</th>
            <th>Status</th>
            <th>Due Date</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($tasks as $task): ?>
        <tr>
            <td><?= htmlspecialchars($task['title']) ?></td>
            <td><?= htmlspecialchars($task['assigned_name']) ?></td>
            <td><?= htmlspecialchars($task['creator_name']) ?></td>
            <td><?= htmlspecialchars($task['status']) ?></td>
            <td><?= htmlspecialchars($task['due_date']) ?></td>
            <td>
                <a href="edit_task.php?id=<?= $task['id'] ?>">Edit</a> |
                <a href="manage_tasks.php?delete=<?= $task['id'] ?>" onclick="return confirm('Are you sure you want to delete this task?');">Delete</a>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<?php include '../includes/footer.php'; ?>
O. tasks/edit_task.php
Edit an existing task (admin and manager).


<?php
// tasks/edit_task.php
include '../includes/header.php';
require_once '../includes/db_connect.php';
require_once '../includes/functions.php';

// Ensure the user is admin or manager
if (!in_array($_SESSION['role'], ['admin', 'manager'])) {
    echo "<div class='error'>Access denied. You do not have permission to view this page.</div>";
    include '../includes/footer.php';
    exit();
}

// Get task ID from URL
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: manage_tasks.php?error=Invalid task ID.");
    exit();
}
$task_id = intval($_GET['id']);

// Fetch task data
$stmt = $pdo->prepare("SELECT * FROM tasks WHERE id = ?");
$stmt->execute([$task_id]);
$task = $stmt->fetch();

if (!$task) {
    header("Location: manage_tasks.php?error=Task not found.");
    exit();
}

$title = $task['title'];
$description = $task['description'];
$assigned_to = $task['assigned_to'];
$status = $task['status'];
$due_date = $task['due_date'];
$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Collect and sanitize form data
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $assigned_to = $_POST['assigned_to'];
    $status = $_POST['status'] ?? 'To Do';
    $due_date = $_POST['due_date'];

    // Validation
    if (empty($title)) $errors[] = 'Task title is required.';
    if (empty($assigned_to)) $errors[] = 'Please assign the task to someone.';
    if (empty($due_date)) $errors[] = 'Due date is required.';

    // Check if assigned user exists
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE id = ?");
    $stmt->execute([$assigned_to]);
    if ($stmt->fetchColumn() == 0) {
        $errors[] = 'Assigned user does not exist.';
    }

    if (empty($errors)) {
        // Update database
        try {
            $stmt = $pdo->prepare("UPDATE tasks SET title = ?, description = ?, assigned_to = ?, status = ?, due_date = ? WHERE id = ?");
            $stmt->execute([$title, $description, $assigned_to, $status, $due_date, $task_id]);
            $success = "Task updated successfully.";
        } catch (Exception $e) {
            $errors[] = "Error: " . $e->getMessage();
        }
    }
}

// Fetch all active users for assignment
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE status = 'active'");
$stmt->execute();
$users = $stmt->fetchAll();
?>

<h2>Edit Task</h2>

<?php if (!empty($errors)): ?>
    <div class="error">
        <ul>
        <?php foreach ($errors as $error): ?>
            <li><?= htmlspecialchars($error) ?></li>
        <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (isset($success)): ?>
    <div class="success">
        <?= htmlspecialchars($success) ?>
    </div>
<?php endif; ?>

<form action="edit_task.php?id=<?= $task_id ?>" method="post">
    <div class="form-group">
        <label for="title">Task Title<span class="text-danger">*</span></label>
        <input type="text" name="title" value="<?= htmlspecialchars($title) ?>" required>
    </div>
    <div class="form-group">
        <label for="description">Description</label>
        <textarea name="description"><?= htmlspecialchars($description) ?></textarea>
    </div>
    <div class="form-group">
        <label for="assigned_to">Assign To<span class="text-danger">*</span></label>
        <select name="assigned_to" required>
            <option value="">Select Employee</option>
            <?php foreach ($users as $user): ?>
                <option value="<?= $user['id'] ?>" <?= $assigned_to == $user['id'] ? 'selected' : '' ?>><?= htmlspecialchars($user['name']) ?></option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="form-group">
        <label for="status">Status</label>
        <select name="status">
            <option value="To Do" <?= $status == 'To Do' ? 'selected' : '' ?>>To Do</option>
            <option value="In Progress" <?= $status == 'In Progress' ? 'selected' : '' ?>>In Progress</option>
            <option value="Completed" <?= $status == 'Completed' ? 'selected' : '' ?>>Completed</option>
        </select>
    </div>
    <div class="form-group">
        <label for="due_date">Due Date<span class="text-danger">*</span></label>
        <input type="date" name="due_date" value="<?= htmlspecialchars($due_date) ?>" required>
    </div>
    <div class="actions">
        <button type="submit">Update Task</button>
        <a href="manage_tasks.php">Cancel</a>
    </div>
</form>

<?php include '../includes/footer.php'; ?>
P. documents/upload_document.php
Upload new documents (admin, manager, staff).


<?php
// documents/upload_document.php
include '../includes/header.php';
require_once '../includes/db_connect.php';
require_once '../includes/functions.php';

// Ensure the user has the right role
if (!in_array($_SESSION['role'], ['admin', 'manager', 'staff'])) {
    echo "<div class='error'>Access denied. You do not have permission to view this page.</div>";
    include '../includes/footer.php';
    exit();
}

$file_name = $file_path = $category = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Collect and sanitize form data
    $category = trim($_POST['category']);

    // Validation
    if (empty($category)) $errors[] = 'Category is required.';

    // Document handling
    if (!empty($_FILES['document']['name'])) {
        $target_dir = "../assets/uploads/documents/";
        $imageFileType = strtolower(pathinfo($_FILES["document"]["name"], PATHINFO_EXTENSION));
        $new_file_name = time() . '_' . basename($_FILES["document"]["name"]);
        $target_file = $target_dir . $new_file_name;
        $uploadOk = 1;

        // Allow only specific formats
        $allowed_types = ['pdf', 'docx', 'doc', 'jpg', 'jpeg', 'png', 'gif'];
        if (!in_array($imageFileType, $allowed_types)) {
            $errors[] = "Only PDF, DOCX, DOC, JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }

        // Check file size (max 10MB)
        if ($_FILES["document"]["size"] > 10000000) {
            $errors[] = "File is too large.";
            $uploadOk = 0;
        }

        // Upload file
        if ($uploadOk) {
            if (move_uploaded_file($_FILES["document"]["tmp_name"], $target_file)) {
                $file_name = basename($_FILES["document"]["name"]);
                $file_path = $new_file_name;
            } else {
                $errors[] = "Error uploading the file.";
            }
        }
    } else {
        $errors[] = 'No file selected.';
    }

    if (empty($errors)) {
        // Insert into database
        try {
            $stmt = $pdo->prepare("INSERT INTO documents (file_name, file_path, uploaded_by, category) VALUES (?, ?, ?, ?)");
            $stmt->execute([$file_name, $file_path, $_SESSION['user_id'], $category]);
            $success = "Document uploaded successfully.";
            // Reset form fields
            $file_name = $file_path = $category = '';
        } catch (Exception $e) {
            $errors[] = "Error: " . $e->getMessage();
        }
    }
}
?>

<h2>Upload Document</h2>

<?php if (!empty($errors)): ?>
    <div class="error">
        <ul>
        <?php foreach ($errors as $error): ?>
            <li><?= htmlspecialchars($error) ?></li>
        <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (isset($success)): ?>
    <div class="success">
        <?= htmlspecialchars($success) ?>
    </div>
<?php endif; ?>

<form action="upload_document.php" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="category">Category<span class="text-danger">*</span></label>
        <input type="text" name="category" value="<?= htmlspecialchars($category) ?>" required>
    </div>
    <div class="form-group">
        <label for="document">Select Document<span class="text-danger">*</span></label>
        <input type="file" name="document" accept=".pdf,.docx,.doc,.jpg,.jpeg,.png,.gif" required>
    </div>
    <div class="actions">
        <button type="submit">Upload Document</button>
        <a href="manage_documents.php">Cancel</a>
    </div>
</form>

<?php include '../includes/footer.php'; ?>
Q. documents/manage_documents.php
Manage (view, delete) documents.


<?php
// documents/manage_documents.php
include '../includes/header.php';
require_once '../includes/db_connect.php';
require_once '../includes/functions.php';

// Ensure the user has the right role
if (!in_array($_SESSION['role'], ['admin', 'manager', 'staff'])) {
    echo "<div class='error'>Access denied. You do not have permission to view this page.</div>";
    include '../includes/footer.php';
    exit();
}

// Handle deletion if requested
if (isset($_GET['delete'])) {
    $delete_id = intval($_GET['delete']);
    // Fetch the document to get file path
    $stmt = $pdo->prepare("SELECT * FROM documents WHERE id = ?");
    $stmt->execute([$delete_id]);
    $document = $stmt->fetch();
    if ($document) {
        // Delete the file from server
        if (file_exists("../assets/uploads/documents/" . $document['file_path'])) {
            unlink("../assets/uploads/documents/" . $document['file_path']);
        }
        // Delete from database
        $stmt = $pdo->prepare("DELETE FROM documents WHERE id = ?");
        if ($stmt->execute([$delete_id])) {
            $success = "Document deleted successfully.";
        } else {
            $error = "Failed to delete document.";
        }
    } else {
        $error = "Document not found.";
    }
}

// Fetch all documents
$stmt = $pdo->prepare("SELECT documents.*, users.name as uploader_name FROM documents LEFT JOIN users ON documents.uploaded_by = users.id");
$stmt->execute();
$documents = $stmt->fetchAll();
?>

<h2>Manage Documents</h2>

<div class="actions">
    <a href="upload_document.php">Upload New Document</a>
</div>

<?php if (isset($error)): ?>
    <div class="error">
        <?= htmlspecialchars($error) ?>
    </div>
<?php endif; ?>

<?php if (isset($success)): ?>
    <div class="success">
        <?= htmlspecialchars($success) ?>
    </div>
<?php endif; ?>

<table>
    <thead>
        <tr>
            <th>File Name</th>
            <th>Category</th>
            <th>Uploaded By</th>
            <th>Uploaded At</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($documents as $doc): ?>
        <tr>
            <td><?= htmlspecialchars($doc['file_name']) ?></td>
            <td><?= htmlspecialchars($doc['category']) ?></td>
            <td><?= htmlspecialchars($doc['uploader_name']) ?></td>
            <td><?= htmlspecialchars($doc['uploaded_at']) ?></td>
            <td>
                <a href="view_document.php?id=<?= $doc['id'] ?>" target="_blank">View</a> |
                <a href="manage_documents.php?delete=<?= $doc['id'] ?>" onclick="return confirm('Are you sure you want to delete this document?');">Delete</a>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<?php include '../includes/footer.php'; ?>
R. documents/view_document.php
View/download a specific document.


<?php
// documents/view_document.php
include '../includes/header.php';
require_once '../includes/db_connect.php';
require_once '../includes/functions.php';

// Ensure the user has the right role
if (!in_array($_SESSION['role'], ['admin', 'manager', 'staff'])) {
    echo "<div class='error'>Access denied. You do not have permission to view this page.</div>";
    include '../includes/footer.php';
    exit();
}

// Get document ID from URL
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: manage_documents.php?error=Invalid document ID.");
    exit();
}
$doc_id = intval($_GET['id']);

// Fetch document data
$stmt = $pdo->prepare("SELECT * FROM documents WHERE id = ?");
$stmt->execute([$doc_id]);
$document = $stmt->fetch();

if (!$document) {
    header("Location: manage_documents.php?error=Document not found.");
    exit();
}

// Define the file path
$file_path = "../assets/uploads/documents/" . $document['file_path'];

if (!file_exists($file_path)) {
    echo "<div class='error'>File does not exist.</div>";
    include '../includes/footer.php';
    exit();
}

// Determine the Content-Type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $file_path);
finfo_close($finfo);

// Set headers to force download
header('Content-Description: File Transfer');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="' . basename($document['file_name']) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit();
?>
S. chat/chat.php
Basic internal chat interface.


<?php
// chat/chat.php
include '../includes/header.php';
require_once '../includes/db_connect.php';
require_once '../includes/functions.php';

// Ensure the user has the right role
if (!in_array($_SESSION['role'], ['admin', 'manager', 'staff', 'receptionist'])) {
    echo "<div class='error'>Access denied. You do not have permission to view this page.</div>";
    include '../includes/footer.php';
    exit();
}

// Fetch all users except the current user
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE id != ?");
$stmt->execute([$_SESSION['user_id']]);
$users = $stmt->fetchAll();

// Handle message sending via POST
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['receiver_id']) && isset($_POST['message'])) {
    $receiver_id = intval($_POST['receiver_id']);
    $message = trim($_POST['message']);

    if (!empty($message)) {
        $stmt = $pdo->prepare("INSERT INTO messages (sender_id, receiver_id, message) VALUES (?, ?, ?)");
        $stmt->execute([$_SESSION['user_id'], $receiver_id, $message]);
        header("Location: chat.php#user-$receiver_id");
        exit();
    }
}
?>

<h2>Internal Chat</h2>

<div class="chat-container">
    <div class="users-list">
        <h3>Users</h3>
        <ul>
            <?php foreach ($users as $user): ?>
                <li><a href="#user-<?= $user['id'] ?>"><?= htmlspecialchars($user['name']) ?></a></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <div class="chat-box">
        <?php foreach ($users as $user): ?>
            <div id="user-<?= $user['id'] ?>" class="chat-window">
                <h4>Chat with <?= htmlspecialchars($user['name']) ?></h4>
                <div class="messages" id="messages-<?= $user['id'] ?>">
                    <?php
                    // Fetch messages between current user and selected user
                    $stmt = $pdo->prepare("SELECT * FROM messages WHERE (sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?) ORDER BY timestamp ASC");
                    $stmt->execute([$_SESSION['user_id'], $user['id'], $user['id'], $_SESSION['user_id']]);
                    $messages = $stmt->fetchAll();
                    foreach ($messages as $msg) {
                        $sender = $msg['sender_id'] == $_SESSION['user_id'] ? "You" : htmlspecialchars($user['name']);
                        echo "<p><strong>{$sender}:</strong> " . htmlspecialchars($msg['message']) . "</p>";
                    }
                    ?>
                </div>
                <form action="chat.php#user-<?= $user['id'] ?>" method="post">
                    <input type="hidden" name="receiver_id" value="<?= $user['id'] ?>">
                    <input type="text" name="message" placeholder="Type your message..." required>
                    <button type="submit">Send</button>
                </form>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<style>
/* Basic styles for chat */
.chat-container {
    display: flex;
    gap: 20px;
}

.users-list {
    width: 25%;
    border-right: 1px solid #ccc;
    padding-right: 20px;
}

.users-list ul {
    list-style: none;
    padding: 0;
}

.users-list li {
    margin-bottom: 10px;
}

.chat-box {
    width: 75%;
}

.chat-window {
    margin-bottom: 40px;
}

.chat-window h4 {
    margin-bottom: 10px;
}

.messages {
    border: 1px solid #ccc;
    padding: 10px;
    height: 200px;
    overflow-y: scroll;
    background-color: #f1f1f1;
    margin-bottom: 10px;
}

.chat-window form {
    display: flex;
    gap: 10px;
}

.chat-window input[type="text"] {
    flex: 1;
    padding: 8px;
    border-radius: 5px;
    border: 1px solid #ccc;
}

.chat-window button {
    padding: 8px 16px;
    background-color: var(--primary-color);
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.chat-window button:hover {
    background-color: var(--secondary-color);
}
</style>

<?php include '../includes/footer.php'; ?>
T. chat/send_message.php
Handles AJAX-based message sending (optional for more advanced real-time features).

For simplicity, our current implementation handles message sending directly via form submission. To enhance with AJAX, you can implement separate handling, but it's outside the current scope.

U. index.php
Redirect to login or dashboard based on authentication status.


<?php
// index.php
session_start();
if (isset($_SESSION['user_id'])) {
    header("Location: dashboard.php");
} else {
    header("Location: login.php");
}
exit();
?>
4. Additional Feature Implementations
A. Task Completion Notification (Optional)
To notify users when tasks are approaching due dates or have been updated, you can implement SMS or email notifications using PHP's mail() function or external services like Twilio.

B. Real-Time Chat with AJAX or WebSockets
For a truly real-time chat experience, consider using AJAX polling or integrating WebSockets with PHP Ratchet or using a frontend framework.

C. File Versioning in Document Management
Implement version control for documents by adding a version field in the documents table and allowing users to upload new versions while keeping track of old ones.

D. Reporting and Analytics
Create detailed reports using PHP and integrate chart libraries like Chart.js to visualize data such as task completion rates, employee performance, etc.

5. .htaccess File
Enhance security by configuring the .htaccess file to restrict access to certain directories and handle URL rewriting.


# .htaccess

# Deny access to includes directory
<Directory "/app.longevacare.com/includes">
    Order Allow,Deny
    Deny from all
</Directory>

# Deny access to assets/uploads except for specific file types
<Directory "/app.longevacare.com/assets/uploads">
    <FilesMatch "\.(?i:jpg|jpeg|png|gif|pdf|docx|doc)$">
        Order Allow,Deny
        Allow from all
    </FilesMatch>
    Order Deny,Allow
    Deny from all
</Directory>

# Rewrite URLs for cleaner URLs (optional)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php [QSA,L]

# Prevent script execution in uploads directories
<Directory "/app.longevacare.com/assets/uploads/profile_pictures">
    RemoveHandler .php .phtml .php3
    RemoveType .php .phtml .php3
    <FilesMatch "^(.*)\.(php|phtml|php3)$">
        Order Deny,Allow
        Deny from All
    </FilesMatch>
</Directory>

<Directory "/app.longevacare.com/assets/uploads/documents">
    RemoveHandler .php .phtml .php3
    RemoveType .php .phtml .php3
    <FilesMatch "^(.*)\.(php|phtml|php3)$">
        Order Deny,Allow
        Deny from All
    </FilesMatch>
</Directory>
Ensure that .htaccess is enabled on your server and that Apache's mod_rewrite is enabled if you plan to use URL rewriting.

6. JavaScript Enhancements
A. assets/js/scripts.js
Basic scripts for interactivity. You can enhance as needed.


// assets/js/scripts.js

// Example: Automatically scroll messages to the bottom in chat windows
document.addEventListener("DOMContentLoaded", function() {
    const messageContainers = document.querySelectorAll('.messages');
    messageContainers.forEach(container => {
        container.scrollTop = container.scrollHeight;
    });
});

// Add more JavaScript functionalities as needed
7. Testing the Application
A. Local Development Setup
Install XAMPP/WAMP/MAMP:
Download and install a local server environment like XAMPP.
Create Project Directory:
Place your project files in the htdocs (XAMPP) or equivalent folder.
Configure Database:
Access phpMyAdmin via http://localhost/phpmyadmin/.
Create the longevacare_app database and execute the SQL scripts provided above.
Update Database Credentials:
In includes/db_connect.php, set the correct username and password (root and empty password by default in XAMPP).
Access the Application:
Navigate to http://localhost/app.longevacare.com/ (assuming app.longevacare.com is mapped to your local setup via hosts file).
B. Testing Features
Registration and Login:
Register a new admin account and log in.
Employee Management:
Add, view, edit, and delete employees.
Task Management:
Assign tasks and manage their status.
Document Management:
Upload and manage documents.
Internal Chat:
Send and receive messages between users.
Security Features:
Ensure access controls are functioning correctly (e.g., only admins can manage employees).
8. Deployment Guide
A. Preparing for Deployment
Choose a Hosting Provider:
Select a provider that supports PHP and MySQL (e.g., Bluehost, SiteGround).
Set Up Subdomain:
Create a subdomain app.longevacare.com pointing to your application directory.
Upload Files:
Use FTP/SFTP or your hosting provider's file manager to upload your project files to the server.
Import Database:
Export your local database via phpMyAdmin and import it on the live server.
Update Database Credentials:
Modify includes/db_connect.php with your live server's database credentials.
Configure .htaccess:
Upload the .htaccess file to your project root to enforce security measures.
B. Post-Deployment Steps
Set File Permissions:
Ensure that assets/uploads/ directories are writable by the server.
Enable HTTPS:
Secure your website with an SSL certificate.
Test All Features:
Verify that all functionalities are working correctly on the live site.
Monitor and Maintain:
Regularly update your application, monitor for security vulnerabilities, and back up your data.
9. Security Best Practices
Use Prepared Statements:
Prevent SQL injection by using prepared statements.
Password Hashing:
Always hash passwords using password_hash() and verify with password_verify().
Session Management:
Regenerate session IDs upon login using session_regenerate_id(true);.
Implement session timeouts to log out inactive users.
File Upload Security:
Validate file types and sizes.
Store uploads outside the web root or restrict access via .htaccess.
Access Control:
Implement role-based access control to restrict functionalities based on user roles.
Use HTTPS:
Ensure data transmission is secure by using HTTPS.
Regular Backups:
Schedule regular backups of your database and files.
Input Sanitization:
Sanitize all user inputs to prevent XSS and other attacks.
10. Conclusion
You've now set up a fully functional PHP-based web application tailored to your business needs. This application facilitates effective team collaboration, task management, document sharing, and internal communication. Remember to continuously monitor, maintain, and enhance your application to keep it secure and aligned with your evolving business requirements.

Feel free to reach out if you need further assistance or specific enhancements!

) ok, i want to update styles to be cool and respsoinve desing for all devices and i want in add_task.php when Assign To, add option to assgin to all employees and add option if select two people for one task as checkbox and add more features to be flexblie, and in chat/chat.php make it clear and flxibe and make it best ux design, and in documents/manage_documents.php add more features and option to make it cool and easy, and in dashboard.php make it cool and add more features and options and make it cool, and add something like box if add option to make task if this important box task or not or in porgress something like this with different colors and add more things