<?php

namespace App\Livewire\Buttons;

use Livewire\Component;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
class ViewPromotion extends Component
{
    public $uuid;
    public $image,
        $stations,
        $title,
        $description,
        $is_toppromotion,
        $is_gps,
        $status,
        $promo_type,
        $date_start,
        $date_end,
        $start_time,
        $end_time,
        $created_by,
        $updated_by,
        $created_at,
        $updated_at;

        public function mount($uuid)
    {
        $this->uuid = $uuid;

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

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

        $response = Http::withToken($token)->get(config('services.backend_api.url') . "/api/cms/promotion/{$uuid}");

        if ($response->successful()) {
            $promotions = $response->json('data');

            $this->image = $promotions['image'] ?? '';
            $this->title = $promotions['title'] ?? '';
            $this->stations = "All";
            $this->is_toppromotion = $promotions['is_toppromotion'] ?? '';
            $this->is_gps = $promotions['is_gps'] ?? '';
            $this->status = $promotions['status'] ?? '';
            $this->promo_type = $promotions['promo_type']["name"] ?? '';
            $this->description = $promotions['description'] ?? '';
            $this->date_start = isset($promotions['date_start']) ? Carbon::parse($promotions['date_start'])->format('F j, Y') : '';
            $this->date_end = isset($promotions['date_end']) ? Carbon::parse($promotions['date_end'])->format('F j, Y') : '';
            $this->start_time = '00:00:00';
            $this->end_time = '23:59:00';
            $this->created_by = $promotions['created_by'] ?? '';
            $this->updated_by = $promotions['updated_by'] ?? '';
            $this->created_at = isset($promotions['created_at']) ? Carbon::parse($promotions['created_at'])->format('F j, Y g:i A') : '';
            $this->updated_at = isset($promotions['updated_at']) ? Carbon::parse($promotions['updated_at'])->format('F j, Y g:i A') : '';
        } else {
            $this->addError('promotions', 'Failed to fetch promotion data.');
        }
    }

    public function render()
    {
        return view('livewire.buttons.view-promotion');
    }
}
