<?php

namespace App\Livewire\Buttons;

use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Livewire\Component;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;

class UpdatePhotoSlider extends Component
{
    use WithFileUploads;

    public $uuid;
    public $title;
    public $description;
    public $start_date;
    public $end_date;
    public $start_time;
    public $end_time;
    public $image; // For uploaded file
    public $existingImage; // For image from backend

    public $promotions = [];
    public $promotion_id;

    public function mount($uuid)
    {
        $this->uuid = $uuid;
        $token = Session::get('user')['access_token'] ?? null;

        if (!$token) {
            $this->addError('auth', 'No access token found.');
            return;
        }

        // Fetch promotions
        $promoResponse = Http::withToken($token)->get(config('services.backend_api.url') . '/api/cms/photoSlider');
        if ($promoResponse->successful()) {
            $this->promotions = $promoResponse->json('data');
        } else {
            $this->addError('promotions', 'Failed to load promotions.');
        }

        // Fetch specific photo slider
        $sliderResponse = Http::withToken($token)->get(config('services.backend_api.url') . "/api/cms/photoSlider/{$uuid}");
        if ($sliderResponse->successful()) {
            $data = $sliderResponse->json('data');

            $this->title = $data['title'] ?? '';
            $this->description = $data['description'] ?? '';
            $this->start_date = $data['start_date'] ?? '';
            $this->end_date = $data['end_date'] ?? '';
            $this->existingImage = $data['image'] ?? ''; // Store image path only
            $this->promotion_id = $data['promotion_id'] ?? '';
        } else {
            $this->addError('users', 'Failed to fetch photo slider.');
        }
    }

    public function submit()
    {

        $this->validate([
            'start_date'   => 'required|date',
            'end_date'     => 'required|date|after_or_equal:start_date',
        ]);

        $token = Session::get('user')['access_token'] ?? null;

        if (!$token) {
            $this->addError('users', 'No access token found.');
            return;
        }

        if (!$this->image instanceof TemporaryUploadedFile) {
            $this->addError('image', 'Please upload an image.');
            return;
        }

        $response = Http::withToken($token)
            ->attach(
                'image',
                file_get_contents($this->image->getRealPath()),
                $this->image->getClientOriginalName()
            )
            ->post(config('services.backend_api.url') . '/api/cms/updatePhotoSlider/' . $this->uuid, [
                'promotion_uuid' => $this->promotion_id,
                'title'          => $this->title,
                'description'    => $this->description,
                'date_start'     => $this->start_date,
                'date_end'       => $this->end_date,
            ]);

            dd($response->json());

        if ($response->status() === 422) {
            $errors = $response->json('data');
            foreach ($errors as $field => $messages) {
                $this->addError($field, $messages[0]);
            }
            return;
        }

        if ($response->successful()) {
            session()->flash('success', 'Photo slider updated successfully.');
            return redirect('/main/home-page-mobile/photo-slider');
        } else {
            $this->addError('photo_slider', 'Failed to update photo slider.');
        }
    }

    public function cancel()
    {
        return redirect()->to('/main/home-page-mobile/photo-slider');
    }

    public function render()
    {
        return view('livewire.buttons.update-photo-slider');
    }
}
