<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    // =====================
    // FORM LOGIN
    // =====================
    public function showLogin()
    {
        return view('auth.login');
    }

    // =====================
    // PROSES LOGIN
    // =====================
    public function login(Request $request)
    {
        // VALIDASI
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        // CEK LOGIN
        if (Auth::attempt($request->only('email', 'password'))) {

            $request->session()->regenerate();

            // AMBIL ROLE
            $role = Auth::user()->role;

            // REDIRECT BERDASARKAN ROLE
            switch ($role) {

                case 'admin':
                    return redirect()->route('admin.dashboard');

                case 'ekspedisi':
                    return redirect()->route('ekspedisi.dashboard');

                case 'customer':
                default:
                    return redirect()->route('customer.dashboard');
            }
        }

        // JIKA GAGAL LOGIN
        return back()->with('error', 'Email atau password salah');
    }

    // =====================
    // FORM REGISTER
    // =====================
    public function showRegister()
    {
        return view('auth.register');
    }

    // =====================
    // PROSES REGISTER
    // =====================
    public function register(Request $request)
    {
        // VALIDASI
        $request->validate([
            'nama' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:6|confirmed'
        ]);

        // SIMPAN USER
        User::create([
            'nama' => $request->nama,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => 'customer' // default
        ]);

        return redirect()->route('login')
            ->with('success', 'Registrasi berhasil, silakan login');
    }

    // =====================
    // LOGOUT
    // =====================
    public function logout(Request $request)
    {
        Auth::logout();

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

        return redirect()->route('login');
    }
}