<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\{Auth, Hash, Session, Mail};
use Laravolt\Indonesia\Models\Province;

class AuthController extends Controller
{
    private function redirectByRole()
    {
        $role = Auth::user()->role;
        return match($role) {
            'admin'   => redirect()->route('admin.dashboard'),
            'courier' => redirect()->route('courier.dashboard'),
            default   => redirect()->route('user.dashboard'),
        };
    }

    public function showLogin() {
        if (Auth::check()) return $this->redirectByRole();
        return view('auth.login');
    }

    public function login(Request $request) {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);
        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();
            return $this->redirectByRole();
        }
        return back()->withErrors(['email' => 'Email atau password salah'])->withInput();
    }

    public function showRegister() {
        if (Auth::check()) return $this->redirectByRole();
        return view('auth.register', ['provinces' => Province::all()]);
    }

    public function register(Request $request) {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'otp_code' => 'required',
            'password' => 'required|min:6|confirmed',
            'address' => 'required',
            'province_code' => 'required',
            'city_code' => 'required',
            'district_code' => 'required',
            'village_code' => 'required',
        ]);

        if ($request->otp_code != session('otp_code')) {
            return back()->withErrors(['otp_code' => 'OTP salah!'])->withInput();
        }

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'role' => 'user', // Default jadi user
            'address' => $data['address'],
            'province_code' => $data['province_code'],
            'city_code' => $data['city_code'],
            'district_code' => $data['district_code'],
            'village_code' => $data['village_code'],
        ]);

        Auth::login($user);
        $request->session()->regenerate();
        return redirect()->route('user.dashboard');
    }

    public function logout(Request $request) {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('welcome');
    }

    public function sendVerificationCode(Request $request) {
        $request->validate(['email' => 'required|email']);
        $otp = rand(100000, 999999);
        Session::put('otp_code', $otp);
        Mail::raw("Kode OTP Anda: $otp", function($m) use ($request) {
            $m->to($request->email)->subject('OTP Verifikasi');
        });
        return response()->json(['success' => true]);
    }
}