<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use App\Models\User;
use App\Mail\OtpMail;
use Carbon\Carbon;

class AuthController extends Controller
{
    // 1. Tampilkan Form Login
    public function showLoginForm()
    {
        return view('auth.login');
    }

    // 2. Prose Login (Cek Password & Kirim OTP)
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $user = User::where('email', $request->email)->first();

        // Validasi User & Password
        if (!$user || !Hash::check($request->password, $user->password)) {
            return back()->with('error', 'Email atau Password salah.');
        }

        // Generate OTP 6 Digit
        $otp = rand(100000, 999999);
        $user->otp_code = $otp;
        $user->otp_expires_at = Carbon::now()->addMinutes(5);
        $user->save();

        // Kirim Email OTP
        try {
            Mail::to($user->email)->send(new OtpMail($otp));
        } catch (\Exception $e) {
            return back()->with('error', 'Gagal mengirim email OTP. Pastikan konfigurasi SMTP benar.');
        }

        // Simpan Email sementara di session untuk verifikasi
        session(['otp_email' => $user->email]);

        return redirect()->route('otp.form')->with('success', 'Kode OTP telah dikirim ke email Anda.');
    }

    // 3. Tampilkan Form Input OTP
    public function showOtpForm()
    {
        if (!session('otp_email')) {
            return redirect()->route('login');
        }
        return view('auth.otp');
    }

    // 4. Verifikasi OTP & Login Session Akhir
    public function verifyOtp(Request $request)
    {
        $request->validate([
            'otp' => 'required|numeric|digits:6',
        ]);

        $email = session('otp_email');
        if (!$email) {
            return redirect()->route('login');
        }

        $user = User::where('email', $email)->first();

        // Validasi Kode OTP
        if (!$user || $user->otp_code !== $request->otp) {
            return back()->with('error', 'Kode OTP salah.');
        }

        // Validasi Kadaluarsa
        if (Carbon::now()->greaterThan($user->otp_expires_at)) {
            return back()->with('error', 'Kode OTP sudah kadaluarsa. Silakan login ulang.');
        }

        // BERHASIL LOGIN
        // Reset OTP
        $user->otp_code = null;
        $user->otp_expires_at = null;
        $user->save();

        Auth::login($user);
        session()->forget('otp_email'); // Hapus session sementara

        // Redirect ke Dashboard Admin
        return redirect()->route('admin.maps.index');
    }

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

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