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

header('Content-Type: application/json');

$token = get_auth_token();

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'unauthorized']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $res = supabase_rest('GET', 'notifications?select=*&order=created_at.desc&limit=50', [], $token);
    echo json_encode(['notifications' => $res['data'] ?? []]);
} elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';

    if ($action === 'read_all') {
        supabase_rest('PATCH', 'notifications?read_at=is.null', [
            'read_at' => date('c')
        ], $token);
        echo json_encode(['ok' => true]);
    } elseif ($action === 'read') {
        $id = $input['id'] ?? '';
        supabase_rest('PATCH', "notifications?id=eq.{$id}", [
            'read_at' => date('c')
        ], $token);
        echo json_encode(['ok' => true]);
    } else {
        echo json_encode(['error' => 'invalid action']);
    }
}
