<?php

namespace App\Http\Controllers;

use App\Mail\ResetPasswordMail;
use App\Models\PasswordReset;
use App\Models\Pelaporan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use RealRashid\SweetAlert\Facedes\Alert;

class SessionController extends Controller
{
    function index(){
        $users = User::all();
        return view("/Auth/login", compact('users'));

    }

    public function login(Request $request)
    {
        // Validasi input dari form
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ],[
            'name.Required'=>'Name Wajib Diisi',
            'email.Required'=>'Email Wajib Diisi',
            'email.email'=>'Silahkan Masukkan Email Yang Valid',
        ]);

        $infologin =[
                    'email' =>$request->email,
                    'password' => $request->password
                ];
        // Coba melakukan proses autentikasi
        if (Auth::attempt($infologin)) {
            if (Auth::user()->role == 'admin') { // Menggunakan peran untuk memeriksa apakah pengguna adalah admin
                // Jika pengguna adalah admin, redirect ke dashboard admin
                return redirect()->route('admin.dashboards')->withSuccess(Auth::user()->name . ' Berhasil Login');
            } elseif (Auth::user()->role == 'user')  {
                // Jika pengguna adalah pengguna biasa, redirect ke dashboard pengguna
                return redirect()->route('users.dashboard')->withSuccess(Auth::user()->name . ' Berhasil Login');
            }
        }else{

            // Jika autentikasi gagal, redirect kembali ke halaman login dengan pesan error
            return redirect()->route('index.login')->with('error', 'Invalid credentials');
        }
    }

    // public function login(Request $request)
    // {
    //     // Validasi input dari form
    //     $request->validate([
    //         'email' => 'required|email',
    //         'password' => 'required',
    //     ],[
    //         'name.required'=>'Name Wajib Diisi',
    //         'email.required'=>'Email Wajib Diisi',
    //         'email.email'=>'Silahkan Masukkan Email Yang Valid',
    //     ]);

    //     $infologin = [
    //         'email' => $request->email,
    //         'password' => $request->password
    //     ];

    //     // Coba melakukan proses autentikasi
    //     if (Auth::attempt($infologin)) {
    //         if (Auth::user()->role == 'admin') {
    //             // Jika pengguna adalah admin, kirim respons JSON dengan informasi berhasil login
    //             return response()->json(['message' => Auth::user()->name . ' Berhasil Login', 'role' => 'admin']);

    //         } elseif (Auth::user()->role == 'user') {
    //             // Jika pengguna adalah pengguna biasa, kirim respons JSON dengan informasi berhasil login
    //             return response()->json(['message' => Auth::user()->name . ' Berhasil Login', 'role' => 'user']);
    //         }
    //     } else {
    //         // Jika autentikasi gagal, kirim respons JSON dengan informasi credentials invalid
    //         return response()->json(['error' => 'Invalid credentials'], 401);
    //     }
    // }


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

    function signup(Request $request){
        Session::flash('name', $request->name);
        Session::flash('email', $request->email);
        if (config('services.recaptcha.key') && env('RECAPTCHA_ENABLED') == true){
            $request->validate([
                'name'=>'required',
                'email'=>'required|email|unique:users',
                'password'=> 'required|min:8|confirmed',
                'g-recaptcha-response' =>'required|recaptcha'
            ],[
                'name.Required'=>'Name Wajib Diisi',
                'email.Required'=>'Email Wajib Diisi',
                'email.email'=>'Silahkan Masukkan Email Yang Valid',
                'email.unique'=>'Email Sudah Pernah Digunakan, Silahkan Pilih Email Yang Lain',
                'password.Required'=>'Password Wajib Diisi',
                'password.min'=>'Minimum Password Yang Diizinkan 8 Karakter',
                'g-recaptcha-response.recaptcha'=>'Captcha Verification Failed',
                'g-recaptcha-response.required'=>'Please Complete the Captcha',
                'password.confirmed' => 'Konfirmasi password tidak sesuai dengan password',
            ]);
        }else {
            // Jika reCAPTCHA dimatikan, validasi tanpa reCAPTCHA
            $request->validate([
                'name'=>'required',
                'email'=>'required|email|unique:users',
                'password'=> 'required|min:8|confirmed',
            ],[
                'name.Required'=>'Name Wajib Diisi',
                'email.Required'=>'Email Wajib Diisi',
                'email.email'=>'Silahkan Masukkan Email Yang Valid',
                'email.unique'=>'Email Sudah Pernah Digunakan, Silahkan Pilih Email Yang Lain',
                'password.Required'=>'Password Wajib Diisi',
                'password.min'=>'Minimum Password Yang Diizinkan 8 Karakter',
                'password.confirmed' => 'Konfirmasi password tidak sesuai dengan password',
            ]);
        }

        $data = [
            'name' =>$request->name,
            'email' =>$request->email,
            'password' => Hash::make($request->password)
        ];

        User::create($data);

        $infologin =[
            'email' =>$request->email,
            'password' => $request->password
        ];

        if(Auth::attempt($infologin)){
            // jika otentikasi sukses masuk

            return redirect()->route('users.dashboard')->withSuccess(Auth::user()->name . ' Berhasil Login');
        }else{
            // kalau gagal masuk sini
            return redirect('/')->withErrors('Email dan Password Tidak Valid');
        }

    }

    function logout(){
        Auth::logout();
        return redirect('/')->withSuccess('Berhasil Logout');
    }

    function forgot(){

        return view('auth.forgot-password');
    }

    public function sendResetLink(Request $request)
    {
        // Validasi input
        $request->validate([
            'email' => 'required|email',
        ], [
            'email.required' => 'Email Wajib Diisi',
            'email.email' => 'Silahkan Masukkan Email Yang Valid',
        ]);

        // Cek apakah email terdaftar dalam database
        $user = User::where('email', $request->email)->first();

        if ($user) {
            // Generate token
            $token = Str::random(60);

            // Set waktu kadaluarsa token
            $expires_at = now()->addMinutes(1); // Token berlaku selama 1 menit

            // Simpan token dan waktu kadaluarsa ke dalam tabel password_resets
            PasswordReset::updateOrCreate(
                ['email' => $request->email],
                ['email' => $request->email, 'token' => $token, 'created_at' => now(), 'expires_at' => $expires_at]
            );

            // Kirim email reset password
            Mail::to($user->email)->send(new ResetPasswordMail($token));

            return redirect()->route('sendResetLink')->with('success', 'Reset link has been sent to your email.');
        } else {
            return redirect()->back()->withErrors(['email' => 'Email tidak terdaftar.'])->withInput();
        }
    }

    public function showResetForm($token)
    {
        // Logika untuk menampilkan halaman reset password dengan menggunakan token
        return view('auth.reset', ['token' => $token]);
    }

    public function resetPassword(Request $request)
    {
        // Validasi input
        $request->validate([
            'password' => 'required|min:8|confirmed',
        ],[
            'password.required' => 'Password Harus Diisi',
            'password.min' => 'Minimum Password Yang Diizinkan 8 Karakter',
            'password.confirmed' => 'Konfirmasi password tidak sesuai dengan password',
        ]);

        // Cek apakah pengguna sudah login
        if (Auth::check()) {
            // Reset password pengguna yang sudah login
            $user = Auth::user();

        } else {
            // Cek apakah token reset password valid
            $token = $request->route('token');
            // Anda perlu membuat kolom 'password_resets' jika belum ada
            $reset = DB::table('password_resets')->where('token', $token)->first();

            if (!$reset) {
                return redirect()->route('index.login')->withErrors(['error' => 'Invalid token.']);
            }

            // Cek apakah token masih berlaku
            $tokenCreatedAt = Carbon::parse($reset->created_at);
            if (now()->diffInMinutes($tokenCreatedAt) > 1) {
                return redirect()->route('index.login')->withErrors(['error' => 'Token expired.']);
            }

            // Reset password
            $user = User::where('email', $reset->email)->first();
            if (!$user) {
                return redirect()->route('index.login')->withErrors(['error' => 'User not found.']);
            }
            $user->password = Hash::make($request->password);
            $user->save();

            // Hapus token reset password yang sudah digunakan
            DB::table('password_resets')->where('token', $token)->delete();
        }

        // Redirect ke halaman login dengan pesan sukses
        return redirect()->route('index.login')->with('success', 'Password has been reset successfully.');
    }

}
