based on this manage_comments (<?php
session_start();
require_once 'db_connect.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit();
}

// Handle AJAX requests (for reply and delete actions)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'reply' && isset($_POST['comment_id'], $_POST['reply_message'])) {
        $comment_id = $_POST['comment_id'];
        $reply_message = $_POST['reply_message'];

        // Fetch the original comment to get patient_id
        $stmt = $pdo->prepare("SELECT patient_id FROM comments WHERE id = ?");
        $stmt->execute([$comment_id]);
        $original_comment = $stmt->fetch();

        if ($original_comment) {
            $patient_id = $original_comment['patient_id'];

            // Insert the reply into the comments table with sender='admin'
            $stmt = $pdo->prepare("INSERT INTO comments (patient_id, sender, message, parent_id) VALUES (?, 'admin', ?, ?)");
            $stmt->execute([$patient_id, $reply_message, $comment_id]);

            echo json_encode(['status' => 'success', 'message' => 'Reply sent successfully.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Original comment not found.']);
        }
        exit();
    }

    if ($_POST['action'] === 'delete' && isset($_POST['comment_id'])) {
        $comment_id = $_POST['comment_id'];

        // Delete the comment and its replies
        $stmt = $pdo->prepare("DELETE FROM comments WHERE id = ? OR parent_id = ?");
        $stmt->execute([$comment_id, $comment_id]);

        echo json_encode(['status' => 'success', 'message' => 'Comment deleted successfully.']);
        exit();
    }
}

// Fetch comments grouped by patient
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$sender_filter = isset($_GET['sender']) ? $_GET['sender'] : '';

$params = [];
$query = "SELECT c.*, p.name AS patient_name
          FROM comments c
          JOIN patients p ON c.patient_id = p.id
          WHERE c.parent_id IS NULL";

if ($search !== '') {
    $query .= " AND (p.name LIKE :search OR p.id = :patient_id)";
    $params[':search'] = '%' . $search . '%';
    $params[':patient_id'] = $search;
}

if ($sender_filter !== '') {
    $query .= " AND c.sender = :sender_filter";
    $params[':sender_filter'] = $sender_filter;
}

$query .= " ORDER BY p.name ASC, c.timestamp DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Organize comments by patient
$comments_by_patient = [];
foreach ($comments as $comment) {
    $patient_id = $comment['patient_id'];
    if (!isset($comments_by_patient[$patient_id])) {
        $comments_by_patient[$patient_id] = [
            'patient_name' => $comment['patient_name'],
            'comments' => []
        ];
    }
    $comments_by_patient[$patient_id]['comments'][] = $comment;
}

