<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;

class AuthController extends Controller
{
    public function showLoginForm()
    {
        return view('login');
    }

    public function authenticate(Request $request)
    {
        $request->validate([
            'username' => 'required',
            'password' => 'required',
        ]);

          $data = [
            'grant_type' => 'password',
            'username'   => $request->username,
            'password'   => $request->password,
        ];
        $response = Http::asForm()->post('https://intersolid.ellevocloud.com/api/seguranca/token', $data);

        if ($response->successful()) {
            $data = $response->json();

            Session::put('access_token', $data['access_token']);
            Session::put('token_type', $data['token_type']);
            Session::put('expires_in', $data['expires_in']);

            return redirect()->route('dashboard')->with('success', 'Login realizado com sucesso!');
        }

        return back()->withErrors(['login_error' => 'Credenciais inválidas ou falha na API.']);
    }

    public function dashboard()
    {
        $accessToken = Session::get('access_token');

        return view('dashboard', ['accessToken' => $accessToken]);
    }

    public function logout()
    {
        Session::forget('access_token');
        return redirect()->route('login');
    }
}
