<?php

require_once __DIR__ . '/helpers.php';
api_require_login();

function get_notification_page(string $passType, string $transactionRef): string
{
    if ($passType === 'Personnel Pass') {
        return 'employees.php?ref=' . urlencode($transactionRef);
    }

    if ($passType === 'Visitor Pass') {
        return 'visitors.php?ref=' . urlencode($transactionRef);
    }

    if ($passType === 'Item Pass') {
        return 'packages.php?ref=' . urlencode($transactionRef);
    }

    if ($passType === 'Food Pass') {
        return 'items.php?ref=' . urlencode($transactionRef);
    }

    if ($passType === 'Meal Break Pass') {
        return 'mealbreak.php?ref=' . urlencode($transactionRef);
    }

    return 'dashboard.php';
}

try {
    $action = $_GET['action'] ?? 'list';

    if ($action === 'read') {
        db_execute($conn, "UPDATE notifications SET is_read = 1 WHERE is_read = 0");

        json_response([
            'success' => true,
            'message' => 'Notifications marked as read.'
        ]);
    }

    $unreadCount = (int) db_value($conn, "
        SELECT COUNT(*) FROM notifications
        WHERE is_read = 0
    ");

    $rows = db_all($conn, "
        SELECT id, pass_type, transaction_ref, message, is_read, created_at
        FROM notifications
        ORDER BY created_at DESC
        LIMIT 20
    ");

    $notifications = [];

    foreach ($rows as $row) {
        $row['target_page'] = get_notification_page(
            $row['pass_type'],
            $row['transaction_ref']
        );

        $notifications[] = $row;
    }

    json_response([
        'success' => true,
        'unread_count' => $unreadCount,
        'notifications' => $notifications
    ]);

} catch (Throwable $e) {
    json_response([
        'success' => false,
        'message' => 'Unable to load notifications.'
    ], 500);
}