<?php

namespace App\Livewire\Buttons;

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

class UpdateTermsAndPrivacy extends Component
{
    public $uuid;
    public $title;
    public $details;
    public $type;

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

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

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

            $this->title = $data['title'] ?? '';
            $this->details = $data['details'] ?? '';
            $this->type = $data['type'] ?? '';


        } else {
            $this->addError('terms and privacy', 'Failed to fetch terms and privacy.');
        }
    }


    public function submit()
    {

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


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

        $response = Http::withToken($token)->put(config('services.backend_api.url') . '/api/cms/TermsAndPrivacy/'. $this->uuid, [
            '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 updated successfully.');
            return redirect('/main/about-us/terms-and-privacy');
        } else {
            $this->addError('terms and privacy', 'Failed to update user.');
        }
    }

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

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