<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] !== 'PATIENT') {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$pat_res = $conn->query("SELECT patient_id, full_name, email FROM patients WHERE user_id = $user_id")->fetch_assoc();
$patient_id = $pat_res['patient_id'];

// Create table if not exists (Auto-setup for this module)
$conn->query("CREATE TABLE IF NOT EXISTS patient_messages (
    message_id INT AUTO_INCREMENT PRIMARY KEY,
    patient_id INT NOT NULL,
    subject VARCHAR(255) NOT NULL,
    message TEXT NOT NULL,
    status ENUM('SENT','READ','REPLIED') DEFAULT 'SENT',
    reply TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// Handle New Message
$success_msg = $error_msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_message'])) {
    $subject = $conn->real_escape_string($_POST['subject']);
    $message = $conn->real_escape_string($_POST['message']); // In production use prepared statements for insert

    $stmt = $conn->prepare("INSERT INTO patient_messages (patient_id, subject, message) VALUES (?, ?, ?)");
    $stmt->bind_param("iss", $patient_id, $subject, $message);

    if ($stmt->execute()) {
        $success_msg = "Message sent successfully!";
    } else {
        $error_msg = "Error sending message: " . $conn->error;
    }
}

// Fetch Messages
$sql = "SELECT * FROM patient_messages WHERE patient_id = ? ORDER BY created_at DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Messages')); ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">My Messages</h4>
                            </div>
                        </div>
                    </div>

                    <?php if ($success_msg): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $success_msg; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <?php if ($error_msg): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $error_msg; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-4">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Compose Message</h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Subject</label>
                                            <select class="form-select" name="subject" required>
                                                <option value="">Select Topic...</option>
                                                <option value="Appointment Inquiry">Appointment Inquiry</option>
                                                <option value="Billing Question">Billing Question</option>
                                                <option value="Medical Question">Medical Question</option>
                                                <option value="Feedback">Feedback</option>
                                                <option value="Other">Other</option>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Message</label>
                                            <textarea class="form-control" name="message" rows="5" required
                                                placeholder="Type your message here..."></textarea>
                                        </div>
                                        <div class="d-grid">
                                            <button type="submit" name="send_message" class="btn btn-primary">Send
                                                Message</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-8">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Message History</h5>
                                </div>
                                <div class="card-body">
                                    <table id="messagesTable" class="table table-bordered dt-responsive nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Subject</th>
                                                <th>Message & Reply</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($row = $result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo date('M d, Y H:i', strtotime($row['created_at'])); ?>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($row['subject']); ?></td>
                                                    <td>
                                                        <div class="p-2 border rounded bg-light mb-2">
                                                            <small class="text-muted">You:</small><br>
                                                            <?php echo nl2br(htmlspecialchars($row['message'])); ?>
                                                        </div>
                                                        <?php if ($row['reply']): ?>
                                                            <div class="p-2 border rounded bg-white">
                                                                <small class="text-success fw-bold">Clinic Reply:</small><br>
                                                                <?php echo nl2br(htmlspecialchars($row['reply'])); ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php
                                                        $statusClass = match ($row['status']) {
                                                            'SENT' => 'bg-secondary',
                                                            'READ' => 'bg-info',
                                                            'REPLIED' => 'bg-success',
                                                            default => 'bg-secondary'
                                                        };
                                                        ?>
                                                        <span
                                                            class="badge <?php echo $statusClass; ?>"><?php echo $row['status']; ?></span>
                                                    </td>
                                                </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#messagesTable').DataTable({
                order: [[0, 'desc']]
            });
        });
    </script>
</body>

</html>