<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/middleware.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/notifications.php';

if (!isset($pdo)) {
    $pdo = require_once __DIR__ . '/config/database.php';
}

require_auth();

$user = current_user();
$userId = (int)$user['id'];

// Handle Actions
$action = $_POST['action'] ?? '';
if ($action === 'read') {
    ensure_csrf();
    $notifId = (int)($_POST['id'] ?? 0);
    mark_notification_read($pdo, $userId, $notifId);
    set_flash('success', 'Notification marked as read.');
    redirect('/notifications.php');
}
if ($action === 'read_all') {
    ensure_csrf();
    $pdo->prepare("UPDATE notifications SET status='read', read_at=? WHERE user_id=? AND status='unread'")
        ->execute([date('c'), $userId]);
    set_flash('success', 'All notifications marked as read.');
    redirect('/notifications.php');
}

// Fetch Notifications
$notifs = $pdo->prepare("SELECT * FROM notifications WHERE user_id=? ORDER BY created_at DESC LIMIT 50");
$notifs->execute([$userId]);
$rows = $notifs->fetchAll();

$meta = ['title' => 'Notifications | Go Legal'];
include __DIR__ . '/includes/header.php';
?>

<style>
.notif-card { background: #fff; border: 1px solid var(--border); border-radius: 16px; margin-bottom: 12px; padding: 20px; transition: transform 0.2s, box-shadow 0.2s; position: relative; overflow: hidden; }
.notif-card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
.notif-unread { border-left: 4px solid var(--primary); background: #f8fafc; }
.notif-unread .notif-dot { position: absolute; top: 12px; right: 12px; width: 8px; height: 8px; background: var(--primary); border-radius: 50%; }

.notif-icon { width: 40px; height: 40px; border-radius: 10px; background: #f1f5f9; color: #475569; display: flex; align-items: center; justify-content: center; font-size: 18px; flex-shrink: 0; }
.notif-unread .notif-icon { background: #ecfdf5; color: var(--primary); }

.notif-title { font-weight: 700; color: var(--text); margin-bottom: 4px; font-size: 15px; }
.notif-body { color: var(--muted); font-size: 14px; line-height: 1.5; margin-bottom: 12px; }
.notif-meta { display: flex; align-items: center; justify-content: space-between; font-size: 12px; color: var(--muted); }

.empty-state { text-align: center; padding: 80px 20px; }
.empty-icon { font-size: 48px; color: var(--border); margin-bottom: 16px; }
</style>

<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:32px">
    <div>
        <h1 style="margin:0; font-size:28px; font-weight:800; letter-spacing:-0.5px">Notifications</h1>
        <p style="margin:4px 0 0; color:var(--muted); font-size:15px">Stay updated with your application progress and account alerts.</p>
    </div>
    <?php if (!empty($rows)): ?>
    <form method="post" style="margin:0">
        <?=csrf_field()?>
        <input type="hidden" name="action" value="read_all">
        <button type="submit" class="btn" style="font-size:13px; font-weight:700">Mark All as Read</button>
    </form>
    <?php endif; ?>
</div>

<?php if (empty($rows)): ?>
    <div class="card empty-state">
        <div class="empty-icon"><?=ui_icon('faq', 48)?></div>
        <h3 style="margin:0; font-weight:700">No Notifications</h3>
        <p class="muted">You're all caught up! We'll notify you here when there's an update.</p>
    </div>
<?php else: ?>
    <div class="notif-list">
        <?php foreach ($rows as $n): 
            $isUnread = $n['status'] === 'unread';
            $type = $n['type'] ?? 'general';
            $icon = 'faq';
            if ($type === 'app_event') $icon = 'services';
            if ($type === 'payment') $icon = 'processing';
            if ($type === 'auth') $icon = 'logout';
        ?>
            <div class="notif-card <?=$isUnread?'notif-unread':''?>">
                <?php if($isUnread): ?><div class="notif-dot"></div><?php endif; ?>
                <div style="display:flex; gap:16px; align-items:flex-start">
                    <div class="notif-icon"><?=ui_icon($icon, 20)?></div>
                    <div style="flex:1">
                        <div class="notif-title"><?=e($n['title'] ?? 'Notification')?></div>
                        <div class="notif-body"><?=e($n['body'] ?? '')?></div>
                        <div class="notif-meta">
                            <span><?=date('M j, Y • H:i', strtotime($n['created_at']))?></span>
                            <?php if($isUnread): ?>
                                <form method="post" style="margin:0">
                                    <?=csrf_field()?>
                                    <input type="hidden" name="action" value="read">
                                    <input type="hidden" name="id" value="<?=e((string)$n['id'])?>">
                                    <button type="submit" class="btn" style="padding:4px 10px; font-size:11px; font-weight:700; background:transparent; border-color:var(--border)">Mark as Read</button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<?php include __DIR__ . '/includes/footer.php'; ?>
