<?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',
        ], [
            'username.required' => 'Username wajib diisi',
            'password.required' => 'Password wajib diisi',
        ]);

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

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

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

        if ($petani && Hash::check($request->password, $petani->password)) {
            // Validasi Status Akun Petani
            if ($petani->status_akun == 'menunggu') {
                return back()->withErrors(['login_error' => 'Akun Anda masih dalam proses verifikasi Admin.']);
            }
            if ($petani->status_akun == 'ditolak') {
                return back()->withErrors(['login_error' => 'Pendaftaran Anda ditolak. Silakan hubungi Admin.']);
            }

            Auth::guard('petani')->login($petani);
            $request->session()->regenerate();
            
            return redirect()->intended('petani/dashboard');
        }

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

        return back()->withErrors([
            'login_error' => 'Username atau password salah, atau akun tidak ditemukan.',
        ])->withInput($request->only('username'));
    }

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

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

        if ($request->role == 'petani') {
            Petani::create([
                'nama_lengkap' => $request->nama_lengkap,
                'email'        => $request->email,
                'username'     => $request->username,
                'password'     => Hash::make($request->password),
                'no_hp'        => $request->no_hp,
                'alamat'       => $request->alamat,
                'nama_usaha'   => $request->nama_usaha ?? 'Toko Tani ' . $request->nama_lengkap, 
                'status_akun'  => 'menunggu'
            ]);
            
            return redirect('/login')->with('success', 'Registrasi Petani Berhasil! Mohon tunggu verifikasi Admin.');

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

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

    public function logout(Request $request)
    {
        // Logout semua guard untuk keamanan
        if (Auth::guard('admin')->check()) Auth::guard('admin')->logout();
        if (Auth::guard('petani')->check()) Auth::guard('petani')->logout();
        if (Auth::guard('pembeli')->check()) Auth::guard('pembeli')->logout();

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

        return redirect('/login');
    }
}