<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail; // Tambah ini
use App\Mail\ResetPasswordMail;       // Mail custom buatan kita (nanti dibikin)
use App\Models\User;

class AuthController extends Controller
{
    public function showRegister()
    {
        return view('auth.register'); // tanpa slash di depan
    }

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

        User::create([
            'name'     => $request->name,
            'email'    => $request->email,
            'password' => Hash::make($request->password),
            'role'     => 'user', // default role
        ]);

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

    public function showLogin()
    {
        return view('auth.login');
    }

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

        // Buat atau update akun default jika email admin
        if ($request->email === 'admin@gmail.com') {
            User::updateOrCreate(
                ['email' => 'admin@gmail.com'],
                [
                    'name'     => 'Admin',
                    'password' => Hash::make('admin12345'),
                    'role'     => 'admin',
                ]
            );
        }

        if ($request->email === 'pemilik@gmail.com') {
            User::updateOrCreate(
                ['email' => 'pemilik@gmail.com'],
                [
                    'name'     => 'Pemilik',
                    'password' => Hash::make('pemilik12345'),
                    'role'     => 'pemilik',
                ]
            );
        }

        // Lakukan login
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            $user = Auth::user();

            // Redirect berdasarkan role
            switch ($user->role) {
                case 'admin':
                    return redirect()->route('admin.dashboard');
                case 'pemilik':
                    return redirect()->route('pemilik.dashboard');
                default:
                    return redirect()->route('users.peta');
            }
        }

        return back()->with('error', 'Email atau password salah.');
    }

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

   // Menerima email dan langsung ke form reset password
   public function sendResetForm(Request $request)
{
    $request->validate([
        'email' => 'required|email',
    ]);

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

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

    // Generate token dan simpan di kolom reset_password
    $token = Str::random(64);
    $user->reset_password = $token;
    $user->save();

    // Redirect ke halaman reset password dengan membawa email
    return redirect()->route('password.reset', ['email' => $user->email]);
}

public function showResetForm(Request $request)
{
    $email = $request->query('email');

    if (!$email) {
        return redirect()->route('password.request')->withErrors(['email' => 'Email tidak ditemukan.']);
    }

    return view('auth.reset-password', ['email' => $email]);
}

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

    // Cari user berdasarkan email dan reset_password
    $user = User::where('email', $request->email)
                ->where('reset_password', $request->email) // Verifikasi email yang valid
                ->first();

    if (!$user) {
        return back()->withErrors(['email' => 'Email tidak ditemukan atau token sudah kadaluarsa.']);
    }

    // Update password user
    $user->password = Hash::make($request->password);
    $user->reset_password = null; // Hapus token agar tidak bisa dipakai lagi
    $user->save();

    // Login otomatis setelah reset password
    Auth::login($user);

    // Redirect ke halaman login dengan success
    return redirect()->route('login')->with('success', 'Password berhasil diubah. Silakan login dengan password baru Anda.');
}

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