<?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 $showForgotUsernameModal = false;

    public function forgotUsername()
    {
        $this->showForgotUsernameModal = true;
    }

    public function closeForgotUsernameModal()
    {
        $this->showForgotUsernameModal = false;
    }

    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,
            ]);

            $data = $response->json();


            if ($response->successful() && $data['code'] === 200) {
                $isPasswordChange = $data['data']['prompt_password'] ?? 0;

                Session::put('user', [
                    'admin' => $data['data']['admin'] ?? null,
                    'access_token' => $data['data']['token'] ?? null,
                    'is_passwordChange' => $isPasswordChange,
                    'admin_uuid' => $data['data']['admin_uuid'] ?? null,
                ]);

                if ($isPasswordChange) {
                    return $this->redirect('change-password');
                } else {
                    return $this->redirect('/main/profile');
                }
            } else {
                $message = $data['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
    }
}
