<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/config.php';

$auth = new Auth();
$auth->requireLogin();

if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {
    jsonResponse(false, 'Invalid request');
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$csrf = new CSRF();
$userId = $auth->userId();
$restaurantId = $auth->restaurantId();
$notif = new Notification();

if ($action === 'pending_orders') {
    $db = Database::getInstance();
    $result = $db->query("SELECT COUNT(*) as cnt FROM orders WHERE restaurant_id = ? AND order_status = 'new'", [$restaurantId])->fetch();
    jsonResponse(true, 'ok', ['count' => (int)$result['cnt']]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (empty($_POST['csrf_token']) || !$csrf->verify($_POST['csrf_token'])) {
        jsonResponse(false, 'Invalid CSRF token');
    }

    if ($action === 'mark_all_read') {
        $notif->markAllAsRead($userId);
        jsonResponse(true, 'Notifications marked as read');
    }

    jsonResponse(false, 'Invalid action');
}

$notifications = $notif->getUnread($userId, 10);
$count = $notif->getUnreadCount($userId);

jsonResponse(true, 'ok', ['notifications' => $notifications, 'unread_count' => $count]);
