<?php

namespace App\Livewire;

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

class LoginForm extends Component
{
    public $username, $password;

    public function submit()
    {
        $this->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);
    
        try {
            $response = Http::post(config('services.backend_api.url') . '/api/cms/login_password', [
                'username' => $this->username,
                'password' => $this->password,
            ]);
        

            $json = $response->json();

            // dd($json);
        
            if ($response->successful()) {
                if ($json['code'] === 200) {
                    Session::put('user', [
                        'admin' => $json['data']['admin'] ?? null,
                        'access_token' => $json['data']['token'] ?? null,
                    ]);                    
                    // dd(Session::get('user')); // right before redirect

        
                    return $this->redirect('/main/profile');
                } else {
                    $this->addError('username', $json['message'] ?? 'Login failed.');
                }
            } else {
                $message = $json['message'] ?? 'Login request failed. Please try again.';
                $this->addError('username', $message);
            }
        } catch (\Exception $e) {
            $this->addError('username', 'An error   : ' . $e->getMessage());
        }
        
    }

    public function render()
    {
        return view('livewire.auth.login-form'); // This will point to the resource/views/livewire/auth/login-form.blade.php component
    }

}