<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_auth();
$pageTitle = 'Obaveštenja';
$pageSubtitle = 'Pregled sistemskih obaveštenja za vaš nalog';

if (isset($_GET['open'])) {
    if (!csrf_token_is_valid((string)($_GET['csrf'] ?? ''))) {
        http_response_code(419);
        exit('Bezbednosni token je istekao ili nije validan. Otvorite obaveštenje ponovo iz sistema.');
    }
    $notificationId = (int)$_GET['open'];
    $link = mark_notification_read($notificationId, (int)$user['id']);
    if ($link !== null && $link !== '') {
        redirect($link);
    }
    redirect('notifications.php');
}

if (is_post()) {
    validate_csrf();
    $action = (string)($_POST['action'] ?? '');
    if ($action === 'mark_all') {
        mark_all_notifications_read((int)$user['id']);
        flash('success', 'Sva obaveštenja su označena kao pročitana.');
        redirect('notifications.php');
    }
}

try {
    $stmt = db()->prepare('SELECT id, title, message, link_url, is_read, created_at, read_at FROM notifications WHERE user_id = ? ORDER BY is_read ASC, created_at DESC LIMIT 100');
    $stmt->execute([(int)$user['id']]);
    $notifications = $stmt->fetchAll();
} catch (Throwable $e) {
    $notifications = [];
}

require_once __DIR__ . '/app/header.php';
?>
<section class="card card-pad">
    <div class="section-heading">
        <div>
            <span class="badge">Centar obaveštenja</span>
            <h2>Moja obaveštenja</h2>
            <p>Prikazana su poslednja obaveštenja povezana sa zahtevima, nalogom i dodeljenom opremom.</p>
        </div>
        <form method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="mark_all">
            <button class="button button-light" type="submit">Označi sve kao pročitano</button>
        </form>
    </div>

    <?php if (!$notifications): ?>
        <p class="empty-state">Trenutno nema obaveštenja.</p>
    <?php else: ?>
        <div class="notification-page-list">
            <?php foreach ($notifications as $notification): ?>
                <a class="notification-card <?= (int)$notification['is_read'] === 0 ? 'neprocitano' : '' ?>" href="<?= e(url('notifications.php?open=' . (int)$notification['id'] . '&csrf=' . rawurlencode(csrf_token()))) ?>">
                    <div>
                        <strong><?= e($notification['title']) ?></strong>
                        <p><?= e($notification['message']) ?></p>
                        <small><?= e(format_datetime($notification['created_at'])) ?></small>
                    </div>
                    <span class="pill <?= (int)$notification['is_read'] === 0 ? 'status-open' : 'status-closed' ?>"><?= (int)$notification['is_read'] === 0 ? 'Novo' : 'Pročitano' ?></span>
                </a>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</section>
<?php require_once __DIR__ . '/app/footer.php'; ?>
