<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Hash, Auth;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;
use Jenssegers\Agent\Agent;

class ChangepasswordController extends Controller
{




    public function changePassword(Request $request)
    {
        
        $request->validate([
          'current_password' => 'required|max:255',
          'password' => 'required|string|min:8|confirmed|max:255',
          'password_confirmation' => 'required|max:255',
        ]);
        if($request->current_password == $request->password){
            return response()->json(['error' => 'Your new password can not be the same as your old password. Please choose a new password.']);
        }else{
            $user = Auth::user();
            if (Hash::check($request->current_password, $user->password)) {
                $user->password = Hash::make($request->password);
                $user->save();

                $geolocation = GeoIP::getLocation(request()->getClientIp());
                $agent = new Agent();
                $activity = new EmployeeActivity();
                $activity->user_id = Auth::user()->id;
                $activity->activity_type = 'Changed their password';
                $activity->ip_address = $geolocation->ip;
                $activity->browser = $agent->browser();
                $activity->device = $agent->device();
                $activity->save();
               
                Auth::logout();
                $request->session()->flush();
        
                return  response()->json(['success' => 'The password has been successfully changed!']);
            }
            else{
                return response()->json(['error' => 'The current password does not match!']);
            }
        }

        
    }
}
