<?php

namespace App\Livewire\Buttons;

use Livewire\Component;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Livewire\WithFileUploads;

class CreateCardType extends Component
{
    use WithFileUploads;

    //card type details
    public $card_code;
    public $card_name;
    public $card_description;
    public $card_image;
    public $card_cover_image;
    public $card_font_color = 0;
    public $id_number = 0;
    public $id_description;

    //image preview handler
    public $type_image;
    public $cover_image;

    //data privacy
    public $terms_condition;
    public $faqs;


    public function submit()
    {

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


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

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

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

        $response = Http::withToken($token)
            ->attach(
                'image',                             //card type image
                file_get_contents($this->card_image->getRealPath()),
                $this->card_image->getClientOriginalName()
            )
            ->attach(
                'bg_image',                            //card type cover image
                file_get_contents($this->card_cover_image->getRealPath()),
                $this->card_cover_image->getClientOriginalName()
            )
            ->post(config('services.backend_api.url') . '/api/cms/cardType', [
                'code'   => $this->card_code,
                'type'   => $this->card_name,
                'description'   => $this->card_description,
                'virtual_card_font_color'       => $this->card_font_color,
                'id_number'   => $this->id_number,
                'id_number_description'   => $this->id_description,
                'terms_and_conditions'     => $this->terms_condition,
                'faqs'       => $this->faqs,
            ]);

        // 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', 'Card type created successfully.');
            return redirect('/main/about-us/card-type');
        } else {
            $this->addError('card types', 'Failed to create card type.');
        }
    }

    public function cancel()
    {
        return redirect()->to('/main/about-us/card-type');
    }
    public function render()
    {
        return view('livewire.buttons.create-card-type');
    }
}
