<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Permission;
use App\Models\Recurring;
use App\Models\Support;
use App\Models\Uploadmedia;
use App\Models\User;
use App\Services\CreditReportService;
use App\Models\VideoSetting;
use App\Services\Package;
use App\Services\SmartCreditJsonToHtml;
use App\Utility\ActionLogCreate;
use App\Utility\Email;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use phpDocumentor\Reflection\DocBlock\Tags\Uses;


class AjaxController extends Controller
{
    private array $response = [
                'status'=>false,
                'message'=>'fail',
                'type'=>'error',
                'data'=>[]
            ];
    public function processAjaxRequest(Request $request)
    {
        $logData=[];
        $inputData = $request->all();
        $action = $inputData['action'];

        if($inputData['action'] == "GET_CREDIT_REPORT"){

            $this->getCreditReport();
        }
        if($inputData['action'] == "GET_CREDIT_REPORT_REFRESH_BUTTON_CONTENT"){
           $this->getCreditReportRefreshButtonContent($inputData);
        }
        if($inputData['action'] == "GET_CREDIT_REPORT_REFRESH_DATE")
        {
            $inputData = auth()->user();
            $inputData['password'] = customDecrypt($inputData['password']);
            $this->getSmartCreditRefreshDate($inputData);
        }
        if($inputData['action'] == "DELETE_RECURRING")
        {
            $postData['user_id']=auth()->user()->id;
            $returnData= (new Package())->deleteRecurring($postData);
            if($returnData) {
                $this->response['message'] = 'Recurring has deleted successfully';
                $this->response['code'] = config('constant.API_SUCCESS_CODE');
                $this->response['type'] = 'success';
                $this->response['status'] = true;
                $this->response['data']['html'] = $returnData;
            }
        }
        if($inputData['action'] == "SUBSCRIPTION_SMART_CREDIT")
        {
            $auth_user = auth()->user();
            $type = config('constant.SUBSCRIPTION_SMART_CREDIT.SUBSCRIBE');
            $type_id = config('constant.SUBSCRIPTION_STATUS.SUBSCRIBED');
            if($auth_user->subscription_status == config('constant.SUBSCRIPTION_STATUS.SUBSCRIBED')){
                $type = config('constant.SUBSCRIPTION_SMART_CREDIT.UNSUBSCRIBE');
                $type_id = config('constant.SUBSCRIPTION_STATUS.CANCEL_ACCOUNT');
            }
            $inputData['user_id'] = $auth_user->id;
            $inputData['type'] = $type;
            $inputData['report_type'] = $auth_user->credit_report_company_type;
            $inputData['type_id'] = $type_id;
            $inputData['email'] = $auth_user->email;
            $inputData['name'] = $auth_user->first_name.' '.$auth_user->last_name;
            $this->customer_subscription_status_submit($inputData);
        }

        if($inputData['action'] == "DELETE_CLIENT_DOC_FILE")
        {
            $this->deleteDocFile($inputData);
        }

        if($inputData['action'] == "CLOSE_SUPPORT_TICKET")
        {
            $this->closeSupportTicket($inputData);
            $inputData['userData'] = array_slice($inputData['userData'],0,8,false);
        }
        if($inputData['action'] == "REMINDER_SUPPORT_TICKET")
        {
            $this->sendReminder($inputData);
        }



        appLog($this->logDataCreate($action,getModelDataMasking($inputData),$this->response['message'],$this->response['status'],$this->response['code'] ?? ""));
        return response()->json($this->response,200);

    }
    public function processAdminAjaxRequest(Request $request)
    {
        $inputData = $request->all();
        $clientId =[];
        if($inputData['action'] == "DELETE_CLIENT" || $inputData['action'] == "DELETE_EMPLOYEE")
        {
            $clientId = $inputData['userData'][0];
        }
        if($inputData['action'] == 'DELETE_MULTIPLE_CLIENT' || $inputData['action'] == "DELETE_MULTIPLE_EMPLOYEE"){
                foreach ($inputData['userData'] as $user) {
                        $data = json_decode($user);
                        $clientId[] = $data[0];
                    }
         }

        $this->deleteClient($clientId,$inputData['delete_type']??'');
        appLog($this->logDataCreate($inputData['action'],getModelDataMasking($inputData),$this->response['message'], "",$this->response['code'] ?? ""));
        return response()->json($this->response,200);
    }

