<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/iscms_layout.php';

$conn = iscms_init();
$pageTitle = 'Notifications';
$activeNav = 'dashboard';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'mark_all_read') {
    $uidPost = (string) ($_SESSION['user_id'] ?? '');
    if ($uidPost !== '' && iscms_csrf_validate($_POST['csrf_token'] ?? null)) {
        $up = $conn->prepare('UPDATE notifications SET is_read = 1, read_at = NOW() WHERE user_id = ? AND is_read = 0');
        if ($up) {
            $up->bind_param('s', $uidPost);
            $up->execute();
            $up->close();
        }
    }
    header('Location: notifications.php');
    exit;
}

$uid = (string) ($_SESSION['user_id'] ?? '');
$rows = [];
$dbError = null;

if ($uid !== '') {
    $sql = "SELECT n.id, n.title, n.message, n.notification_type, n.entity_type, n.entity_id,
                   n.is_read, n.read_at, n.created_at
            FROM notifications n
            WHERE n.user_id = ?
            ORDER BY n.created_at DESC
            LIMIT 200";
    $st = $conn->prepare($sql);
    if ($st) {
        $st->bind_param('s', $uid);
        $st->execute();
        $res = $st->get_result();
        $rows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
        $st->close();
    } else {
        $dbError = $conn->error;
    }
}

iscms_render_head($pageTitle);
iscms_render_sidebar($activeNav);
iscms_render_topbar($pageTitle);
?>
    <div class="page-header">
        <h1>Notifications</h1>
        <p>In-app alerts for your account.</p>
    </div>

    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-links-line"></i> Related</h2>
        </div>
        <div class="quick-actions">
            <a class="qa-btn" href="index.php"><i class="ri-dashboard-3-line"></i> Dashboard</a>
            <a class="qa-btn" href="messaging.php"><i class="ri-chat-3-line"></i> Messaging</a>
            <?php if ($uid !== ''): ?>
            <form method="post" action="notifications.php" class="d-inline ms-1">
                <input type="hidden" name="csrf_token" value="<?= iscms_h(iscms_csrf_token()) ?>">
                <input type="hidden" name="action" value="mark_all_read">
                <button type="submit" class="btn btn-sm btn-outline-secondary"><i class="ri-check-double-line me-1"></i>Mark all read</button>
            </form>
            <?php endif; ?>
        </div>
    </div>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-notification-3-line"></i> Inbox</h2>
            <span class="text-muted" style="font-size:.75rem"><?= count($rows) ?> shown</span>
        </div>
        <div class="table-responsive">
            <?php if ($dbError): ?>
                <div class="alert alert-danger m-3" style="font-size:.85rem">Unable to load data: <?= iscms_h($dbError) ?></div>
            <?php else: ?>
            <table class="ssbs-table">
                <thead>
                    <tr>
                        <th>When</th>
                        <th>Type</th>
                        <th>Title</th>
                        <th>Message (excerpt)</th>
                        <th>Read</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($rows)): ?>
                    <tr class="empty-row"><td colspan="5"><i class="ri-inbox-line me-2"></i>No notifications</td></tr>
                    <?php else: ?>
                        <?php foreach ($rows as $r): ?>
                        <?php
                            $msg = (string) ($r['message'] ?? '');
                            $msgDisp = strlen($msg) > 100 ? substr($msg, 0, 97) . '...' : $msg;
                        ?>
                        <tr>
                            <td><small class="text-muted"><?= !empty($r['created_at']) ? iscms_h(substr((string) $r['created_at'], 0, 19)) : '-' ?></small></td>
                            <td><small><?= iscms_h(str_replace('_', ' ', (string) ($r['notification_type'] ?? ''))) ?></small></td>
                            <td><small><strong><?= iscms_h((string) ($r['title'] ?? '')) ?></strong></small></td>
                            <td><small><?= iscms_h($msgDisp) ?></small></td>
                            <td><?= !empty($r['is_read']) ? '<span class="badge bg-secondary-subtle text-secondary" style="font-size:.65rem">Read</span>' : '<span class="badge bg-primary-subtle text-primary" style="font-size:.65rem">New</span>' ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
<?php
iscms_render_footer();
