<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rules\Password;

class PasswordChangeController extends Controller
{
    /**
     * Show the customer password change form
     */
    public function showCustomerForm()
    {
        return view('auth.change-password', [
            'title' => 'Change Password',
            'user_type' => 'customer'
        ]);
    }

    /**
     * Show the admin password change form
     */
    public function showAdminForm()
    {
        return view('admin.change-password', [
            'title' => 'Change Password',
            'user_type' => 'admin'
        ]);
    }

    /**
     * Update customer password
     */
    public function updateCustomerPassword(Request $request)
    {
        return $this->updatePassword($request, 'customer');
    }

    /**
     * Update admin password
     */
    public function updateAdminPassword(Request $request)
    {
        return $this->updatePassword($request, 'admin');
    }

    /**
     * Update password for any user type
     */
    private function updatePassword(Request $request, $userType)
    {
        $request->validate([
            'current_password' => ['required', 'string'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
            'password_confirmation' => ['required', 'string']
        ], [
            'current_password.required' => 'Current password is required.',
            'password.required' => 'New password is required.',
            'password.min' => 'Password must be at least 6 characters long.',
            'password.confirmed' => 'Password confirmation does not match.',
        ]);

        $user = Auth::user();

        // Check if current password is correct
        if (!Hash::check($request->current_password, $user->password)) {
            return back()->withErrors([
                'current_password' => 'Current password is incorrect.'
            ])->withInput();
        }

        // Check if new password is different from current password
        if (Hash::check($request->password, $user->password)) {
            return back()->withErrors([
                'password' => 'New password must be different from current password.'
            ])->withInput();
        }

        // Update password
        $user->update([
            'password' => Hash::make($request->password)
        ]);

        // Note: Auth::logoutOtherDevices() removed due to compatibility issues
        // Users should manually log out from other devices if needed

        $message = 'Password changed successfully!';
        $redirectRoute = $userType === 'admin' ? 'admin.dashboard' : 'dashboard';

        return redirect()->route($redirectRoute)->with('success', $message);
    }
}