<?php
session_start();
include "db.php";

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

$user_id = $_SESSION['user_id'];
$message_sent = false;
$error = "";

/* =========================
   HANDLE MESSAGE SUBMISSION
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['title'], $_POST['message'])) {
    $title = trim($_POST['title']);
    $message = trim($_POST['message']);

    if (empty($title) || empty($message)) {
        $error = "Please fill in both fields.";
    } else {
        $stmt = $conn->prepare("
            INSERT INTO student_messages (user_id, title, message, created_at)
            VALUES (?, ?, ?, NOW())
        ");
        $stmt->bind_param("iss", $user_id, $title, $message);

        if ($stmt->execute()) {
            $message_sent = true;
        } else {
            $error = "Failed to send message. Try again.";
        }
        $stmt->close();
    }
}

/* =========================
   PAGINATION SETUP
========================= */
$limit = 5;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Count messages
$stmt = $conn->prepare("SELECT COUNT(*) FROM student_messages WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($total_messages);
$stmt->fetch();
$stmt->close();

$total_pages = ceil($total_messages / $limit);

// Fetch messages
$stmt = $conn->prepare("
    SELECT * FROM student_messages
    WHERE user_id = ?
    ORDER BY created_at DESC
    LIMIT ?, ?
");
$stmt->bind_param("iii", $user_id, $offset, $limit);
$stmt->execute();
$messages = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Messages</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@300;400;500;600&family=Poppins:wght@300;400;500&display=swap" rel="stylesheet">

<style>
:root {
    --primary: rgb(18, 108, 201);
    --primary-hover: rgb(14, 85, 160);
    --bg: #ffffff;
    --text-dark: rgb(22, 34, 57);
    --muted: #6b7280;
    --border: #e5e7eb;
    --input-bg: #f9fafb;
}

* { box-sizing: border-box; transition: all 0.2s ease; }

body {
    margin: 0;
    background: var(--bg);
    color: var(--text-dark);
    font-family: 'Poppins', sans-serif;
    line-height: 1.6;
}

.wrapper {
    max-width: 850px;
    margin: 40px auto;
    padding: 0 20px;
}

/* Header & Logo */
.topbar {
    border-bottom: 1px solid var(--border);
    padding: 20px 0;
    margin-bottom: 40px;
    text-align: left;
}

.topbar img { height: 50px; }

/* Typography */
h2 {
    font-family: 'Oswald', sans-serif;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: var(--text-dark);
    margin-bottom: 25px;
    border-left: 4px solid var(--primary);
    padding-left: 15px;
}

/* Form Styling */
.message-form {
    background: var(--input-bg);
    padding: 30px;
    border-radius: 12px;
    border: 1px solid var(--border);
    margin-bottom: 50px;
}

.message-form label {
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: uppercase;
    color: var(--primary);
    display: block;
    margin-bottom: 8px;
}

.message-form input, 
.message-form textarea {
    width: 100%;
    padding: 12px 15px;
    margin-bottom: 20px;
    border: 1px solid var(--border);
    border-radius: 8px;
    font-family: inherit;
    font-size: 1rem;
}

.message-form input:focus, 
.message-form textarea:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(18, 108, 201, 0.1);
}

.message-form button {
    background: var(--primary);
    color: white;
    border: none;
    padding: 12px 35px;
    border-radius: 50px;
    font-weight: 500;
    cursor: pointer;
    box-shadow: 0 4px 6px rgba(18, 108, 201, 0.2);
}

.message-form button:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
}

/* Message Feed */
.message {
    padding: 25px;
    margin-bottom: 20px;
    background: white;
    border: 1px solid var(--border);
    border-radius: 12px;
}

.message-title {
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--primary);
    margin-bottom: 5px;
}

.message-body {
    font-size: 0.95rem;
    color: var(--text-dark);
}

.message-date {
    font-size: 0.75rem;
    color: var(--muted);
    margin-top: 10px;
    display: block;
}

/* Replies Section */
.replies {
    margin-top: 20px;
    padding: 15px 20px;
    background: #f0f7ff;
    border-left: 3px solid var(--primary);
    border-radius: 0 8px 8px 0;
}

.replies h6 {
    margin: 0 0 10px 0;
    text-transform: uppercase;
    font-size: 0.7rem;
    letter-spacing: 1px;
}

/* Pagination */
.pagination {
    display: flex;
    justify-content: center;
    gap: 8px;
    margin: 40px 0;
}

.pagination a {
    padding: 8px 16px;
    border: 1px solid var(--border);
    border-radius: 6px;
    text-decoration: none;
    color: var(--text-dark);
}

.pagination a.active {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}

@media(max-width: 600px) {
    .wrapper { margin: 20px auto; }
    .message-form { padding: 20px; }
}
</style>
</head>

<body style="background-color:white;">

<div class="topbar">
    <img src="../assets/images/Activ8-Hub-logo.png" alt="Activ8 Hub"style="height:90px">
</div>

<div class="wrapper">

    <!-- SEND MESSAGE -->
    <section class="message-form">
        <h2>Send Message</h2>

        <?php if ($message_sent): ?>
            <div class="alert success">Message sent successfully.</div>
        <?php elseif (!empty($error)): ?>
            <div class="alert error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <form method="POST">
            <label>Title</label>
            <input type="text" name="title" required>

            <label>Message</label>
            <textarea name="message" rows="5" required></textarea>

            <button type="submit">Send</button>
        </form>
    </section>
 <h2 >Your Messages</h2>
    <!-- MESSAGE HISTORY -->
    <?php foreach ($messages as $msg): ?>
        <div class="message">
           
            <div class="message-title"><?= htmlspecialchars($msg['title']) ?></div>
            <div class="message-body" style="color:rgb(22,34,57);"><?= nl2br(htmlspecialchars($msg['message'])) ?></div>
            <div class="message-date"><?= date("d M Y • h:i A", strtotime($msg['created_at'])) ?></div>

            <?php
            $stmt = $conn->prepare("
                SELECT reply, created_at
                FROM student_message_replies
                WHERE message_id = ?
                ORDER BY created_at ASC
            ");
            $stmt->bind_param("i", $msg['id']);
            $stmt->execute();
            $replies = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            ?>

            <?php if(count($replies)>0): ?>
            <div class="replies">
                <h6 style="color:rgb(18,108,201);">replies</h6>
                <?php foreach($replies as $r): ?>
                    <p style="color:rgb(22,34,57);">
                        <?= nl2br(htmlspecialchars($r['reply'])) ?><br>
                        <small><?= date("d M Y • h:i A", strtotime($r['created_at'])) ?></small>
                    </p>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>

    <?php if ($total_pages > 1): ?>
    <div class="pagination">
        <?php for ($i=1;$i<=$total_pages;$i++): ?>
            <a href="?page=<?= $i ?>" class="<?= $i==$page?'active':'' ?>"><?= $i ?></a>
        <?php endfor; ?>
    </div>
    <?php endif; ?>

</div>


</body>
</html><br><br><br><br>
<?php include "footer.php"; ?>
