<?php

namespace App\Livewire;

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

class Header extends Component
{
    public $user;
    public $dropdownOpen = false;

    public function mount()
    {
        $this->user = Session::get('user');
    }

    public function toggleDropdown()
    {
        $this->dropdownOpen = !$this->dropdownOpen;
    }

    public function logout()
    {
        $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/logout');

        if ($response->successful()) {
            Session::forget('user');
            session()->flash('success', 'Logout successfully.');
            return redirect()->route('login');
        } else {
            // Optional: flash an error or handle it
            logger()->error('Logout failed:', [
                'status' => $response->status(),
                'error' => $response->json(),
            ]);
            session()->flash('error', 'Logout failed.');
        }
    }

    public function render()
    {
        return view('livewire.header.header');
    }
}


