<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Auth;
use App\Rules\NameRule;
use App\Rules\PasswordRule;
use App\Models\HCountry;

class UserProfileController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $user = Auth::user();
        
        $countries = HCountry::pluck('name', 'code'); 
        return view('client.pages.user.profile', compact('user', 'countries'));
    }

    protected function validator(array $data)
    {   
        $validate = [
            'name'          => ['required', 'string', 'max:255', new NameRule],
            'company'       => ['required', 'string', 'max:255'],
            'phone'         => ['required', 'string', 'max:20'],
            'country'       => ['required', 'string'],
        ];

        if(isset($data['avatar'])) {
            $validate['avatar'] =  ['mimes:jpeg,jpg,png,gif', 'max:2048'];
        }
        
        return Validator::make($data, $validate);
    }

    public function update(Request $request)
    {
        $user = Auth::user();
        $this->validator($request->all())->validate();

        $data = $request->all();

        $arrayUpdate = [
            'name'          => $data['name'],
            'phone'         => $data['phone'],
            'company'       => $data['company'],
            'country_code'  => $data['country'],
        ];

        if($request->hasFile('avatar')) {
            $avatarPath = $request->file('avatar')->store('avatar', 'public');
            $arrayUpdate['avatar'] = $avatarPath;
        } 

        $user->update( $arrayUpdate);

        return redirect('/')->with('success', 'Account settings updated successfully.');
    }

    public function changePassword() {
        return view('client.pages.user.change_password');
    }

    public function updatePassword(Request $request) {
        $request->validate([
            'current_password' => ['required','string'],
            'password' => ['required', 'string', new PasswordRule],
            'password_confirmation' => ['required', 'string', 'same:password'],
        ]);

        $user = Auth::user();
        if (!Hash::check($request->current_password, $user->password)) {
            return response()->json(['message' => 'Current password is incorrect.'], 400);
        }
       $user->update(['password' => Hash::make($request->password)]);
       Auth::logout();
       return response()->json(['message' => 'Password changed successfully!'], 200);
    }
}
