<?php
// backend/api/notifications.php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

$input = json_decode(file_get_contents('php://input'), true);
$token = getAuthToken();
$user = getUserFromToken($token);

if (!$user) {
    errorResponse('User not authenticated', 401);
}

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

try {
    if ($action === 'list') {
        $stmt = $pdo->prepare("SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 20");
        $stmt->execute([$user['id']]);
        $notifications = $stmt->fetchAll();
        
        // Count unread
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0");
        $stmt->execute([$user['id']]);
        $unreadCount = $stmt->fetch()['count'];

        jsonResponse([
            'notifications' => $notifications,
            'unread_count' => $unreadCount
        ]);
    } else if ($action === 'mark_read') {
        $id = $input['id'] ?? null;
        if ($id) {
            $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE id = ? AND user_id = ?");
            $stmt->execute([$id, $user['id']]);
        } else {
            // Mark all valid for this user
            $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = ?");
            $stmt->execute([$user['id']]);
        }
        jsonResponse(['success' => true]);
    } else if ($action === 'create' && isAdmin($user['id'])) {
        // Admin can create notification for testing
        $userId = $input['user_id'] ?? $user['id']; // Default to self
        $type = $input['type'] ?? 'info';
        $message = $input['message'] ?? 'Test notification';
        
        $id = generateUUID();
        $stmt = $pdo->prepare("INSERT INTO notifications (id, user_id, type, message, created_at) VALUES (?, ?, ?, ?, datetime('now'))");
        $stmt->execute([$id, $userId, $type, $message]);
        
        jsonResponse(['success' => true, 'id' => $id]);
    } else {
        errorResponse('Invalid action', 400);
    }
} catch (Exception $e) {
    errorResponse('Error: ' . $e->getMessage(), 500);
}
?>