    public function processAdminGetAjaxRequest(Request $request)
    {
        $inputData = $request->all();

        if($inputData['action'] == "GET_USER_PERMISSION")
        {
            $this->getUserPermission($inputData['id']);
        }
        if($inputData['action'] == "GET_SUBSCRIPTION_STATUS_CREDIT_REPORT_PROVIDER"){

            $this->getSubscriptionStatusCreditReportProvider($inputData);
        }
        appLog($this->logDataCreate($inputData['action'],getModelDataMasking($inputData),$this->response['message'], $this->response['status'],$this->response['code'] ?? ""));

        return response()->json($this->response,200);
    }

    private function getCreditReport(){
        $auth_user = auth()->user();
        $user_id = $auth_user->id;
        $credit_report_type = $auth_user->credit_report_company_type;

        $creditReport = (new CreditReportService())->getUpdatedReport($user_id,$credit_report_type,$auth_user->ssn);

        if(empty($creditReport['credit_report_file_name']) && empty($creditReport['html'])){
            $logData = [];
            $this->response['code'] = config('constant.OTP_SUCCESS_CODE');
            $this->response['status'] = true;
            $email = $creditReport['credit_report_user_obj']['email'];
            $password = $creditReport['credit_report_user_obj']['password'];
            $this->response['data']['html'] = view('epicvelocity.one_time_password', ['email'=>$email,'password'=>$password])->render();
            $logData['action'] = "ONE_TIME_PASSWORD_PAGE";
            $logData['request'] = $email;
            $logData['response'] = $this->response['code'];
            appLog($logData);
            return;
        }

        if($creditReport['status']){
            if(config('app.SMART_CREDIT_REPORT_BY_JSON') == '1' && $credit_report_type == config('constant.reportType.SMART_CREDIT')) {
                $creditReport['html'] = $this->generateHtml($creditReport['html']);
            }
            $this->response['status'] = true;
            $this->response['message'] = "Credit Report info fetched successfully";
            $this->response['code'] = config('constant.API_SUCCESS_CODE');
            $this->response['data']['html'] = $creditReport['html'];

        }else{
            $this->response['status'] = false;
            $this->response['message'] = "Can not fetched Data";
            $this->response['code'] = config('constant.API_FAILED_CODE');
            $this->response['data']['html'] = null;
        }
    }
    private function getSmartCreditRefreshDate($inputData)
    {

        $this->response['status'] = false;

        $response =[];
        /*$inputData['email'] = "stevetest@consumerdirect.com";
        $inputData['password'] ="123456789";*/
        if($inputData->credit_report_company_type == config('constant.reportType.SMART_CREDIT')){
            $response = (new CreditReportService())->getSmartCreditRefreshDate($inputData['email'], $inputData['password'], '');
        }else if($inputData->credit_report_company_type == config('constant.reportType.IDENTITY_IQ')){
            $response = (new CreditReportService())->getIdentityIQRefreshDate($inputData['email'], $inputData['password'], $inputData->ssn);

        }
        $this->response['message'] = "";

        if(!empty($response)){

            if ($response['refresh_date'] == "ERROR") {
                $this->response['status'] = false;
                $this->response['message'] = $response['message'];
            }else{

                $this->response['status'] = true;
                $this->response['code'] = config('constant.API_SUCCESS_CODE');

                $remove_view_late_text ="View Latest Report";
                $remove_purchase_text = "Purchase Report";
                $remove_refresh_text = "Refresh Report";
                $remove_notfound_text = "Not Found";

                $removetext = "Refresh Available";


                $response['refresh_date'] = str_replace([$remove_view_late_text,$remove_purchase_text,$remove_refresh_text,$remove_notfound_text],"",$response['refresh_date']);
                $response['refresh_date'] = str_replace("×\n","" , $response['refresh_date']);

                $this->response['button_type'] =  $response['button_type'];
                $this->response['refresh_date'] =  "REFRESH DATE (Next available) ".$response['refresh_date'];
                $this->response['type'] = "success";
                $this->response['message'] = 'Fetched data successfully.';

            }
        }


    }

