<?php

namespace App\Livewire\Buttons;

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

class CreateTermsAndPrivacy extends Component
{
    public $title;
    public $details;
    public $type = 1;
    
    public function submit()
    {

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


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

        $response = Http::withToken($token)->post(config('services.backend_api.url') . '/api/cms/TermsAndPrivacy', [
            'title'   => $this->title,
            'details'  => $this->details,
            'type'   => $this->type,
        ]);


        //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', 'terms and privacy created successfully.');
            return redirect('/main/about-us/terms-and-privacy');
        } else {
            $this->addError('terms and privacy', 'Failed to create user.');
        }
    }

    public function cancel()
    {
        return redirect()->to('/main/about-us/terms-and-privacy');
    }

    public function render()
    {
        return view('livewire.buttons.create-terms-and-privacy');
    }
}
