<?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 PhotoSliderController 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 photo-slider');
                return redirect()->route('login')->with('error', 'Please log in to view photo sliders.');
            }

            $page = $request->input('page', 1);
            $pageSize = 5;

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

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

            $json = $response->json();

            Log::info("PhotoSlider API Response (Page {$page}): ", $json);

            if ($response->successful() && isset($json['data']) && is_array($json['data'])) {
                $sliders = array_map(function ($slider) {
                    Log::info('Processing photo slider record: ', $slider);
                    return [
                        'photoslider_uuid' => $slider['photoslider_uuid'] ?? $slider['id'] ?? null,
                        'title' => $slider['title'] ?? 'Untitled',
                        'type' => $slider['promo_type'] ?? 'Unknown',
                        'startDate' => $slider['date_start'] ?? null,
                        'endDate' => $slider['date_end'] ?? null,
                        'isActive' => $slider['is_active'] ?? 0,
                        'image' => $slider['image'] ?? null, // Include image field
                    ];
                }, $json['data']);

                $total = $json['meta']['total'] ?? count($sliders);
                $lastPage = $json['meta']['last_page'] ?? ceil($total / $pageSize);

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

    public function create()
    {
        return view('pages.photo-slider-create');
    }

    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 photo slider.');
            }

            // Validate the request
            $request->validate([
                'image' => 'required|file|mimes:jpeg,png,jpg,gif|max:2048', // Adjust max size as needed
            ]);

            $data = [
                'title' => $request->input('title'),
                'description' => $request->input('description'),
                'promo_type' => $request->input('type'),
                'date_start' => $request->input('startDate'),
                'date_end' => $request->input('endDate'),
                'is_active' => $request->input('isActive', 0),
            ];

            // Attach the image file
            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->attach(
                'image', file_get_contents($request->file('image')->getRealPath()), $request->file('image')->getClientOriginalName()
            )->post("{$this->apiBaseUrl}/cms/photoSlider", $data);

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

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

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

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

            $json = $response->json();

            if ($response->successful() && isset($json['data'])) {
                $slider = [
                    'photo_slider_uuid' => $json['data']['photoslider_uuid'] ?? $json['data']['id'] ?? null,
                    'title' => $json['data']['title'] ?? 'Untitled',
                    'description' => $json['data']['description'] ?? '',
                    'type' => $json['data']['promo_type'] ?? 'Unknown',
                    'startDate' => $json['data']['date_start'] ?? null,
                    'endDate' => $json['data']['date_end'] ?? null,
                    'isActive' => $json['data']['is_active'] ?? 0,
                    'image' => $json['data']['image'] ?? null,
                ];
                return view('pages.photo-slider-edit', ['slider' => $slider]);
            } else {
                Log::warning('No photo slider found or invalid API response: ', $json);
                return redirect()->route('photo-slider')->with('error', 'Photo slider not found.');
            }
        } catch (\Exception $e) {
            Log::error('Error fetching photo slider for edit: ' . $e->getMessage());
            return redirect()->route('photo-slider')->with('error', 'An error occurred while loading the photo slider.');
        }
    }

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

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

            // Validate the request (image is optional for updates)
            $request->validate([
                'image' => 'nullable|file|mimes:jpeg,png,jpg,gif|max:2048',
            ]);

            $data = [
                'title' => $request->input('title'),
                'description' => $request->input('description'),
                'promo_type' => $request->input('type'),
                'date_start' => $request->input('startDate'),
                'date_end' => $request->input('endDate'),
                'is_active' => $request->input('isActive', 0),
            ];

            $client = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ]);

            // Attach the image if provided
            if ($request->hasFile('image')) {
                $client = $client->attach(
                    'image',
                    file_get_contents($request->file('image')->getRealPath()),
                    $request->file('image')->getClientOriginalName()
                );
            }

            $response = $client->post("{$this->apiBaseUrl}/cms/updatePhotoSlider/{$uuid}", $data);

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

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

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

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

            $json = $response->json();

            if ($response->successful() && isset($json['data'])) {
                $slider = [
                    'photo_slider_uuid' => $json['data']['photoslider_uuid'] ?? $json['data']['id'] ?? null,
                    'title' => $json['data']['title'] ?? 'Untitled',
                    'description' => $json['data']['description'] ?? '',
                    'type' => $json['data']['promo_type'] ?? 'Unknown',
                    'startDate' => $json['data']['date_start'] ?? null,
                    'endDate' => $json['data']['date_end'] ?? null,
                    'isActive' => $json['data']['is_active'] ?? 0,
                    'image' => $json['data']['image'] ?? null,
                ];
                return view('pages.photo-slider-view', ['slider' => $slider]);
            } else {
                Log::warning('No photo slider found or invalid API response: ', $json);
                return redirect()->route('photo-slider')->with('error', 'Photo slider not found.');
            }
        } catch (\Exception $e) {
            Log::error('Error fetching photo slider for view: ' . $e->getMessage());
            return redirect()->route('photo-slider')->with('error', 'An error occurred while loading the photo slider.');
        }
    }

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

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

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

            if ($response->successful()) {
                return redirect()->route('photo-slider')->with('success', 'Photo slider deleted successfully.');
            } else {
                Log::warning('Failed to delete photo slider: ', $response->json());
                return redirect()->back()->with('error', 'Failed to delete photo slider. Please try again.');
            }
        } catch (\Exception $e) {
            Log::error('Error deleting photo slider: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while deleting the photo slider.');
        }
    }

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

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

            $uuids = $request->input('photoslider_uuid');

            if (!is_array($uuids) || empty($uuids)) {
                return redirect()->back()->with('error', 'No photo sliders selected for deletion.');
            }

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

            if ($response->successful()) {
                return redirect()->route('photo-slider')->with('success', 'Photo sliders deleted successfully.');
            } else {
                Log::warning('Failed to batch delete photo sliders: ', $response->json());
                return redirect()->back()->with('error', 'Failed to delete photo sliders. Please try again.');
            }
        } catch (\Exception $e) {
            Log::error('Error batch deleting photo sliders: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while deleting photo sliders.');
        }
    }
}