<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
require_once __DIR__ . '/helpers.php';
if (!isset($_SESSION['parent_id'])) { header('Location: login.php'); exit; }
$conn = portalGetConnection();
if (!$conn instanceof mysqli) { http_response_code(500); exit('Database connection failed.'); }
$messages = [];
$stmt = $conn->prepare(
    "SELECT pm.*, u.full_name AS admin_name
     FROM parent_messages pm
     LEFT JOIN users u ON u.id = pm.admin_id
     WHERE pm.parent_id = ?
     ORDER BY pm.created_at DESC"
);
$stmt->bind_param('i', $_SESSION['parent_id']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) { $messages[] = $row; }
$stmt->close();
echo portalPageStart('Messages', 'messages', 'Messages');
?>
<div class="portal-card">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="portal-section-title mb-0">Inbox / Sent</div>
        <button class="portal-btn-primary" data-bs-toggle="modal" data-bs-target="#messageModal">Send Message to School</button>
    </div>
    <ul class="nav nav-pills mb-3" id="messageTabs">
        <li class="nav-item"><button class="nav-link active" data-bs-toggle="pill" data-bs-target="#inboxPane" type="button">Inbox</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#sentPane" type="button">Sent</button></li>
    </ul>
    <div class="tab-content">
        <div class="tab-pane fade show active" id="inboxPane">
            <?php foreach ($messages as $message): if ($message['sender'] !== 'admin') continue; ?>
                <div class="portal-card mb-2">
                    <div class="d-flex justify-content-between">
                        <div class="fw-semibold"><?= htmlspecialchars((string) ($message['admin_name'] ?? 'School Administration')) ?></div>
                        <small class="portal-muted"><?= htmlspecialchars((string) $message['created_at']) ?></small>
                    </div>
                    <div class="small fw-semibold mt-1"><?= htmlspecialchars((string) ($message['subject'] ?? 'No subject')) ?></div>
                    <p class="mb-0 mt-2"><?= nl2br(htmlspecialchars((string) $message['message'])) ?></p>
                </div>
            <?php endforeach; ?>
        </div>
        <div class="tab-pane fade" id="sentPane">
            <?php foreach ($messages as $message): if ($message['sender'] !== 'parent') continue; ?>
                <div class="portal-card mb-2">
                    <div class="d-flex justify-content-between">
                        <div class="fw-semibold">You</div>
                        <small class="portal-muted"><?= htmlspecialchars((string) $message['created_at']) ?></small>
                    </div>
                    <div class="small fw-semibold mt-1"><?= htmlspecialchars((string) ($message['subject'] ?? 'No subject')) ?></div>
                    <p class="mb-0 mt-2"><?= nl2br(htmlspecialchars((string) $message['message'])) ?></p>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<div class="modal fade" id="messageModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="sendMessageForm">
                <input type="hidden" name="_csrf" value="<?= htmlspecialchars(portalCsrfToken()) ?>">
                <div class="modal-header"><h5 class="modal-title">Send Message to School</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <div class="mb-3"><label class="form-label">Subject</label><input type="text" name="subject" class="form-control" maxlength="200" required></div>
                    <div class="mb-3"><label class="form-label">Message</label><textarea name="message" class="form-control" rows="5" maxlength="500" required></textarea></div>
                </div>
                <div class="modal-footer"><button type="submit" class="btn btn-primary">Send</button></div>
            </form>
        </div>
    </div>
</div>
<script>
document.getElementById('sendMessageForm').addEventListener('submit', async function (event) {
    event.preventDefault();
    const response = await fetch('ajax/send_message.php', { method: 'POST', body: new URLSearchParams(new FormData(this)) });
    const data = await response.json();
    alert(data.message || 'Done');
    if (data.success) { location.reload(); }
});
</script>
<?= portalPageEnd('messages') ?>
