<?php
namespace App\Http\Controllers;

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

class PhotoSliderViewController extends Controller
{
    protected $apiBaseUrl;

    public function __construct()
    {
        $this->apiBaseUrl = config('services.api.base_url'); // put your base URL in config/services.php
    }

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

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

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

            $json = $response->json();
            Log::info('Photo Slider API Response: ', $json);

            if ($response->successful() && isset($json['data']) && is_array($json['data'])) {
                $sliders = array_map(function ($slider) {
                    return [
                        'id' => $slider['id'],
                        'title' => $slider['title'],
                        'type' => $slider['type'],
                        'startDate' => $slider['start_date'],
                        'endDate' => $slider['end_date'],
                    ];
                }, $json['data']);

                return view('pages.home page.photo-slider', [
                    'sliders' => $sliders,
                ]);
            } else {
                Log::warning('No slider data found or invalid API response: ', $json);
                return view('pages.home page.photo-slider', ['sliders' => []]);
            }
        } catch (\Exception $e) {
            Log::error('Error fetching photo slider data: ' . $e->getMessage());
            return view('pages.home page.photo-slider', ['sliders' => []]);
        }
    }
}
