<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use GuzzleHttp\Client;

class AuthController extends Controller
{

    public function createLogin()
    {
        return view('auth.login');
    }

    public function storeLogin(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string', 'min:8'],
        ]);

        if (auth()->attempt($credentials)) {
            $request->session()->regenerate();

            return match (auth()->user()->role->name) {
                'admin' => redirect()->route('admin.dashboard'),
                'mahasiswa' => redirect()->route('mahasiswa.dashboard'),
                default => redirect()->route('guest.index'),
            };
        }

        return back()->withErrors([
            'email' => 'Email tidak terdaftar. Harap register terlebih dahulu.',
            'password' => 'Password salah. Silakan coba lagi.',
        ]);
    }

    public function createRegister()
    {
        return view('auth.register');
    }

    public function storeRegister(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'name' => ['required', 'string', 'max:255'],
            'no_id' => ['required', 'string', 'max:30', 'unique:users,no_id'],
            'no_hp' => ['required', 'string', 'max:20'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $client = new Client();

        try {
            $response = $client->get(config('services.api.base_url').'/mahasiswa/nim/'.$request->no_id, [
                'headers' => [
                    'Authorization' => 'Bearer ' . config('services.api.token'),
                ]
            ]);

            $data = json_decode($response->getBody(), true);

            $mahasiswa = $data['data'][0] ?? null;

            if (!$mahasiswa || empty($mahasiswa['nim'])) {
                return back()->withErrors([
                    'no_id' => 'NPM tidak ditemukan. Silakan periksa kembali atau hubungi admin.',
                ])->withInput();
            }
            $user = User::create([
                'no_id' => $mahasiswa['nim'],
                'name' => $mahasiswa['nama_mahasiswa'],
                'email' => $mahasiswa['email'],
                'program_studi' => $mahasiswa['prodi'],
                'no_hp' => $request->no_hp,
                'password' => bcrypt($request->password),
                'role_id' => 2,
            ]);

            auth()->login($user);

            return redirect()->route('mahasiswa.dashboard');
        } catch (\Throwable $e) {
            return back()->withErrors([
                'no_id' => 'Gagal menghubungi API: '.$e->getMessage(),
            ])->withInput();
        }
    }

    public function logout(Request $request)
    {
        auth()->logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/');
    }
}
