<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use App\Models\User;
use Carbon\Carbon;

class LoginWithEmailController extends Controller
{
    public function showForm() {
        return view('auth.login-email');
    }

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

        $token = Str::random(64);
        $user->email_login_token = $token;
        $user->token_expires_at = Carbon::now()->addMinutes(15);
        $user->save();

        $link = route('login.email.token', $token);
        Mail::raw("Klik link ini untuk login: $link", function($message) use($user) {
            $message->to($user->email)
                    ->subject('Link Login Sekali Pakai');
        });

        return back()->with('success', 'Link login sudah dikirim ke email Anda.');
    }

    public function login($token) {
        $user = User::where('email_login_token', $token)
                    ->where('token_expires_at', '>', Carbon::now())
                    ->firstOrFail();

        Auth::login($user);

        $user->email_login_token = null;
        $user->token_expires_at = null;
        $user->save();

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


