<?php

namespace App\Http\Controllers;

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

class NotificationController extends Controller
{
    protected $apiBaseUrl = 'http://192.168.100.6:8081/api';

 public function index(Request $request)
{
    try {
        $user = Session::get('user');
        $accessToken = $user['access_token'] ?? null;

        if (!$accessToken) {
            Log::info('No access token found, redirecting to login from notification');
            return redirect()->route('login')->with('error', 'Please log in to view notifications.');
        }

        // Fetch all notifications directly from the API
        $response = Http::withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $accessToken,
        ])->get("{$this->apiBaseUrl}/cms/notification");

        $json = $response->json();
        Log::info("Response from index endpoint: ", $json);

        $notifications = [];
        if ($response->status() === 401 || $response->status() === 403) {
            Log::warning('Unauthorized or Forbidden API response for index endpoint: ', $json);
            return redirect()->route('login')->with('error', 'Your session has expired. Please log in again.');
        }

        if ($response->successful() && isset($json['data']) && is_array($json['data'])) {
            $notifications = array_map(function ($notification) {
                return [
                    'id' => $notification['id'] ?? null,
                    'subject' => $notification['subject'] ?? 'Untitled',
                    'description' => $notification['description'] ?? '',
                    'isScheduled' => $notification['trigger_schedule'] ? 'Scheduled' : 'Not Scheduled',
                    'schedule' => $notification['trigger_schedule'] ?? '',
                    'expiration' => $notification['expiration_date'] ?? '',
                ];
            }, $json['data']);
        } else {
            Log::warning('Failed to fetch notifications: ', $json);
        }

        // Update session with the fetched notification IDs (optional, for future use)
        $notificationIds = array_column($notifications, 'id');
        Session::put('notification_ids', $notificationIds);

        return view('pages.notification', [
            'notifications' => $notifications,
        ])->with('error', empty($notifications) ? 'No notification data available. Please create a new notification.' : '');
    } catch (\Exception $e) {
        Log::error('Error fetching notification data: ' . $e->getMessage());
        return view('pages.notification', [
            'notifications' => [],
        ])->with('error', 'An error occurred while fetching notifications: ' . $e->getMessage());
    }
}
    public function create()
    {
        return view('pages.add-notification');
    }

    public function store(Request $request)
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

            if (!$accessToken) {
                return redirect()->route('login')->with('error', 'Please log in to add a notification.');
            }

            $data = [
                'subject' => $request->input('subject'),
                'description' => $request->input('description'),
                'schedule' => $request->input('schedule') ?: null,
                'expiration' => $request->input('expiration') ?: null,
            ];

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->post("{$this->apiBaseUrl}/cms/notification", $data);

            if ($response->successful()) {
                return redirect()->route('notification')->with('success', 'Notification created successfully.');
            } else {
                Log::warning('Failed to create notification: ', $response->json());
                return redirect()->back()->with('error', $response->json()['message'] ?? 'Failed to create notification. Please try again.');
            }
        } catch (\Exception $e) {
            Log::error('Error creating notification: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while creating the notification: ' . $e->getMessage());
        }
    }

    public function edit($id)
    {
        return redirect()->route('notification')->with('error', 'Edit functionality is not available due to backend limitations.');
    }

    public function update(Request $request, $id)
    {
        return redirect()->route('notification')->with('error', 'Update functionality is not available due to backend limitations.');
    }

    public function show($id)
    {
        return redirect()->route('notification')->with('error', 'View functionality is not available due to backend limitations.');
    }

    public function destroy($id)
    {
        return redirect()->route('notification')->with('error', 'Delete functionality is not available due to backend limitations.');
    }
}