<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class DenunciantePasswordController extends Controller
{
    public function edit()
    {
        return view('denunciante.cambiar-password');
    }

    public function update(Request $request)
    {
        $request->validate([
            'password_actual' => 'required|string',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $user = auth()->user();

        if (!Hash::check($request->password_actual, $user->password)) {
            return back()->withErrors([
                'success' => 'La contraseña actual no es correcta.',
            ]);
        }

        if (Hash::check($request->password, $user->password)) {
            return back()->withErrors([
                'success' => 'La nueva contraseña debe ser diferente a la actual.',
            ]);
        }

        $user->password = Hash::make($request->password);
        $user->change_password = true;
        $user->password_changed_at = now();
        $user->save();

        return redirect()
            ->route('denunciante.dashboard')
            ->with('success', 'Su contraseña fue actualizada correctamente.');
    }
}