<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;

class PasswordResetLinkController extends Controller
{
    /**
     * Display the password reset link request view.
     */
    public function create(): Response
    {
        return Inertia::render('Auth/ForgotPassword', [
            'status' => session('status'),
        ]);
    }

    /**
     * Handle an incoming password reset link request.
     *
     * @throws ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $input = $request->input('email');
        
        // Determine if it is email or phone number
        $isEmail = filter_var($input, FILTER_VALIDATE_EMAIL);
        
        if ($isEmail) {
            $request->validate([
                'email' => 'required|email',
            ]);
            
            $status = Password::sendResetLink(
                $request->only('email')
            );

            if ($status == Password::RESET_LINK_SENT) {
                return back()->with('status', __($status));
            }

            throw ValidationException::withMessages([
                'email' => [trans($status)],
            ]);
        } else {
            // Treat as phone number
            $phone = preg_replace('/[^0-9]/', '', $input);
            if (str_starts_with($phone, '0')) {
                $phone = '62' . substr($phone, 1);
            }
            
            if (empty($phone)) {
                throw ValidationException::withMessages([
                    'email' => ['Format email atau nomor WhatsApp tidak valid.'],
                ]);
            }
            
            // Find user by WhatsApp column
            $user = \App\Models\User::where('whatsapp', $phone)->first();
            if (!$user) {
                throw ValidationException::withMessages([
                    'email' => ['Nomor WhatsApp tidak terdaftar dalam sistem kami.'],
                ]);
            }
            
            // Generate token manually
            $token = Password::broker()->createToken($user);
            $resetLink = url(route('password.reset', ['token' => $token, 'email' => $user->email], false));
            
            // Send WhatsApp message
            $storeName = \App\Models\Setting::get('store_name', 'Toko LRV');
            $message = "Halo *{$user->name}*,\n\n"
                     . "Kami menerima permintaan untuk mereset kata sandi akun {$storeName} Anda.\n"
                     . "Silakan klik tautan di bawah ini untuk mengatur ulang kata sandi Anda:\n\n"
                     . "{$resetLink}\n\n"
                     . "Tautan ini hanya berlaku untuk sementara waktu. Jika Anda tidak meminta reset kata sandi, abaikan pesan ini.";
                     
            $sent = \App\Services\WhatsAppService::sendMessage($user->whatsapp, $message);
            
            if ($sent) {
                return back()->with('status', 'Tautan reset kata sandi telah dikirim ke nomor WhatsApp Anda.');
            }
            
            throw ValidationException::withMessages([
                'email' => ['Gagal mengirim pesan WhatsApp. Silakan coba lagi nanti.'],
            ]);
        }
    }
}
