<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class HardResetController extends Controller
{
    public function verifyEmail(Request $request, $code)
    {
        $user = User::where('hard_reset_code', $code)
            ->where('hard_reset_enabled', true)
            ->firstOrFail();

        if ($request->email !== $user->email) {
            return back()->withErrors(['email' => 'Email tidak cocok dengan database kami.']);
        }

        $view = view('auth.hard-reset', [
            'code' => $code,
            'email_verified' => true, 
            'email' => $request->email
        ]);

        return response($view)
            ->header('X-Robots-Tag', 'noindex, nofollow, noarchive, noimageindex');
    }

    public function resetPassword(Request $request, $code)
    {
        $user = User::where('hard_reset_code', $code)
            ->where('hard_reset_enabled', true)
            ->firstOrFail();

        // Double check email security
        if ($request->email !== $user->email) {
            abort(403, 'Unauthorized attempt');
        }

        $request->validate([
            'password' => ['required', 'confirmed', Password::min(8)],
        ]);

        $user->update([
            'password' => Hash::make($request->password),
            // Optional: Disable hard reset after use for security? No, user can disable it manually.
        ]);

        // Since user has a custom login slug, we cannot easily guess where to go.
        // And /login is disabled (404).
        // Best approach: Redirect back to the Hard Reset page with a success message, 
        // telling them to go to their secret login URL manually.

        return redirect()->to(url('/' . $code))->with('password_reset_success', 'Password berhasil diubah! Silakan login melalui URL rahasia Anda.');
    }
}
