<?php

namespace App\Http\Controllers;

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

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

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

        $credentials = $request->only('username', 'password');

        // Cek Login ADMIN
        if (Auth::guard('admin')->attempt($credentials)) {
            $request->session()->regenerate();
            return redirect()->intended('admin/dashboard');
        }

        // Cek Login PEMBELI
        if (Auth::guard('pembeli')->attempt($credentials)) {
            $request->session()->regenerate();
            return redirect()->intended('/'); // Ke Halaman Utama (Landing)
        }

        // Cek Login PETANI
        $petani = Petani::where('username', $request->username)->first();

        // Jika username ada & password cocok
        if ($petani && Hash::check($request->password, $petani->password)) {
            // Cek Status Akun
            if ($petani->status_akun == 'menunggu') {
                return back()->withErrors(['username' => 'Akun Anda masih MENUNGGU persetujuan Admin.']);
            }
            if ($petani->status_akun == 'ditolak') {
                return back()->withErrors(['username' => 'Maaf, pendaftaran Anda DITOLAK oleh Admin.']);
            }

            // Jika status Aktif, baru izinkan login
            Auth::guard('petani')->login($petani);
            $request->session()->regenerate();
            return redirect()->intended('petani/dashboard');
        }

        return back()->withErrors([
            'username' => 'Username atau password salah.',
        ]);
    }

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

    public function registerProcess(Request $request)
    {
        // Validasi
        $request->validate([
            'role'          => 'required|in:petani,pembeli',
            'nama_lengkap'  => 'required',
            'username'      => 'required|unique:petanis,username|unique:pembelis,username',
            'password'      => 'required|min:6',
            'no_hp'         => 'required',
            'alamat'        => 'required',
        ]);

        if ($request->role == 'petani') {
            Petani::create([
                'nama_lengkap' => $request->nama_lengkap,
                'username'     => $request->username,
                'password'     => Hash::make($request->password),
                'no_hp'        => $request->no_hp,
                'alamat'       => $request->alamat,
                'nama_usaha'   => $request->nama_usaha, 
                'status_akun'  => 'menunggu'
            ]);
            
            return redirect('/login')->with('success', 'Pendaftaran Berhasil! Tunggu verifikasi Admin untuk Login.');

        } else {
            Pembeli::create([
                'nama_lengkap' => $request->nama_lengkap,
                'username'     => $request->username,
                'password'     => Hash::make($request->password),
                'no_hp'        => $request->no_hp,
                'alamat'       => $request->alamat,
            ]);

            return redirect('/login')->with('success', 'Pendaftaran Berhasil! Silakan Login.');
        }
    }

    public function logout(Request $request)
    {
        if (Auth::guard('admin')->check()) Auth::guard('admin')->logout();
        elseif (Auth::guard('petani')->check()) Auth::guard('petani')->logout();
        elseif (Auth::guard('pembeli')->check()) Auth::guard('pembeli')->logout();

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

        return redirect('/login');
    }
}