<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; // Pastikan Model User diimport
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    // --- LOGIN ---
    public function showLoginForm()
    {
        return view('auth.login');
    }

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

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

            // SESUAIKAN DENGAN DATABASE LU:
            // Cek apakah kolom is_admin bernilai 1
            if (Auth::user()->is_admin == 1) {
                return redirect('/admin'); // Langsung ke Dashboard Admin (Foto 2)
            }

            // Jika is_admin bernilai 0, ke halaman depan toko (Foto 1)
            return redirect()->intended('/');
        }

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

    // --- REGISTER (BARU) ---
    public function showRegisterForm()
    {
        return view('auth.register');
    }

    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'phone' => 'required|string|max:20',
            'password' => 'required|string|min:8|confirmed', // Pastikan ada input name="password_confirmation" di view
        ]);

        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'password' => Hash::make($request->password),
            'role' => 'customer', // Default role adalah user biasa
        ]);

        // Opsional: Langsung login setelah daftar
        // Auth::attempt($request->only('email', 'password'));

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

    // --- LOGOUT ---
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

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