// Function to fetch replies
function fetchReplies($pdo, $comment_id) {
    $stmt = $pdo->prepare("SELECT * FROM comments WHERE parent_id = ? ORDER BY timestamp ASC");
    $stmt->execute([$comment_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>Manage Comments</title>
    
    <!-- Importing Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" rel="stylesheet">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome for Icons -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f5f5f5;
            font-family: 'Roboto', Arial, sans-serif;
            color: #333;
            margin: 0;
            padding: 0;
            min-height: 100vh;
        }

        .container {
            margin-top: 50px;
            margin-bottom: 50px;
            max-width: 900px;
            background: #fff;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
        }

        .page-title {
            font-size: 32px;
            font-weight: 700;
            color: #4F3F02;
            margin-bottom: 30px;
            text-align: center;
        }

        .comment {
            border-bottom: 1px solid #ddd;
            padding: 15px 0;
        }

        .comment-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .comment-body {
            margin-top: 10px;
        }

        .comment .patient-name {
            font-weight: 700;
            color: #4F3F02;
        }

        .comment .timestamp {
            font-size: 14px;
            color: #888;
        }

        .comment .sender-badge {
            margin-left: 10px;
            font-size: 12px;
        }

        .comment .actions a {
            color: #d9534f;
            text-decoration: none;
            margin-left: 10px;
            font-size: 16px;
        }

        .comment .actions a.reply-link {
            color: #4F3F02;
            font-size: 16px;
        }

        .comment .actions a:hover {
            text-decoration: underline;
        }

        .reply-form {
            margin-top: 15px;
        }

        .reply-form textarea {
            margin-bottom: 10px;
        }

        .nested-comment {
            margin-left: 40px;
        }

        .toggle-replies {
            cursor: pointer;
            color: #4F3F02;
            font-size: 14px;
            margin-top: 10px;
        }

        .toggle-replies:hover {
            text-decoration: underline;
        }

        .search-form {
            margin-bottom: 30px;
        }

        .btn-custom {
            background-color: #4F3F02;
            color: #ffffff;
            padding: 8px 16px;
            border: none;
            border-radius: 30px;
            font-weight: 700;
            font-size: 14px;
            transition: background-color 0.3s ease;
        }

        .btn-custom:hover {
            background-color: #D1C287;
            color: #4F3F02;
        }

        @media (max-width: 576px) {
            .page-title {
                font-size: 24px;
            }

            .container {
                padding: 20px;
            }

            .comment-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .comment .actions {
                margin-top: 10px;
            }
        }
    </style>
</head>
<body>

<div class="container">
    <h1 class="page-title text-center">Manage Comments</h1>
    <div class="text-end mb-3">
        <a href="admin_dashboard.php" class="btn btn-custom"><i class="fas fa-arrow-left"></i> Back to Dashboard</a>
    </div>

    <form method="GET" action="" class="search-form row gx-3 gy-2">
        <div class="col-md-6">
            <input type="text" name="search" class="form-control" placeholder="Search by Patient Name or ID" value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-3">
            <select name="sender" class="form-select">
                <option value="">All Senders</option>
                <option value="patient" <?= $sender_filter == 'patient' ? 'selected' : '' ?>>Patient</option>
                <option value="admin" <?= $sender_filter == 'admin' ? 'selected' : '' ?>>Admin</option>
            </select>
        </div>
        <div class="col-md-3">
            <button type="submit" class="btn btn-custom w-100"><i class="fas fa-search"></i> Search</button>
        </div>
    </form>

    <?php if ($comments_by_patient): ?>
        <div class="accordion" id="commentsAccordion">
            <?php foreach ($comments_by_patient as $patient_id => $patient_data): ?>
                <div class="accordion-item">
                    <h2 class="accordion-header" id="heading<?= $patient_id ?>">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse<?= $patient_id ?>" aria-expanded="false" aria-controls="collapse<?= $patient_id ?>">
                            <?= htmlspecialchars($patient_data['patient_name']) ?> (<?= count($patient_data['comments']) ?> Comment<?= count($patient_data['comments']) > 1 ? 's' : '' ?>)
                        </button>
                    </h2>
                    <div id="collapse<?= $patient_id ?>" class="accordion-collapse collapse" aria-labelledby="heading<?= $patient_id ?>" data-bs-parent="#commentsAccordion">
                        <div class="accordion-body">
                            <?php foreach ($patient_data['comments'] as $comment): ?>
                                <div class="comment">
                                    <div class="comment-header">
                                        <div>
                                            <span class="patient-name"><?= htmlspecialchars($patient_data['patient_name']) ?></span>
                                            <span class="badge bg-secondary sender-badge"><?= ucfirst($comment['sender']) ?></span>
                                            <span class="timestamp"><?= date('F j, Y, g:i a', strtotime($comment['timestamp'])) ?></span>
                                        </div>
                                        <div class="actions">
                                            <?php if ($comment['sender'] == 'patient'): ?>
                                                <a href="#" class="reply-link" data-comment-id="<?= $comment['id'] ?>"><i class="fas fa-reply"></i></a>
                                            <?php endif; ?>
                                            <a href="#" class="delete-link" data-comment-id="<?= $comment['id'] ?>"><i class="fas fa-trash-alt"></i></a>
                                        </div>
                                    </div>
                                    <div class="comment-body">
                                        <?= nl2br(htmlspecialchars($comment['message'])) ?>
                                    </div>

                                    <?php
                                    $replies = fetchReplies($pdo, $comment['id']);
                                    if ($replies):
                                    ?>
                                        <div class="mt-3">
                                            <?php foreach ($replies as $reply): ?>
                                                <div class="comment nested-comment">
                                                    <div class="comment-header">
                                                        <div>
                                                            <span class="patient-name"><?= $reply['sender'] == 'admin' ? 'Admin' : htmlspecialchars($patient_data['patient_name']) ?></span>
                                                            <span class="badge bg-secondary sender-badge"><?= ucfirst($reply['sender']) ?></span>
                                                            <span class="timestamp"><?= date('F j, Y, g:i a', strtotime($reply['timestamp'])) ?></span>
                                                        </div>
                                                        <div class="actions">
                                                            <a href="#" class="delete-link" data-comment-id="<?= $reply['id'] ?>"><i class="fas fa-trash-alt"></i></a>
                                                        </div>
                                                    </div>
                                                    <div class="comment-body">
                                                        <?= nl2br(htmlspecialchars($reply['message'])) ?>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($comment['sender'] == 'patient'): ?>
                                        <div class="reply-form" id="reply_form_<?= $comment['id'] ?>" style="display: none;">
                                            <textarea class="form-control mb-2" rows="3" placeholder="Type your reply..."></textarea>
                                            <button class="btn btn-custom send-reply-btn" data-comment-id="<?= $comment['id'] ?>">Send Reply</button>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="alert alert-info mt-4" role="alert">
            No comments found.
        </div>
    <?php endif; ?>
</div>


<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Bootstrap JS Bundle (includes Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
    $(document).ready(function() {
        // Toggle reply form
        $('.reply-link').click(function(e) {
            e.preventDefault();
            var commentId = $(this).data('comment-id');
            $('#reply_form_' + commentId).toggle();
        });

        // Send reply
        $('.send-reply-btn').click(function() {
            var commentId = $(this).data('comment-id');
            var replyForm = $('#reply_form_' + commentId);
            var replyMessage = replyForm.find('textarea').val();

            if (replyMessage.trim() === '') {
                alert('Please enter a reply message.');
                return;
            }

            // Disable the button to prevent multiple clicks
            $(this).prop('disabled', true);

            $.ajax({
                url: 'manage_comments.php',
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'reply',
                    comment_id: commentId,
                    reply_message: replyMessage
                },
                success: function(response) {
                    if (response.status === 'success') {
                        alert(response.message);
                        location.reload();
                    } else {
                        alert(response.message);
                        // Re-enable the button in case of error
                        $('.send-reply-btn[data-comment-id="' + commentId + '"]').prop('disabled', false);
                    }
                },
                error: function() {
                    alert('An error occurred while sending the reply.');
                    $('.send-reply-btn[data-comment-id="' + commentId + '"]').prop('disabled', false);
                }
            });
        });

        // Delete comment
        $('.delete-link').click(function(e) {
            e.preventDefault();
            if (!confirm('Are you sure you want to delete this comment?')) return;

            var commentId = $(this).data('comment-id');

            $.ajax({
                url: 'manage_comments.php',
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'delete',
                    comment_id: commentId
                },
                success: function(response) {
                    if (response.status === 'success') {
                        alert(response.message);
                        location.reload();
                    } else {
                        alert(response.message);
                    }
                }
            });
        });
    });
</script>
</body>
</html>)  i want you to change and make it cool layout and make the new comments show first and this info database (Updated Database Structure
Database Structure
The database for the admin dashboard and patient management system consists of the following tables:
a. Patients
id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each patient.
name (VARCHAR): Full name of the patient.
age (INT): Age of the patient.
gender (ENUM('Male', 'Female', 'Other')): Gender of the patient.
phone (VARCHAR): Phone number of the patient.
email (VARCHAR): Email address of the patient.
medical_history (TEXT): Medical history of the patient.
date_of_birth (DATE): Date of birth of the patient.
registration_date (DATE): Date when the patient was registered.
registration_datetime (DATETIME): Date and time when the patient was registered.
status (ENUM): Current status of the patient (e.g., 'Initial Consultation', 'Treatment in Progress').
b. Health Records
id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each health record.
patient_id (INT, FOREIGN KEY REFERENCES patients(id)): ID of the patient associated with this health record.
blood_pressure (VARCHAR): Blood pressure reading.
weight (DECIMAL): Weight of the patient.
bmi (DECIMAL): Body Mass Index of the patient.
cholesterol (DECIMAL): Cholesterol level of the patient.
prescription (TEXT): Prescriptions given to the patient.
treatment_progress (TEXT): Notes on the treatment progress.
record_date (DATE): Date of the health record.
c. Admins
id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each admin.
username (VARCHAR): Admin's username.
password (VARCHAR): Hashed password for the admin.
email (VARCHAR): Email address of the admin.
d. Patient Logins
id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each patient login.
patient_id (INT, FOREIGN KEY REFERENCES patients(id)): ID of the patient associated with this login.
username (VARCHAR): Username for patient login.
password (VARCHAR): Hashed password for patient login.
e. Invoices
id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each invoice.
patient_id (INT NOT NULL, FOREIGN KEY REFERENCES patients(id)): ID of the patient associated with this invoice.
service_name (VARCHAR(255) NOT NULL): Name of the service rendered.
service_description (TEXT): Description of the service.
cost (DECIMAL(10, 2) NOT NULL): Cost of the service.
tax_rate (DECIMAL(5, 2) DEFAULT 0): Tax rate applied to the service.
discount (DECIMAL(5, 2) DEFAULT 0): Discount applied to the service.
total_amount (DECIMAL(10, 2) NOT NULL): Total amount due after tax and discount.
invoice_date (DATE DEFAULT CURRENT_DATE): Date of the invoice.
notes (TEXT): Additional notes for the invoice.
f. Services
service_id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each service.
service_name (VARCHAR(255) NOT NULL): Name of the service.
service_price (DECIMAL(10, 2) NOT NULL): Price of the service.
service_description (TEXT): Description of the service.
created_at (TIMESTAMP DEFAULT CURRENT_TIMESTAMP): Timestamp when the service was created.
updated_at (TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP): Timestamp when the service was last updated.
g. Invoice Services
id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each entry in the invoice services table.
invoice_id (INT NOT NULL, FOREIGN KEY REFERENCES invoices(id)): ID of the associated invoice.
service_id (INT NOT NULL, FOREIGN KEY REFERENCES services(service_id)): ID of the associated service.
service_name (VARCHAR(255) NOT NULL): Name of the service rendered.
cost (DECIMAL(10, 2) NOT NULL): Cost of the service rendered.
h. Comments
id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each comment.
patient_id (INT NOT NULL, FOREIGN KEY REFERENCES patients(id)): ID of the patient associated with the comment.
sender (ENUM('patient', 'doctor', 'admin') NOT NULL): Sender of the comment, which can now be 'patient', 'doctor', or 'admin'.
message (TEXT NOT NULL): The message or comment content.
timestamp (DATETIME DEFAULT CURRENT_TIMESTAMP): Date and time the comment was made.
parent_id (INT NULL DEFAULT NULL): ID of the parent comment (for threaded conversations), if applicable.
i. Doctor-Patient
id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each doctor-patient relationship.
doctor_id (INT NOT NULL, FOREIGN KEY REFERENCES doctors(id)): ID of the associated doctor.
patient_id (INT NOT NULL, FOREIGN KEY REFERENCES patients(id)): ID of the associated patient.
UNIQUE (doctor_id, patient_id): Ensures a unique doctor-patient pair.


File Paths
Here are the file paths for the PHP files:
/your_web_root/
│
├── admin_dashboard.php          // Admin dashboard displaying patient list
├── admin_login.php              // Admin login page
├── admin_logout.php             // Admin logout functionality
├── create_patient.php           // Page for creating a new patient
├── view_patient.php             // Page for viewing patient details
├── edit_patient.php             // Page for editing patient information
├── delete_patient.php           // Page for deleting a patient
├── add_health_record.php        // Page for adding health records for a patient
├── edit_health_record.php       // Page for editing health records
├── patient_login.php            // Patient login page
├── patient_dashboard.php        // Patient dashboard displaying their information
├── patient_logout.php           // Patient logout functionality
├── db_connect.php               // Database connection file
├── index.php                    // Index home 
├── update_patient_status.php     // Update patient status
├── doctors/
│   ├── login.php                // Doctor login page
│   ├── logout.php               // Doctor logout functionality
│   ├── dashboard.php             // Doctor dashboard
│   ├── view_patient.php         // Doctor view patient page
│   ├── edit_health_record.php    // Doctor edit health record page
│   ├── add_health_record.php     // Doctor add health record page
│   ├── health_records.php        // Doctor health records page
│   └── manage_doctors.php        // Admin manage doctors page
│
├── patients/
│   ├── delete_comment.php        // Delete a patient comment
│   ├── patient_dashboard.php     // Patient dashboard
│   ├── patient_login.php         // Patient login page
│   ├── send_comment.php          // Send a comment from patient
│   └── patient_logout.php        // Patient logout functionality
│
├── invoice/
│   ├── index.php                 // Page for generating an invoice
│   ├── services.php              // Page for managing services
│   ├── create_invoice.php        // Page for creating a new invoice
│   ├── edit_invoice.php          // Page for editing an invoice
│   ├── print_invoice.php         // Page for printing an invoice
│   └── view_invoice.php          // Page for viewing an invoice
) and type full codes