<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/supabase.php';
require_once __DIR__ . '/../includes/auth.php';

$token = requireAuth();
$userId = getUserId($token);
$db = supabase($token);

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $limit = intval($_GET['limit'] ?? 50);
    $notifications = $db->get('notifications', [
        'user_id' => 'eq.' . $userId,
        'select' => 'id,type,title,title_ar,body,body_ar,is_read,created_at,data',
        'order' => 'created_at.desc',
        'limit' => $limit
    ]);

    if (!is_array($notifications) || isset($notifications['error'])) {
        jsonResponse(['notifications' => [], 'unread' => 0]);
    }

    $unread = count(array_filter($notifications, fn($n) => !$n['is_read']));
    jsonResponse(['notifications' => $notifications, 'unread' => $unread]);
}

if ($method === 'PATCH') {
    $input = getInput();
    $action = $input['action'] ?? 'read';

    if ($action === 'read') {
        $notifId = $input['id'] ?? null;
        if ($notifId) {
            $db->update('notifications', ['is_read' => true], ['id' => 'eq.' . $notifId, 'user_id' => 'eq.' . $userId]);
        } else {
            $db->update('notifications', ['is_read' => true], ['user_id' => 'eq.' . $userId, 'is_read' => 'eq.false']);
        }
        jsonResponse(['success' => true]);
    }
}

jsonError('Method not allowed', 405);
