<?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
{
    // 1. Tampilkan Halaman Login
    public function showLogin()
    {
        return view('auth.login');
    }

    // 2. Proses Login
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();
            
            // Redirect berdasarkan Role
            if (auth()->user()->role === 'admin') {
                return redirect()->route('dashboard')->with('success', 'Selamat Datang Admin!');
            }
            
            return redirect()->intended('/')->with('success', 'Login Berhasil!');
        }

        return back()->withErrors([
            'email' => 'Email atau password salah.',
        ])->onlyInput('email');
    }

    // 3. Tampilkan Halaman Register
    public function showRegister()
    {
        return view('auth.register');
    }

    // 4. Proses Register
  public function register(Request $request)
{
    $request->validate([
        'name' => 'required|string|max:255',
        'phone' => 'required|string|max:15|unique:users', // Tambahkan validasi phone
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:8|confirmed',
    ]);

    User::create([
        'name' => $request->name,
        'phone' => $request->phone, // Simpan ke database
        'email' => $request->email,
        'password' => Hash::make($request->password),
        'role' => 'pelanggan',
    ]);

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

    // 5. Proses Logout
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/');
    }
}