<?php

namespace App\Livewire\Buttons;

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

class UpdatePromotion extends Component
{
    use WithFileUploads;
    //wire models
    public $uuid;
    public $title;
    public $description;
    public $image;
    public $start_date;
    public $end_date;
    public $start_time;
    public $end_time;
    public $is_toppromotion = 0;
    public $is_gps = 0;
    public $promo_type = 1;

    public $existingImage; // For image from backend

    //get all stations
    public $stations = [];
    public $selectedStation = '';

    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 specific photo slider
        $sliderResponse = Http::withToken($token)->get(config('services.backend_api.url') . "/api/cms/promotion/{$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->is_toppromotion = $data['is_toppromotion'] ?? '';
            $this->is_gps = $data['is_gps'] ?? '';
            $this->promo_type = $data['promo_type'] ?? '';
        } else {
            $this->addError('users', 'Failed to fetch promotion.');
        }
    }

    public function submit()
    {

        $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',                      // field name expected by backend
                file_get_contents($this->image->getRealPath()),  // file content
                $this->image->getClientOriginalName()            // original filename
            )
            ->post(config('services.backend_api.url') . '/api/cms/updatePromotion/' . $this->uuid, [
                'title'         => $this->title,
                'description'   => $this->description,
                'date_start'    => $this->start_date,
                'date_end'      => $this->end_date,
                'is_toppromotion' => $this->is_toppromotion,
                'is_gps'          => $this->is_gps,
                'promo_type'      => $this->promo_type,
            ]);

        // dd($response->json());   

        //handle backend response
        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', 'Promotoin updated successfully.');
            return redirect('/main/main/promotion');
        } else {
            $this->addError('promotions', 'Failed to update promotion.');
        }
    }

    public function cancel()
    {
        return redirect()->to('/main/home-promotion/promotion');
    }
    public function render()
    {
        return view('livewire.buttons.update-promotion');
    }
}