    private function getCreditReportRefreshButtonContent($inputData){
        $auth_user = auth()->user();
        $response ='';
        /*$creditReportDataObj=[];*/
        /*$creditReportDataObj['email'] = "stevetest@consumerdirect.com";
        $creditReportDataObj['password'] ="123456789";*/

        if($auth_user->credit_report_company_type == config('constant.reportType.SMART_CREDIT')){
            $response= (new CreditReportService())->getSmartCreditRefreshButtonContent($auth_user['email'],customDecrypt($auth_user['password']));
        }else if($auth_user->credit_report_company_type == config('constant.reportType.IDENTITY_IQ')){
            $response = (new CreditReportService())->getIdentityRefreshButtonContent($auth_user['email'], customDecrypt($auth_user['password']), $auth_user->ssn);
        }

        $this->response['message'] = "";

        if(!empty($response)){
            $this->response['status'] = true;
            $this->response['code'] = config('constant.API_SUCCESS_CODE');
            if( $response['message'] == 'DONE'){
                $this->response['message'] = "Congratulations! Your Refresh is Complete. Please click the Import to get Your Most Recent Report Now";
            }
            if($response['message'] == "ERROR" || $response['message'] == "TIME_OUT" ) {
                $this->response['message'] = 'Not found';
            }
            if($response['message'] == "BUTTON_NOT_FOUND"){
                $this->response['message'] = $response['message'];
            }

        }

    }
    public function getTrainingVideo(Request $request)
    {
           $inputData['action']="GET_TRAINING_VIDEO";
           $sectionName=getSectionById($request['section_id']);
           $video= (new VideoSetting())->getVideoBySectionId($request['section_id']);
           if(!empty($video))
           {
               $this->response['status'] = true;
               $this->response['data']['video'] =$video;
               $this->response['data']['section_name'] =$sectionName;
               $this->response['message'] = "Training Video fetched successfully";
               $this->response['code'] = config('constant.API_SUCCESS_CODE');
           }
           else {
               $this->response['data'] = ['section_name' => $sectionName];
           }

        appLog($this->logDataCreate($inputData['action'],getModelDataMasking($inputData),$this->response['message'],$this->response['data']['html'] ?? "",$this->response['code'] ?? ""));

          return response()->json($this->response,200);
    }
    private function deleteClient($id,$delete_type)
    {
        $action='DELETE_CLIENT';
        $message = 'Client has deleted successfully';
        if($delete_type == 'employee')
        {
            $action='DELETE_EMPLOYEE';
            $message = 'Employee has deleted successfully';
        }

        if($id>0) {
            $returnData=(new User())->deleteUser($id);
            if($returnData) {
                $this->response['message'] = $message;
                $this->response['code'] = config('constant.API_SUCCESS_CODE');
                $this->response['type'] = 'success';
                $this->response['status'] = true;
            }
        }
        /*
        $user_info= (new User())->getUserByUserId($id);
        if(!empty($user_info))
        {
            $type = config('constant.SUBSCRIPTION_SMART_CREDIT.DELETE');
            $type_id = 3;
            $inputData['type'] = $type;
            $inputData['user_id'] = $user_info['id'];
            $inputData['report_type'] = $user_info['credit_report_company_type'];
            $inputData['type_id'] = $type_id;
            $this->customer_subscription_status_submit($inputData);
            if( $this->response['code'] == config('constant.API_SUCCESS_CODE')){
                if($id>0) {
                    $returnData=(new User())->deleteUser($id);
                    if($returnData) {
                        $this->response['message'] = 'Client has deleted successfully';
                        $this->response['code'] = config('constant.API_SUCCESS_CODE');
                        $this->response['type'] = 'success';
                        $this->response['status'] = true;
                    }
                }
                $this->response['status'] = true;
            }else{
                $this->response['status'] = false;
            }
        }
        */
        return response()->json($this->response,200);
    }

    private function getUserPermission($id)
    {
        $action='GET_USER_PERMISSION';
        $permitted_module=  (new Permission())->getPermittedSubmoduleIdListByUserId($id);
        if($permitted_module) {
            $this->response['message'] = 'fetch data successfully';
            $this->response['code'] = config('constant.API_SUCCESS_CODE');
            $this->response['type'] = 'success';
            $this->response['status'] = true;
            $this->response['data']=$permitted_module;
        }
        return response()->json($this->response,200);
    }

