<?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 Illuminate\Support\Facades\Password;
use App\Models\User;
use App\Models\Koleksi;
use Carbon\Carbon;

class AuthController extends Controller
{
    public function showRegister()
    {
        if (Auth::check()) {
            return $this->redirectBasedOnRole();
        }
        return view('register');
    }

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

    public function register(Request $request)
    {
        $request->validate([
            'name'     => 'required|string|max:255',
            'email'    => 'required|email|unique:users,email',
            'password' => [
                'required',
                'string',
                'min:8',
                'regex:/[A-Z]/',
                'regex:/[a-z]/',
                'regex:/[0-9]/',
                'regex:/[.,]/',
                'confirmed',
            ],
        ], [
            'password.min'       => 'Kata sandi minimal 8 karakter.',
            'password.regex'     => 'Kata sandi harus mengandung huruf besar, huruf kecil, angka, dan tanda baca (.,)',
            'password.confirmed' => 'Konfirmasi kata sandi tidak cocok.',
        ]);

        $otp = rand(100000, 999999);
        $now = Carbon::now();

        $user = User::create([
            'name'                 => $request->name,
            'email'                => $request->email,
            'password'             => Hash::make($request->password),
            'role'                 => 'user',
            'email_otp'            => $otp,
            'email_otp_expires_at' => $now,
            'otp_last_sent_at'     => $now,
        ]);

        $this->sendOtpEmail($user, $otp);

        return redirect()->route('verify.email.form', ['email' => $user->email])
                         ->with('success', 'Registrasi berhasil! Silakan cek email untuk kode verifikasi (berlaku 1 menit).');
    }

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

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

        if ($user && $user->blocked_at !== null) {
            return back()->withErrors([
                'email' => 'Akun Anda telah diblokir dan tidak dapat login.'
            ])->onlyInput('email');
        }

        if ($user && !$user->email_verified_at) {
            return back()->withErrors(['email' => 'Email belum diverifikasi. Silakan verifikasi terlebih dahulu.'])
                         ->onlyInput('email');
        }

        if (Auth::attempt($credentials)) {
            // Mengamankan session ID baru sebelum melakukan pengalihan rute
            $request->session()->regenerate();
            
            // Dipastikan langsung mengeksekusi return redirect bypass role
            return $this->redirectBasedOnRole();
        }

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

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

    public function dashboard()
    {
        // Jembatan utama penentu rute setelah melewati guard auth bawaan
        return $this->redirectBasedOnRole();
    }

    public function adminDashboard()
    {
        $user = Auth::user();
        if (!$user || ($user->role !== 'admin' && $user->role !== 'super_admin')) {
            return redirect()->route('login');
        }
        return view('admin.dashboard', compact('user'));
    }

    public function userDashboard()
    {
        $user = Auth::user();
        if (!$user || $user->role !== 'user') {
            return redirect()->route('login');
        }
        return view('user.dashboard', compact('user'));
    }

    public function profile()
    {
        $user = Auth::user();
        if (!$user) return redirect()->route('login');
        
        return ($user->role === 'admin' || $user->role === 'super_admin')
            ? view('admin.profile', compact('user'))
            : view('user.profile', compact('user'));
    }

    public function security()
    {
        $user = Auth::user();
        if (!$user || $user->role !== 'user') return redirect()->route('login');
        return view('user.security', compact('user'));
    }

    public function adminSecurity()
    {
        $user = Auth::user();
        if (!$user || ($user->role !== 'admin' && $user->role !== 'super_admin')) {
            return redirect()->route('login');
        }
        return view('admin.security', compact('user'));
    }

    public function updateProfile(Request $request)
    {
        $request->validate([
            'name'  => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:users,email,' . Auth::id(),
        ]);

        $user = Auth::user();
        $user->name  = $request->name;
        $user->email = $request->email;

        if ($request->filled('new_password')) {
            $request->validate([
                'current_password' => 'required',
                'new_password' => [
                    'required',
                    'string',
                    'min:8',
                    'regex:/[A-Z]/',
                    'regex:/[a-z]/',
                    'regex:/[0-9]/',
                    'regex:/[.,]/',
                    'confirmed',
                ],
            ]);

            if (!Hash::check($request->current_password, $user->password)) {
                return back()->withErrors(['current_password' => 'Password saat ini salah']);
            }

            $user->password = Hash::make($request->new_password);
        }

        $user->save();
        
        $route = ($user->role === 'admin' || $user->role === 'super_admin') ? 'admin.security' : 'user.security';
        return redirect()->route($route)->with('success', 'Profil & password berhasil diperbarui!');
    }

    public function userKoleksi()
    {
        $user = Auth::user();
        if (!$user || $user->role !== 'user') return redirect()->route('login');

        $koleksi = Koleksi::where('user_id', $user->id)->get();
        return view('user.koleksi', compact('user', 'koleksi'));
    }

