<?php

namespace App\Http\Controllers\Controllers;

use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Mail\ForgotPasswordMail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;

class AuthController extends Controller
{
    public function showLoginForm()
    {
        if (Auth::check()) {
            return redirect()->route('admin.dashboard');
        }

        return view('auth.login');
    }

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

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

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

            if (Auth::attempt($credentials)) {
                $request->session()->regenerate();

                // Hanya izinkan Kepala Desa & Sekretaris
                $user = Auth::user();
                $allowed = ['admin'];

                if (!in_array($user->role, $allowed, true)) {
                    // Langsung keluarkan & beri pesan
                    Auth::logout();
                    $request->session()->invalidate();
                    $request->session()->regenerateToken();

                    return back()->withErrors([
                        'email' => 'Akun Anda tidak berwenang masuk ke Admin Dashboard.',
                    ])->withInput($request->only('email'));
                }

                // Lolos semua cek
                return redirect()->intended(route('admin.dashboard'));
            }

            return back()->withErrors([
                'email' => 'Email atau password salah.',
            ])->withInput($request->only('email'));
        } catch (\Exception $e) {
            //throw $th;
            Log::error('Login error: ' . $e->getMessage());
            return back()->withErrors([
                'error' => 'Terjadi kesalahan pada server harap coba lagi nanti.',
            ]);
        }
    }

    public function forgotPassword(Request $request)
    {
        // Validate email
        $data =  $request->validate(['email' => 'required|email|exists:users,email'],     [
            'email.required' => 'Kolom email wajib diisi.',
            'email.email'    => 'Format email tidak valid.',
            'email.exists'   => 'Maaf, email ini tidak terdaftar di sistem kami.',
        ]);

        // Generate reset password link
        $token = Str::random(64);
        DB::table('password_resets')->updateOrInsert(
            ['email' => $data['email']],
            [
                'token' => $token,
                'created_at' => now()
            ]
        );
        $url = url("/reset-password/{$token}?email=" . urlencode($data['email']));

        // Send email
        Mail::to($data['email'])->send(new ForgotPasswordMail($url));

        return back()->with('status', 'Link reset password telah dikirim ke email Anda.');
    }

    public function resetPassword(Request $request)
    {
        // 1. Validasi input
        $data = $request->validate(
            [
                'email'                 => 'required|email|exists:users,email',
                'password'              => 'required|string|min:8|confirmed',
                'token'                 => 'required|string',
            ],
            [
                'email.required'        => 'Kolom email wajib diisi.',
                'email.email'           => 'Format email tidak valid.',
                'email.exists'          => 'Email tidak terdaftar di sistem kami.',
                'password.required'     => 'Kolom kata sandi wajib diisi.',
                'password.min'          => 'Kata sandi minimal :min karakter.',
                'password.confirmed'    => 'Konfirmasi kata sandi tidak cocok.',
                'token.required'        => 'Token reset tidak ditemukan.',
            ]
        );


        // 2. Cek token di tabel password_resets
        $reset = DB::table('password_resets')
            ->where('email', $data['email'])
            ->where('token', $data['token'])
            ->first();

        if (!$reset) {
            return back()->withErrors([
                'token' => 'Token reset tidak valid atau sudah kedaluwarsa.',
            ]);
        }

        if (now()->diffInMinutes($reset->created_at) > 60) {
            DB::table('password_resets')->where('email', $data['email'])->delete();
            return back()->withErrors([
                'token' => 'Token reset telah kedaluwarsa.',
            ]);
        }

        // 3. Update password user
        $user = User::where('email', $data['email'])->first();
        $user->password = Hash::make($data['password']);
        $user->save();

        // 4. Hapus record password_resets
        DB::table('password_resets')->where('email', $data['email'])->delete();

        return redirect()
            ->route('login')
            ->with('status', 'Password Anda berhasil direset. Silakan login dengan kata sandi baru.');
    }

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

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