<?php

namespace App\Livewire;

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(env('BACKEND_API_URL') . '/api/login_password', [
                'username' => $this->username,
                'password' => $this->password,
            ]);
    
            if ($response->successful()) {
                $json = $response->json();
    
                if ($json['code'] === 200) {
                    // Store UUID in session if needed
                    Session::put('admin_uuid', $json['data']['admin_uuid'] ?? null);
    
                    // Redirect if user must change password
                    if (!empty($json['data']['prompt_password'])) {
                        return redirect('/api/login_changePassword');
                    }
    
                    // Redirect to profile after successful login
                    return redirect('/main/profile');
                } else {
                    $this->addError('username', $json['message'] ?? 'Login failed.');
                }
            } else {
                $this->addError('username', 'Login request failed. Please try again.');
            }
        } catch (\Exception $e) {
            $this->addError('username', 'An error occurred: ' . $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
    }

}