<?php

namespace App\Http\Controllers\In_Charge;

use App\Http\Controllers\Controller;
use App\Models\Common;
use App\Models\In_Charge;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class ChangePasswordController extends Controller
{
    public $common;
    public function __construct()
    {
        $this->common = new Common;
    }

    public function index(Request $request)
    {
        try {

            $params['data'] = [];
            $incharge = InCharge_Data();
            if (isset($incharge) && $incharge != null) {

                $params['incharge_id'] = $incharge['id'];

                return view('incharge.changepassword.index', $params);
            } else {
                return redirect()->route('incharge.login')->with('success', __('label.logout_successfully'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function update($id, Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'current_password' => 'required',
                'new_password' => 'required|min:4',
                'confirm_password' => 'required|min:4|same:new_password',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs));
            }

            $provider = In_Charge::where('id', $id)->first();

            if (isset($provider) && $provider != null) {

                if (Hash::check($request['current_password'], $provider['password'])) {

                    $provider->password = Hash::make($request['new_password']);
                    if ($provider->save()) {
                        return response()->json(array('status' => 200, 'success' => __('label.password_change_successfully')));
                    }
                } else {
                    return response()->json(array('status' => 400, 'errors' => __('label.please_enter_right_current_password')));
                }
            } else {
                return response()->json(array('status' => 400, 'errors' => __('label.data_not_updated')));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
}