    private function customer_subscription_status_submit($inputData){

        $responseData=[];
//        $responseData= (new Package())->customerCreditReportStatus($inputData);
//        $this->response['data'] =  $responseData->data;
        $responseData['status_code'] = config('constant.API_SUCCESS_CODE');
        if($responseData['status_code'] == config('constant.API_SUCCESS_CODE')){
//            if($inputData['type_id'] != 3) {
                Auth::user()->update([
                    'subscription_status' => $inputData['type_id'],
                    'account_cancel_datetime' => getCurrentDateTime(),
                    'last_import_date' => null

                ]);
//            }
            $this->response['status'] = true;
            $this->response['code'] = config('constant.API_SUCCESS_CODE');
            $this->response['message'] = "Account has been cancelled successfully";
            $this->response['type'] = "success";
            $this->cancelAccountMail($inputData);
        }else{
            $this->response['status'] = false;
            $this->response['code'] = config('constant.API_FAILED_CODE');
            $this->response['message'] = "Account has not been cancelled. Please contact with support.";
            $this->response['type'] = "error";
        }
    }
    private function logDataCreate($action,$request,$message,$response,$code)
    {
        $logData=[];
        $logData['action'] = $action;
        $logData['data']['request'] = $request;
        $logData['data']['message'] = $message;
        $logData['data']['response'] = $response;
        $logData['data']['code'] = $code;
        return $logData;
    }

    private function cancelAccountMail($inputData)
    {
        $data['email'] = $inputData['email'];
        $data['email_body'] = $inputData['name'];
        $data['email_subject'] = "Cancel Account From Credit Zombies";
        $from = null;
        $attachment = null;
        $result = (new User())->getUserListByType(1);

        (new Email())->send($data, $data['email_subject'], $from, $attachment, 'email.account_closing_letter', $data['email']);
        (new Email())->send($data, $data['email_subject'], $from, $attachment, 'email.account_closing_admin_letter', $result[0]['email']);
    }

    private function getSubscriptionStatusCreditReportProvider($inputData){

        $this->response = (new CreditReportService())->validateUserInCreditReportProvider($inputData);

    }

    private function generateHtml($json_data){
        $data_set = (new SmartCreditJsonToHtml())->generateHtml($json_data);
        $html = '';
        if($data_set != null) {
            $creditScore = $data_set['creditScore'];
            $personal_infos = $data_set['personal_infos'];
            $consumer_statement_data_set = $data_set['consumer_statement_data_set'];
            $summary_info_data_set = $data_set['summary_info_data_set'];
            $creditor_contact_data_set = $data_set['creditor_contact_data_set'];
            $inquiries_data_set = $data_set['inquiries_data_set'];
            $account_history_data_set = $data_set['account_history_data_set'];
            $html = view('partials.credit_report.main_report', compact('creditScore', 'personal_infos', 'consumer_statement_data_set', 'summary_info_data_set', 'creditor_contact_data_set', 'inquiries_data_set', 'account_history_data_set'))->render();
        }
        return $html;

    }

    private function deleteDocFile($inputData)
    {
        $media_file = json_decode($inputData['userData'],true);
        $postData['user_id']=auth()->user()->id;
        $returnData = (new Uploadmedia())->deleteById($media_file['id']);

        if($returnData) {
            $file_path = config('constant.UPLOAD_MEDIA_PATH').DIRECTORY_SEPARATOR.auth()->user()->id;
            deleteFile($file_path.DIRECTORY_SEPARATOR.$media_file['image_path']);
            $this->response['message'] = 'File has been deleted successfully';
            $this->response['code'] = config('constant.API_SUCCESS_CODE');
            $this->response['type'] = 'success';
            $this->response['status'] = true;
            $this->response['data']['html'] = $returnData;
        }

    }

    private function closeSupportTicket($inputData)
    {
        $returnData = (new Support())->updateSupport($inputData['userData']);

        if($returnData) {
            $this->response['message'] = 'Ticket has been closed successfully';
            $this->response['code'] = config('constant.API_SUCCESS_CODE');
            $this->response['type'] = 'success';
            $this->response['status'] = true;
            $this->response['data']['html'] = $returnData;
        }

    }

    private function sendReminder($inputData){
        $from = null;
        $attachment = null;
        $supports =  (new Support())->getSupportId($inputData['supportId']);
        if(!empty($supports)) {
            $data['email'] = $supports->email;
            $data['email_body'] = "Please check your message.Ticket ID ".$supports->id;
            $data['email_subject'] = "You have a message.";
            (new Email())->send($data, $data['email_subject'], $from, $attachment, 'email.reminderletter', $data['email']);
            $this->response['message'] = 'Reminder has been sent to member successfully';
            $this->response['code'] = config('constant.API_SUCCESS_CODE');
            $this->response['type'] = 'success';
            $this->response['status'] = true;
        }
    }



}
