<?php

namespace App\Http\Controllers\Customer;

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

class ProfileController extends Controller
{
    public function show()
    {
        $user          = auth()->user();
        $countries     = CountriesData::names();
        $countriesData = CountriesData::all();

        return view('customer.profile.index', compact('user', 'countries', 'countriesData'));
    }

    public function updateInfo(Request $request)
    {
        $user = auth()->user();

        $data = $request->validate([
            'name'    => 'required|string|max:100',
            'company' => 'nullable|string|max:150',
            'phone'   => 'nullable|string|max:30',
            'country' => 'nullable|string|max:100',
            'state'   => 'nullable|string|max:100',
            'address' => 'nullable|string|max:300',
        ]);

        $user->update($data);

        return back()->with('success', 'Profile updated successfully.');
    }

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

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

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

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

        return back()
            ->with('password_success', 'Password changed successfully.')
            ->withFragment('password');
    }
}
