<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class NotificationController extends Controller
{
    /**
     * Mendapatkan URL API.
     */
    protected function apiUrl($endpoint)
    {
        return rtrim(env('BACKEND_API_URL'), '/') . '/' . ltrim($endpoint, '/');
    }

    /**
     * Mengambil daftar notifikasi dari Backend.
     */
    public function getNotifications()
    {
        if (!session()->has('api_token')) {
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 401);
        }

        $response = Http::withToken(session('api_token'))
            ->get($this->apiUrl('/notifications'));

        if ($response->successful()) {
            return response()->json($response->json());
        }

        return response()->json(['success' => false, 'message' => 'Gagal memuat notifikasi'], 500);
    }

    /**
     * Menandai semua notifikasi telah dibaca di Backend.
     */
    public function markAsRead()
    {
        if (!session()->has('api_token')) {
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 401);
        }

        $response = Http::withToken(session('api_token'))
            ->post($this->apiUrl('/notifications/read'));

        if ($response->successful()) {
            return response()->json($response->json());
        }

        return response()->json(['success' => false, 'message' => 'Gagal menandai telah dibaca'], 500);
    }
}