    private function redirectBasedOnRole()
    {
        $user = Auth::user();
        if (!$user) {
            return redirect()->route('login');
        }
        
        if ($user->role === 'admin' || $user->role === 'super_admin') {
            return redirect()->route('admin.dashboard');
        }

        if ($user->role === 'user') {
            return redirect()->route('user.dashboard');
        }

        Auth::logout();
        return redirect()->route('login')->withErrors(['email' => 'Hak akses tidak dikenali.']);
    }

    public function showVerifyEmailForm(Request $request)
    {
        $email = $request->query('email');
        return view('verify-email', compact('email'));
    }

    public function verifyEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'otp'   => 'required|digits:6',
        ]);

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

        if (!$user) {
            return back()->withErrors(['otp' => 'Kode verifikasi salah.']);
        }

        if ($user->email_otp_expires_at) {
            $otpCreatedAt = Carbon::parse($user->email_otp_expires_at);
            $secondsElapsed = Carbon::now()->diffInSeconds($otpCreatedAt);

            if ($secondsElapsed > 60) {
                $user->update([
                    'email_otp'            => null,
                    'email_otp_expires_at' => null,
                    'otp_last_sent_at'     => null,
                ]);
                return back()->withErrors(['otp' => 'Kode OTP sudah kadaluarsa (lebih dari 1 menit). Silakan klik kirim ulang.']);
            }
        }

        $user->update([
            'email_verified_at'    => now(),
            'email_otp'            => null,
            'email_otp_expires_at' => null,
            'otp_last_sent_at'     => null,
        ]);

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

    public function resendOtp(Request $request)
    {
        $request->validate(['email' => 'required|email']);
        $user = User::where('email', $request->email)->first();

        if (!$user) return back()->withErrors(['email' => 'Email tidak ditemukan.']);

        if (empty($user->otp_last_sent_at)) {
            return $this->sendNewOtp($user);
        }

        $lastSent = Carbon::parse($user->otp_last_sent_at);
        $diff = Carbon::now()->diffInSeconds($lastSent);

        if ($diff < 60) {
            $remaining = 60 - $diff;
            return back()->withErrors(['otp' => "Silakan tunggu {$remaining} detik sebelum kirim ulang OTP."]);
        }

        return $this->sendNewOtp($user);
    }

    private function sendNewOtp($user)
    {
        $otp = rand(100000, 999999);
        $now = Carbon::now();

        $user->update([
            'email_otp'            => $otp,
            'email_otp_expires_at' => $now,
            'otp_last_sent_at'     => $now,
        ]);

        $this->sendOtpEmail($user, $otp);
        return back()->with('success', 'Kode OTP baru telah dikirim ke email Anda. Berlaku 1 menit.');
    }

    private function sendOtpEmail($user, $otp)
    {
        Mail::raw(
            "Halo {$user->name},\n\nKode verifikasi akun Anda adalah: {$otp}\nKode ini berlaku selama 1 menit.\n\nTerima kasih,\nBakorwil III Malang",
            function ($message) use ($user) {
                $message->to($user->email)
                        ->subject('Kode Verifikasi Akun Anda - Bakorwil III Malang');
            }
        );
    }

    public function showForgotPasswordForm()
    {
        return view('auth.forgot-password');
    }

    public function sendResetLink(Request $request)
    {
        $request->validate(['email' => 'required|email']);
        $status = Password::sendResetLink($request->only('email'));

        return $status === Password::RESET_LINK_SENT
            ? back()->with(['success' => __($status)])
            : back()->withErrors(['email' => __($status)]);
    }

    public function showResetPasswordForm($token)
    {
        return view('auth.reset-password', ['token' => $token]);
    }

    public function resetPassword(Request $request)
    {
        $request->validate([
            'token' => 'required',
            'email' => 'required|email',
            'password' => [
                'required',
                'string',
                'min:8',
                'regex:/[A-Z]/',
                'regex:/[a-z]/',
                'regex:/[0-9]/',
                'regex:/[.,]/',
                'confirmed',
            ],
        ]);

        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function ($user, $password) {
                $user->forceFill([
                    'password' => Hash::make($password),
                ])->save();
            }
        );

        return $status === Password::PASSWORD_RESET
            ? redirect()->route('login')->with('success', __($status))
            : back()->withErrors(['email' => [__($status)]]);
    }

    public function updateFoto(Request $request)
    {
        $request->validate([
            'foto' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $user = Auth::user();

        if ($request->hasFile('foto')) {
            if ($user->foto && file_exists(public_path('storage/foto/'.$user->foto))) {
                unlink(public_path('storage/foto/'.$user->foto));
            }

            $file = $request->file('foto');
            $namaFile = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('storage/foto'), $namaFile);

            $user->foto = $namaFile;
            $user->save();
        }

        return back()->with('success', 'Foto profil berhasil diperbarui!');
    }

    public function deleteFoto()
    {
        $user = Auth::user();

        if ($user->foto && file_exists(public_path('storage/foto/'.$user->foto))) {
            unlink(public_path('storage/foto/'.$user->foto));
        }

        $user->foto = null;
        $user->save();

        return back()->with('success', 'Foto profil berhasil dihapus!');
    }
}

