<?php

namespace App\Http\Controllers;

use App\Http\Requests\EmployeeRegistrationRequest;
use App\Http\Requests\ManageClientRequest;
use App\Http\Requests\UserEditRequest;
use App\Http\Requests\PasswordChangeRequest;
use App\Http\Requests\PermissionCreateRequest;
use App\Http\Requests\EditEmployeeInfoRequest;
use App\Models\Creditreport;
use App\Models\Module;
use App\Models\Permission;
use App\Models\Sale;
use App\Models\Submodule;
use App\Models\User;
use App\Models\UserIdentityQuestionAnswer;
use App\Models\UserSecurityQuestion;
use App\Models\UserSecurityQuestionAnswer;
use App\Services\ClientService;
use App\Services\CreditReportService;
use App\Services\Package;
use App\Services\Register;
use App\Services\UploadMedia;
use App\Utility\ActionLogCreate;
use App\Utility\Email;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    private $message;
    private $code;
    private $data;
    private $type;
    public function __construct()
    {
        $this->message = 'Fail';
        $this->code = config('constant.API_FAILED_CODE');
        $this->data = [];
        $this->type = "error";
    }
    public function showManageClient(){
        $auth_user = auth()->user();
        $auth_user_id = $auth_user->id;
        $uploadMediaObj = app(\App\Models\Uploadmedia::class);
        $upload_medias = $uploadMediaObj->getUploadMediaByUserId($auth_user_id);
        $question_answer = (new UserIdentityQuestionAnswer())->getUserIdentityQuestionAnswer($auth_user_id);
        $this->setCardNumber();

        return view('auth.manage_client',compact('upload_medias','question_answer'));
    }
    public function manageClient(ManageClientRequest $request){
        $action='CLIENT_INFORMATION_UPDATE';
        $auth_user_id = auth()->id();
        $userObj = app(\App\Models\User::class);
        $inputData['creditreport'] = array_filter($request->creditreport);
        $inputData['html_content'] = $request->html_content;

        try {
            if ($userObj->userupdate($inputData['creditreport'], $auth_user_id)) {

                $creditReportData['user_id'] = $auth_user_id;
                $creditReportData['password'] = customEncrypt($inputData['creditreport']['password']);
                $creditReportData['report_type'] = $inputData['creditreport']['credit_report_company_type'];

                (new Creditreport())->updateCreditReportByUserId($creditReportData);

//                (new UploadMedia($request))->uploadmedia();
                $this->data = ['client_id'=> $auth_user_id];
                $this->code = config('constant.API_SUCCESS_CODE');
                $this->message = "Information is updated successfully.";
                $this->type = "success";
                if(getSession('is_first_login') == 1) {
                    Auth::user()->update(['is_first_login' => 0]);
                    return redirect(route('get.letter'));
                }
            }
        }catch (\Exception $ex){

            $this->code = config('constant.API_FAILED_CODE');
            $this->message = "File upload failed.";
            $this->data = $ex->getMessage();
            $this->type = "error";
        }
        ActionLogCreate::logDataCreate($action,getModelDataMasking($inputData['creditreport']),$this->message,$this->data,$this->code);
        return back()->with([$this->type => $this->message]);

    }
    public function uploadCreditReport(Request $request){
        $action='UPLOAD_CREDIT_REPORT';
        $this->message = 'Report is not uploaded. Please try again!';
        $this->type = 'error';
        try {
            DB::beginTransaction();

            $auth_user_id = auth()->id();
            $creditReportObj = app(\App\Models\Creditreport::class);
            $inputData = $request->all();

            $credit_reportData['user_id'] = $auth_user_id;
            $credit_reportData['html_content'] = $inputData['html_content'];
            if (!$creditReportObj->addOrUpdateCreditReport($credit_reportData)) {
                throw new \Exception("Report upload problem.");
            }

            Auth::user()->update([
                'is_first_login' => 0
            ]);
            DB::commit();
            $this->data = $creditReportObj;
            $this->message = 'Report uploaded successfully';
            $this->code = config('constant.API_SUCCESS_CODE');
            $this->type = 'success';
        }catch (\Exception $ex){
            $this->data= $ex->getMessage();
        }
        ActionLogCreate::logDataCreate($action,$this->prepareLog($request->all()),$this->message,$this->prepareLog($this->data),$this->code);
        return back()->with([$this->type => $this->message]);
    }
    public function getAllClient(Request $request)
    {
        $items = empty($request->pageLimit) ? config('constant.PAGINATION_LIMIT'):$request->pageLimit;

        $searchData=[
            'account_status'=>$request['account_status'],
            'search_value'=>$request['search_value'],
            'payment_status'=>$request['payment_status'] ?? "",
            'client_type' => $request['client_type'] ?? "",
            'pageLimit'=>$items
        ];

        $users =(new ClientService())->getUsers($searchData) ;
        return view('client.list',compact('users','searchData'));
    }
    public function getClientInfo($id)
    {
        $user = (new ClientService())->getUserInfoById($id);
        if (!empty($user['data'])) {
            $question_answer= (new UserIdentityQuestionAnswer())->getUserIdentityQuestionAnswer($id);
            $this->message='Fetched client info successfully';
            $this->code=config('constant.API_SUCCESS_CODE');
            return view('client.view', compact('user','question_answer'));
        }
        return redirect()->route('get.clients')->with('error','No user data found.');
    }
    public function updateClientInfo(UserEditRequest $request)
    {
        $action='EDIT_USER_INFO';

            $this->message='Do not update user data.';
            $inputData = $request->all();

            $inputData['credit_report_company_type'] = $inputData['source_type'];

            if(!empty($inputData['user_access_date'])) {

                $inputData['user_access_date'] = getStringToDateTime($inputData['user_access_date']);
                $inputData['last_payment_date'] = getCurrentDateTime();
                $inputData['subscription_status'] = 1;
            }

            if(!empty($inputData['last_import_date'])) {
                $inputData['last_import_date'] = getStringToDateTime($inputData['last_import_date']);
            }

            $user = (new ClientService())->updateUserInfoById($inputData);

            if(!empty($user)){

                $creditReportData['user_id'] = $inputData['id'];
                $creditReportData['email'] = $inputData['email'];
                $creditReportData['password'] = customEncrypt($inputData['password']);
                $creditReportData['report_type'] = $inputData['source_type'];

                (new Creditreport())->updateCreditReportByUserId($creditReportData);

                $this->message='Successfully update user data.';
                $this->code = config('constant.API_SUCCESS_CODE');
                $this->type ='success';
            }
            $requestData = getModelDataMasking($request->all());
            ActionLogCreate::logDataCreate($action,$requestData,$this->message,'',$this->code);
            return  back()->with($this->type,$this->message);

    }
    public function deleteClient($id)
    {
        $action='DELETE_CLIENT';
        $type='error';
        if($id>0) {
            $returnData= (new User())->deleteUser($id);
            if($returnData) {
                $this->message = 'Client has deleted successfully';
                $this->code = config('constant.API_SUCCESS_CODE');
                $type = 'success';
            }
            ActionLogCreate::logDataCreate($action,$id,$this->message,$id,$this->code);
        }
        return back()->with([$type=>$this->message]);
    }
    public function changeAdminInfo(PasswordChangeRequest $request)
    {
        $action='PASSWORD_CHANGE';
        $inputData=$request->all();
        $password = customEncrypt($inputData['current_password']);
        Auth::user()->update([
            'email' => $inputData['email'],
            'password' => $password
        ]);
        return back()->with(['success'=>'Admin information has been changed Successfully.']);
    }
    public  function getEmployeeInfo($id)
    {

        $employee = (new User())->getUserByUserId($id);

        $employee_permission = (new Permission())->getPermittedSubmoduleIdListByUserId($id);

        $moduleSubmoduleAssoc = (new Module())->getModuleSubmoduleAssoc();

        return view('employee.employee_info_edit',compact('employee','employee_permission','moduleSubmoduleAssoc'));

    }
    public function updateEmployeeInfo(EditEmployeeInfoRequest $request)
    {
        $action = 'EMPLOYEE_UPDATE';

        $this->message = 'Employee permission can not be updated.';

        $inputData = $request->all();

        $result = (new User())->updateEmployeeInfo($inputData);

        if($result) {

            $this->message = 'Employee permission have updated successfully.';
            $this->code = config('constant.API_SUCCESS_CODE');
            $this->data = ['true'];
            $this->type = "success";
        }
        $requestData = $this->prepareLog($request->all());
        ActionLogCreate::logDataCreate($action,$requestData,$this->message,$result,$this->code);
        return back()->with([$this->type=>$this->message]);
    }
    public function employeeList(Request $request)
    {
        $items = empty($request->pageLimit) ? config('constant.PAGINATION_LIMIT'):$request->pageLimit;

        $searchData=[
            'search_value'=>$request['search_value'],
            'pageLimit'=>$items
        ];
        $employees = (new User())->getEmployees($searchData) ;

        return view('employee.employee_list',compact('employees','searchData'));
    }
    public function createEmployee(Request $request)
    {
        $moduleSubmoduleAssoc = (new Module())->getModuleSubmoduleAssoc();

        return view('employee.employee_info',compact('moduleSubmoduleAssoc'));
    }

    public function uploadClientImage(Request $request){
        $inputData = $request->only(['doc_type','uploadmedia']);
        $action = "UPLOAD_CLIENT_DOC";
        try {
            (new UploadMedia($request))->uploadmedia();
            $this->code = config('constant.API_SUCCESS_CODE');
            $this->message = "File is uploaded successfully.";
            $this->type = "success";

            if($inputData['doc_type'] == 9) {
                getUserImagesAndDoc(auth()->user()->id);
            }
        }catch (\Exception $ex){

            $this->code = config('constant.API_FAILED_CODE');
            $this->message = "File upload failed.";
            $this->data = $ex->getMessage();
            $this->type = "error";
        }
        ActionLogCreate::logDataCreate($action,$inputData,$this->message,$this->data,$this->code);
        return back()->with([$this->type => $this->message]);
    }

    public function updateClientInfoById(Request $request)
    {
        $inputData = $request->all();
        $mailData = [];
        $saveData = [];
        $action = 'CLIENT_ACTIVATION';

        $time_interval = (-1) * config('constant.PACKAGE_INTERVAL_DAY');

        $user = (new User())->getUserByUserId($inputData['client_id']);
        if($inputData['type'] == 2)
        {
            $action = 'RESET_IMPORT_BUTTON';
            $saveData['is_import'] = 1;
            if($user["is_first_login"] == 0 && $user['last_import_date'] == null){
                $saveData['last_import_date'] = getDateAfterSpicificDay(getCurrentDateTime(),$time_interval);
            }
        }
        if($inputData['type'] == 1){
            $action = 'CLIENT_ACTIVATION';
            $saveData['subscription_status'] = 1;
            $saveData['status'] = 1;
            $saveData['wave'] = 1;
        }

        if (!empty($user)) {

            (new User())->userupdate($saveData,$inputData['client_id']);
            $mailData['email'] = $user['email'];
            $mailData['name'] = $user['first_name'] . ' ' . $user['last_name'];
            $mailData['password'] = customDecrypt($user['password']);
            $this->message='Import Credit Report button has been reset successfully.';
            $this->code=config('constant.API_SUCCESS_CODE');
            $user['data'] = $user;
            $this->type = 'success';
        }

        ActionLogCreate::logDataCreate( $action,getModelDataMasking($mailData),$this->message,$this->type,$this->code);
        return redirect()->route('get.client.info',$inputData['client_id'])->with( $this->type,$this->message);
    }
    private function setCardNumber(){
        $key = 'card_no';

        unsetCache($key);

        if(empty(getCache($key))){

            $user_last_payment = (new Sale())->getLatestSalesByUserId(auth()->id());

            if(!empty($user_last_payment)) {

                setCache($key, $user_last_payment['cc_number']);

            }
        }
    }
    private function  prepareLog($inputData)
    {
        if(!empty($inputData['password']))
        {
            $inputData['password']="*********";
        }
        if(!empty($inputData['full_ssn']))
        {
            $inputData['full_ssn']="*********";
        }
        if(!empty($inputData['ssn']))
        {
            $inputData['ssn']="****";
        }
        if(!empty($inputData['security_key']))
        {
            $inputData['security_key']="*********";
        }
        if(!empty($inputData['card_number']))
        {
            $inputData['card_number']="*********";
        }
        if(!empty($inputData['html_content']))
        {
            $inputData['html_content']="*********************************";
        }

        return $inputData;
    }


}
