<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Notifications\ResetPasswordNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;

class ForgotPasswordController extends Controller
{
    public function showLinkRequestForm()
    {
        return view('auth.forgot-password');
    }

    public function sendResetLinkEmail(Request $request)
    {
        $request->validate([
            'send_method' => 'required|in:email,whatsapp',
            'email' => 'required_if:send_method,email|nullable|email',
            'phone' => 'required_if:send_method,whatsapp|nullable|string|max:20',
        ], [
            'send_method.required' => 'Pilih metode pengiriman',
            'email.required_if' => 'Email harus diisi',
            'email.email' => 'Format email tidak valid',
            'phone.required_if' => 'Nomor WhatsApp harus diisi',
        ]);

        $sendMethod = $request->send_method;

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

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

            $identifier = $request->email;
        } else {
            // Untuk WhatsApp, cari berdasarkan nomor HP
            $user = User::where('phone', $request->phone)->first();

            if (!$user) {
                return back()->withErrors(['phone' => 'Nomor WhatsApp tidak terdaftar.'])->withInput();
            }

            $identifier = $user->email;  // Tetap pakai email untuk token
        }

        // Generate token
        $token = Str::random(64);

        // Simpan token ke database
        DB::table('password_reset_tokens')->updateOrInsert(
            ['email' => $user->email],
            [
                'email' => $user->email,
                'token' => bcrypt($token),
                'created_at' => now()
            ]
        );

        // Kirim notifikasi sesuai pilihan user
        if ($sendMethod === 'email') {
            $user->notify(new ResetPasswordNotification($token, null, 'email'));
            $message = 'Link reset password telah dikirim ke email Anda!';
        } else {
            $user->notify(new ResetPasswordNotification($token, $request->phone, 'whatsapp'));
            $message = 'Link reset password telah dikirim ke WhatsApp Anda!';
        }

        return back()->with('status', $message);
    }
}
