<?php
// restaurantadmin/ajax/notifications.php
// Powers the notification bell dropdown in includes/header.php
session_start();
include("../config/db.php");
header('Content-Type: application/json');

$allowed = ['restaurant_admin','staff','waiter'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role']??'', $allowed)) {
    echo json_encode([]); exit;
}

$uid = (int)$_SESSION['user_id'];
$u = $conn->prepare("SELECT restaurant_id FROM users WHERE id=?");
$u->bind_param("i",$uid); $u->execute();
$rid = (int)($u->get_result()->fetch_assoc()['restaurant_id'] ?? 0);

if (!$rid) { echo json_encode([]); exit; }

$action = $_GET['action'] ?? '';

if ($action === 'read' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = $conn->prepare("UPDATE notifications SET is_read=1 WHERE id=? AND restaurant_id=?");
    $stmt->bind_param("ii",$id,$rid); $stmt->execute();
    echo json_encode(["ok"=>true]); exit;
}

if ($action === 'read_all') {
    $stmt = $conn->prepare("UPDATE notifications SET is_read=1 WHERE restaurant_id=?");
    $stmt->bind_param("i",$rid); $stmt->execute();
    echo json_encode(["ok"=>true]); exit;
}

// Fetch latest 20 notifications
$stmt = $conn->prepare("SELECT * FROM notifications WHERE restaurant_id=? ORDER BY created_at DESC LIMIT 20");
$stmt->bind_param("i",$rid); $stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);
