";print_r($data);exit; } function processAjaxRequest($conn, $inputData) { //echo "
";print_r();exit;
    $is_processed = false;
    if(isset($inputData['save_letter']) && $inputData['save_letter'] == 1){
        $is_processed = true;
    }else {
        $messages = getAutomations($conn, $inputData);
        if($messages['status']){
            $is_processed = true;
        }
    }
    //pr($messages['all_file_info']);exit;
    if($is_processed){
        if(isset($inputData['onload_form_id']) && !empty($inputData['onload_form_id'])){
            $rtg_letters_id = updateRTGLetters($conn, $inputData['onload_form_id'], $inputData);
        }else{
            $rtg_letters_id = saveRTGLetters($conn, $inputData);
        }
        
        if(isset($inputData['set_automation']) && $inputData['set_automation'] == 1){

            $inputData['sertg_id'] = $rtg_letters_id;
            $all_file_info = $messages['all_file_info'];

            if(!empty($all_file_info)){
                foreach($all_file_info as $finfo){
                    $isInserted = setAutomation($conn, $inputData);
                    if($isInserted){
                        if($finfo['category_id'] == LETTER_STREAM_TYPE){
                            $inputData['ls_data'] = [];
                            $inputData['ls_data'][] = $messages['data'];
                            copyPdfToAnotherDir($inputData['file_path'],"/rtg_letters/letterstream/",$rtg_letters_id,$inputData);

                        }else if($finfo['category_id'] == RINGCENTRAL_EXPORT_TYPE){
                            
                                $sent_pdf_file = $finfo['data'];
                                $file_info_for_json['status'] = 1;
                                $file_info_for_json['pdf'] = $inputData['file_path'];
                                $file_info_for_json['fax_number'] = $sent_pdf_file['destination_0'];
                                $file_info_for_json['db_key'] = 'destination_0';
                                $file_info_for_json['sequence'] = 0;
                                $inputData['ls_data'] = [];
                                $inputData['ls_data'][] = $file_info_for_json;
                                copyPdfToAnotherDir($inputData['file_path'],"/rtg_letters/ringcentral/",$rtg_letters_id,$inputData);
                                
                        } else if($finfo['category_id'] == EMAIL_EXPORT_TYPE){
                            copyPdfToAnotherDir($inputData['file_path'],"/rtg_letters/email/",$rtg_letters_id,$inputData);
                        } else if($finfo['category_id'] == DROPBOX_EXPORT_TYPE){
                            copyPdfToAnotherDir($inputData['file_path'],"/rtg_letters/dropbox/",$rtg_letters_id,$inputData);
                        } else if($finfo['category_id'] == GOOGLE_DRIVE_EXPORT_TYPE){
                            copyPdfToAnotherDir($inputData['file_path'],"/rtg_letters/google_drive/",$rtg_letters_id,$inputData);
                        } else if($finfo['category_id'] == ZAPIER_EXPORT_TYPE){
                            copyPdfToAnotherDir($inputData['file_path'],"/rtg_letters/zapier/",$rtg_letters_id,$inputData);
                        } else if($finfo['category_id'] == ONE_DRIVE_TYPE){
                            copyPdfToAnotherDir($inputData['file_path'],"/rtg_letters/onedrive/",$rtg_letters_id,$inputData);
                        }
                    }
                }
            }
            
        }
        
        letterEmailSendToClient($conn, $inputData);
        insertSttPILetterSet($conn,$rtg_letters_id);
        storePdfLetters($_POST['client_id'],$rtg_letters_id,3,$inputData['file_path']);
    }
    return $messages;
}



function getAutomations($conn, $inputData) {
     
    $destAssocAddress = $inputData['destAssocAddress'];
    $destAssocReturnAddress = $inputData['destAssocReturnAddress'];
    $lettertypes = json_decode($inputData['lettertypes'],true);
    
    $dropdown_category_id = implode(",", $inputData['download_category']);
    $credit_bureau_name_address = $inputData['credit_bureau_name_address'];
    $total_pdf_pages = $inputData['total_pdf_pages'];
    $client_name = $inputData['client_name'];
    $client_id = $inputData['client_id'];
    
    $sql = "SELECT * FROM automations where id IN (" . $dropdown_category_id . ")";
    
    $result = $conn->query($sql);
    $all_file_info = [];
    if ($result->num_rows > 0) {
        
        $errorArray = [];
        $messages = "";
        $errorMessages = setErrorMessage();
        
        while ($row = $result->fetch_assoc()) {
           
            $category_id = $row['export_id'];
            $obj = json_decode($row['input_json']);
            
            $data = [];
            if (!empty($obj)) {
                $data['access_key'] = !empty($obj->access_key) ? $obj->access_key : '';
                $data['dropbox_token'] = !empty($obj->dropbox_token) ? $obj->dropbox_token : '';
                $data['dropbox_client_id'] = !empty($obj->user_name) ? $obj->user_name : '';
                $data['dropbox_client_secret'] = !empty($obj->password) ? $obj->password : '';
                $data['dropbox_refresh_token'] = !empty($obj->dropbox_refresh_token) ? $obj->dropbox_refresh_token : '';
                $data['email'] = !empty($obj->email) ? $obj->email : '';
                $data['email_subject'] = !empty($obj->email_subject) ? $obj->email_subject : '';
                $data['email_body'] = !empty($obj->email_body) ? $obj->email_body : '';
                $data['google_token'] = !empty($obj->google_token) ? $obj->google_token : '';
                $data['google_client_id'] = !empty($obj->google_client_id) ? $obj->google_client_id : '';
                $data['google_client_secret'] = !empty($obj->google_client_secret) ? $obj->google_client_secret : '';
                $data['google_refresh_token'] = !empty($obj->google_refresh_token) ? $obj->google_refresh_token : '';
                $data['ring_client_id'] = !empty($obj->ring_client_id) ? $obj->ring_client_id : '';
                $data['ring_client_secret'] = !empty($obj->ring_client_secret) ? $obj->ring_client_secret : '';
                $data['ring_account'] = !empty($obj->ring_account) ? $obj->ring_account : '';
                $data['ring_password'] = !empty($obj->ring_password) ? $obj->ring_password : '';
                $data['ring_extension'] = !empty($obj->ring_extension) ? $obj->ring_extension : '';
                $data['ring_isEmailReceived'] = isset($obj->ring_isEmailReceived) ? $obj->ring_isEmailReceived : 0;
                $data['ring_server'] = !empty($obj->ring_server) ? $obj->ring_server : '';
                $data['destination_2'] = !empty($obj->ring_fax_equifax_number) ? $obj->ring_fax_equifax_number : '';
                $data['destination_3'] = !empty($obj->ring_fax_trans_number) ? $obj->ring_fax_trans_number : '';
                $data['destination_1'] = !empty($obj->ring_fax_experian_number) ? $obj->ring_fax_experian_number : '';
                $data['destination_0'] = !empty($obj->ring_fax_default_number) ? $obj->ring_fax_default_number : '';
                $data['destination_4'] = !empty($obj->ring_fax_innovis_number) ? $obj->ring_fax_innovis_number : '';
                $data['destination_5'] = !empty($obj->ring_fax_lexisnexis_number) ? $obj->ring_fax_lexisnexis_number : '';
                $data['destination_6'] = !empty($obj->ring_fax_sagestream_number) ? $obj->ring_fax_sagestream_number : '';
                $data['destination_7'] = !empty($obj->ring_fax_chex_systems_number) ? $obj->ring_fax_chex_systems_number : '';
                $data['destination_8'] = !empty($obj->ring_fax_mib_inc_number) ? $obj->ring_fax_mib_inc_number : '';
                $data['destination_9'] = !empty($obj->ring_factor_inc_number) ? $obj->ring_factor_inc_number : '';
                $data['destination_10'] = !empty($obj->ring_data_furnishers_number) ? $obj->ring_data_furnishers_number : '';
                $data['destination_11'] = !empty($obj->ring_other_number) ? $obj->ring_other_number : '';
                $data['letter_stream_api_key'] = !empty($obj->letter_stream_api_key) ? $obj->letter_stream_api_key : "";
                $data['letter_stream_api_id'] = !empty($obj->letter_stream_api_id) ? $obj->letter_stream_api_id : "";
                $data['letter_stream_token'] = !empty($obj->letter_stream_token) ? $obj->letter_stream_token : "";
                $data['letter_stream_name_1'] = !empty($obj->letter_stream_name_1) ? $obj->letter_stream_name_1 : "";
                $data['letter_stream_name_2'] = !empty($obj->letter_stream_name_2) ? $obj->letter_stream_name_2 : "";
                $data['letter_stream_address_1'] = !empty($obj->letter_stream_address_1) ? $obj->letter_stream_address_1 : "";
                $data['letter_stream_address_2'] = !empty($obj->letter_stream_address_2) ? $obj->letter_stream_address_2 : "";
                $data['letter_stream_city'] = !empty($obj->letter_stream_city) ? $obj->letter_stream_city : "";
                $data['letter_stream_state'] = !empty($obj->letter_stream_state) ? $obj->letter_stream_state : "";
                $data['letter_stream_zip'] = !empty($obj->letter_stream_zip) ? $obj->letter_stream_zip : "";

                $data['one_drive_client_id'] = !empty($obj->one_drive_client_id) ? $obj->one_drive_client_id : "";
                $data['one_drive_client_secret'] = !empty($obj->one_drive_client_secret) ? $obj->one_drive_client_secret : "";
                $data['one_drive_code'] = !empty($obj->one_drive_code) ? $obj->one_drive_code : "";
            }
            
            $zip_file = $inputData['file_path'];
            $file_name = $zip_file;
            
            if ($category_id == EMAIL_EXPORT_TYPE) {
                $status = sendEmail($data, $zip_file);
                if ($status) {
                    $all_file_info[] = [
                        'file_path'=>$file_name,
                        'category_id' =>$category_id,
                        'data'=>array_filter($data)
                    ];
                    $errors = 6;
                } else {
                    $errors = 5;
                }

                if (!empty($errorString)) {
                    $errorString .= "\n" . $row['name'] . " " . $errorMessages[$errors];
                } else {
                    $errorString = $row['name'] . " " . $errorMessages[$errors];
                }
            } elseif ($category_id == DROPBOX_EXPORT_TYPE) {
                $_POST['export_type_id'] = 2;
                if(getAutomationsForDropbox($inputData['download_category'],$file_name)){

                }else{
                    $status = sendDropbox($data, $file_name);
                    if ($status) {
                        $all_file_info[] = [
                            'file_path'=>$file_name,
                            'category_id' =>$category_id,
                            'data'=>array_filter($data)
                        ];
                        $errors = 2;
                    } else {
                        $errors = 1;
                    }
                }


                if (!empty($errorString)) {
                    $errorString .= "\n" . $row['name'] . " " . $errorMessages[$errors];
                } else {
                    $errorString = $row['name'] . " " . $errorMessages[$errors];
                }
            } elseif ($category_id == GOOGLE_DRIVE_EXPORT_TYPE) {
                $status = sendGoogleDrive($data, $zip_file);
                if ($status) {
                    $all_file_info[] = [
                        'file_path'=>$file_name,
                        'category_id' =>$category_id,
                        'data'=>array_filter($data)
                    ];
                    $errors = 8;
                } else {
                    $errors = 7;
                }

                if (!empty($errorString)) {
                    $errorString .= "\n" . $row['name'] . " " . $errorMessages[$errors];
                } else {
                    $errorString = $row['name'] . " " . $errorMessages[$errors];
                }
            } elseif ($category_id == ZAPIER_EXPORT_TYPE) {
                if (!empty($data['access_key'])) {
                    $status = sendZapier($data['access_key'], $zip_file);
                    if ($status) {
                        $all_file_info[] = [
                            'file_path'=>$file_name,
                            'category_id' =>$category_id,
                            'data'=>array_filter($data)
                        ];
                        $errors = 4;
                    } else {
                        $errors = 3;
                    }
                }

                if (!empty($errorString)) {
                    $errorString .= "\n" . $row['name'] . " " . $errorMessages[$errors];
                } else {
                    $errorString = $row['name'] . " " . $errorMessages[$errors];
                }
            } elseif ($category_id == RINGCENTRAL_EXPORT_TYPE) {
                
                $equfax_number = $data['ring_fax_equifax_number'];
                $trans_number = $data['ring_fax_trans_number'];
                $experian_number = $data['ring_fax_experian_number'];
                $fax_number = $data['destination_0'];
                
                if(!empty($data['destination_6']) && $inputData['form_id'] == 63){
                    $fax_number = $data['destination_6'];
                }
                
                if(!empty($fax_number)){
                    $fax_number = str_replace([" ", "-", ")", "("], "", $fax_number);
                }
                
                
                $fax_number_assoc_fax_content = [];
                $fax_error_status_array = [];
                
                $allPdfAndNumbers = [];
               
                $selectedDestination = true;

                if ($selectedDestination) {
                    
                    $allPdfAndNumbers[] = [
                        'fax_number'=>$fax_number,
                        'pdf'=>$file_name
                    ];
                    
                    $response = sendFaxByringcentral($allPdfAndNumbers, $data);
                    
                    $fax_number_assoc_fax_content = $response['faxinfo'];
                    $errors = 10;
                    if (!empty($fax_number_assoc_fax_content)) {
                        foreach ($fax_number_assoc_fax_content as $res) {
                            if (!$res['status']) {
                                $errors = 9;
                                break;
                            }
                        }
                    }

                   // $file = fopen("sertg_export_error.txt","a");
                   // fwrite($file, json_encode($fax_number_assoc_fax_content));// replace will be by $fax_number_assoc_fax_content
                   // fclose($file);
                    //Send email to member if has checked for this member
                    if ($data['ring_isEmailReceived'] == 1 && !empty($fax_number_assoc_fax_content)) {
                        $member_email = $_POST['member_email'];
                        //global $client_name;
                        sendEmailToMember($member_email, $fax_number_assoc_fax_content, $zip_file, $client_name);
                    }
                }
                
                if($errors == 10){
                    $all_file_info[] = [
                        'file_path'=>$file_name,
                        'category_id' =>$category_id,
                        'data'=>array_filter($data)
                    ];
                }
                
                if (!empty($errorString)) {
                    $errorString .= "\n" .$row['name']." ".$errorMessages[$errors];
                } else {
                    $errorString = $row['name']." ".$errorMessages[$errors];
                }
            } elseif ($category_id == LETTER_STREAM_TYPE) {
                $succesfully_sent_pdf_info = [];
                $api_key = $data['letter_stream_api_key'];
                $api_id = $data['letter_stream_api_id'];
                //$credit_bureau_name_address = str_replace("  ", " ", $credit_bureau_name_address);
                $info['return_address'] = letterStreamRetunAddressGenerate($data);
                //$info['from_address'] = getFormatedDFAddress(RemoveBS($credit_bureau_name_address));
                $info['from_address'] = $info['return_address'];
                $db_return_address = $info['return_address'];
                
                $info['letter_stream_name_1'] = $data['letter_stream_name_1'];
                $info['letter_stream_name_2'] = $data['letter_stream_name_2'];
                $info['client_name'] = $client_name;
                
                if($client_id > 0){
                    
                    $info['client_id'] = $client_id;
                    
                    $clientInfoFromDB = getClientIforLS($conn, $client_id);
                    
                    if(!empty($clientInfoFromDB['from'])){
                        $info['from_address'] = $clientInfoFromDB['from'];
                    }
                    
                    if(!empty($clientInfoFromDB['return_address_db'])){
                        $db_return_address = $clientInfoFromDB['return_address_db'];
                    }
                    
                    if(!empty($clientInfoFromDB['letter_stream_name_1'])){
                        $info['letter_stream_name_1'] = $clientInfoFromDB['letter_stream_name_1'];
                        $info['client_name'] = $info['letter_stream_name_1'];
                    }
                    
                    if(!empty($clientInfoFromDB['letter_stream_name_2'])){
                        $info['letter_stream_name_2'] = $clientInfoFromDB['letter_stream_name_2'];
                        if(!empty($info['client_name']) && !empty($info['letter_stream_name_2'])){
                            $info['client_name'] .= " ".$info['letter_stream_name_2'];
                        }else{
                            $info['client_name'] = $info['letter_stream_name_2'];
                        }
                    }
                    
                    if(!empty($clientInfoFromDB['db_client_count'])){
                        $info['db_client_count'] = $clientInfoFromDB['db_client_count'];
                    }
                    
                    
                }
                
                
                $info['total_pdf_pages'] = $total_pdf_pages;
                $info['file_path'] = $inputData['file_path'];
                $info['duplex'] = $inputData['is_letterstream_duplex'];
                $info['lettertypes'] = $lettertypes;
                //pr($destAssocAddress);
                if(!empty($destAssocAddress)){
                    foreach ($destAssocAddress as $dest_id => $address_list){
                        $formated_address_list = getDestinationAddressLetterStreamForFormAddress($dest_id);
                        
                        
                        if(!empty($address_list)){
                            foreach ($address_list as $address_id){
                                
                                if($dest_id == 11){
                                    
                                    $formated_to_address = RemoveBS($address_id);
                                    $formated_to_address = getFormatedDFAddress($formated_to_address);
                                    //$formated_to_address = $formated_from_address;
                                    
                                }else{
                                    
                                    $formated_from_address = $formated_address_list[current($destAssocReturnAddress[$dest_id])];
                                    $formated_to_address = $formated_address_list[$address_id];
                                }
                                
                                if(!empty($formated_from_address)){
                                    $info['from_address'] = $info['letter_stream_name_1'].":".$info['letter_stream_name_2'].":".$formated_from_address;
                                }else{
                                     $info['from_address'] = $db_return_address;
                                }
                                
                                if(!empty($formated_to_address)){
                                    $info['return_address'] = $info['letter_stream_name_1']." ".$info['letter_stream_name_2'].":".":".$formated_to_address;
                                }
                                
                                $letterStreamResponse = sendToLetterStream($conn, $api_key, $api_id, $info);
                                
                                if(!$letterStreamResponse['status']){
                                    break 2;
                                }
                                $succesfully_sent_pdf_info[] = $letterStreamResponse['letter_stream_data'];
                                if($info['db_client_count'] > 0 || $info['db_client_count'] == 0){
                                    $info['db_client_count']++;
                                }

                            }
                        }
                    }
                }
                
                // echo "
";print_r($letterStreamResponse);
                // exit;
                //
                extract($letterStreamResponse);
                
                if ($status) {
                    $all_file_info[] = [
                        'file_path'=>$file_name,
                        'category_id' =>$category_id,
                        'data'=>array_filter($data)
                    ];
                    $errors = 13;
                } else {
                    $errors = 14;
                }
                
                if (!empty($errorString)) {
                    $errorString .= "\n" . letterStreamErrorString($errors,$messages);;
                } else {
                    $errorString = letterStreamErrorString($errors,$messages);;
                }
                
            } elseif ($category_id == ONE_DRIVE_TYPE) {

                $clientId = $data['one_drive_client_id'];
                $clientSec = $data['one_drive_client_secret'];
                $token = $data['one_drive_code'];
                $attachment = $zip_file;
                $response = sendToOneDrive($clientId, $clientSec, $token, $attachment);
                if ($response['status']) {
                    $all_file_info[] = [
                        'file_path'=>$file_name,
                        'category_id' =>$category_id,
                        'data'=>array_filter($data)
                    ];
                    $errors = 11;
                } else {
                    $errors = 12;
                }
                if (!empty($errorString)) {
                    $errorString .= "\n" . "The file has been sent to your one drive.";
                } else {
                    $errorString = "The file has been sent to your one drive.";
                }
            }
            
            
        }
    }

    return ['message'=>$errorString,'status'=>$status,'data'=>$succesfully_sent_pdf_info,'all_file_info'=>$all_file_info];
}



function sendToOneDrive($clientId, $clientSec, $token, $attachment) {
    require 'vendor_onedrive/autoload.php';
    global $global_member_id;
    $result = false;
    $values = [
        'client_id' => $clientId,
        'client_secret' => $clientSec,
        'grant_type' => 'refresh_token',
        'refresh_token' => $token,
    ];
    $redirect_url = 'https://readytogoletters.com/one_drive_key_generator.php';
    //$redirect_url = 'http://localhost/rtgv4/one_drive_key_generator.php';
   // $ch = curl_init();
   // curl_setopt($ch, CURLOPT_URL, Client::TOKEN_URL);
   // curl_setopt($ch, CURLOPT_POST, 1);
   // curl_setopt($ch, CURLOPT_POSTFIELDS, $values);
   // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   // $server_output = curl_exec($ch);
   // curl_close($ch);
    
    $server_output = makeCurlRequest($values,Client::TOKEN_URL,[]);
    $res = json_decode($server_output);
   // if($global_member_id == 51){
   //     echo "
";print_r($res);exit;
   // }
    

    $graph = new Graph();
    $graph->setAccessToken($res->access_token);

    $client = new Client(
            $clientId, $graph, new GuzzleHttpClient(), [
        'state' => (object) [
            'redirect_uri' => $redirect_url,
            'token' => (object) [
                'obtained' => time(),
                'data' => $res
            ]
        ]]
    );

    $state = $client->getState();
    $generated_refresh_token = $state->token->data->refresh_token;
    //$attachment
    $myfile = file_get_contents($attachment);

    // Past this point, you can start using file/folder functions from the SDK, eg:
    $file_name = basename($attachment);
    $file = $client->getRoot()->upload($file_name, $myfile);
    //$children = $file
    if ($token != $generated_refresh_token) {
        $result = true;
    }

    return $result;
    /// one drive api code here  
}

function sendZapier($zapier_url, $fileuri) {

    $result = true;

    //Initialise the cURL var
    // $ch = curl_init();
    // converts the file into binary for sending
    $fileuri = curl_file_create(realpath($fileuri), '', '');


    // Get the response from cURL
    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //Set the Url
    // curl_setopt($ch, CURLOPT_URL, $zapier_url);

    //Create a POST array with the file in it
    $postData = array(
        'file' => $fileuri,
    );
    // curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

    // Receive server response ...
    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Execute the request
    // $response = curl_exec($ch);
    //$server_output = curl_exec($ch);
   // echo $zapier_url;exit;
    $server_output = makeCurlRequest($postData,$zapier_url,[]);
    
    if ($server_output == false) {
        $result = false;
    }


    // curl_close($ch);
    return $result;
}

function sendGoogleDrive($data, $zip_file) {
    $result = true;
    $clientId = $data['google_client_id']; //'1069879966426-fuv8et5l7abndhtttqhpofc636e3kkn3.apps.googleusercontent.com'; 
    $clientSec = $data['google_client_secret']; //'nfcvOzisrBkN4xYXBAhQtlkg'; 

    $accessToken = $data['google_token']; //'ya29.GlvvBtJrYayeGo9gsWSx622trc-kwj73uB9KVoZundmCbqrDtZ3nFkhmkcXFhluIkKsC6gc3I-z_q_NGBOcPBi_bjvlJoNhpETcvzxkOQNQwKTjH_lNfXs4fXGe1';
    $refreshToken = $data['google_refresh_token']; //'1/pG_de-9RBo4L2HvyCPgjYhVljKPZwQ2TNBgyMGIQKLHykhtDjg_uMtFc1a1HY9pf';
    //$clientId = "asdasdasd";
    $redirectUrl = 'urn:ietf:wg:oauth:2.0:oob';
    $tokenObj = '{"access_token":"' . $accessToken . '","expires_in":3600,"scope":"https:\/\/www.googleapis.com\/auth\/drive.file","token_type":"Bearer","created":1555475349,"refresh_token":"' . $refreshToken . '"}';
    $tokenPath = 'token.json';
    $file_path = realpath($zip_file);
    $file_name = basename($file_path);

    // Get the API client and construct the service object.
    $client = getGoogleClient($clientId, $clientSec, $redirectUrl, $tokenObj, $tokenPath);

    $service = new Google_Service_Drive($client);

    if ($service) {
        $mime_type = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $file_path);

        $fileMetadata = new Google_Service_Drive_DriveFile(array(
            'name' => $file_name, 'mimeType' => $mime_type));

        $content = file_get_contents($file_path);
        try {
            $file = $service->files->create($fileMetadata, array(
                'data' => $content,
                'mimeType' => $mime_type,
                'uploadType' => 'multipart',
                'fields' => 'id'));

            //printf("Upload Success. File ID: %s\n", $file->id);
        } catch (\Exception $e) {
            if (!empty($e->getMessage())) {
                errorLog("Google drive error", $e->getMessage());
            }

            $result = false;
        }
    }
    return $result;
}

/*function sendDropbox($data, $zip_file_name) {

    $result = true;
    $token = $data['dropbox_token'];
    $clientId = $data['dropbox_client_id'];
    $clientSecret = $data['dropbox_client_secret'];
    try {
        $app = new DropboxApp($clientId, $clientSecret, $token);
        $dropbox = new Dropbox($app);

        if ($dropbox) {
            $projectFolder = "testfolder";
            $src_file = $zip_file_name;
            $src_path = realpath($zip_file_name);
            $f_name = basename($src_path);
            $dpx_src_path = "/" . $f_name;
            $dropboxFile = new DropboxFile($src_path);

            $file = $dropbox->upload($dropboxFile, $dpx_src_path, ['autorename' => false]);
        }
    } catch (\Exception $e) {

        $result = false;
        if (!empty($e->getMessage())) {
            errorLog("Dropbox error", $e->getMessage());
        }
    }
    return $result;
}*/



function sendEmailToMember($memberEmail, $contents, $zip_file, $client_name) {

    $current_date = date('F m,y');
    $emailSubject = "Fax Sent at: " . $current_date;
    if (!empty($client_name)) {
        $emailSubject = "Fax Sent To: " . str_replace(" ", "_", $client_name) . "_" . $current_date;
    }
    $data['email'] = $memberEmail;
    $data['email_subject'] = $emailSubject;
    $contentString = "";
    /* $file = fopen("fax_error.txt","w");
      fwrite($file,json_encode($contents));
      fclose($file); */
    if (!empty($contents)) {
        foreach ($contents as $key => $faxinfo) {
            if ($faxinfo['status']) {
                if (!empty($contentString)) {
                    $contentString .= "

" . $faxinfo['pdf'] . " has been successfully sent to " . $faxinfo['fax_number'] . "

"; } else { $contentString = "

" . $faxinfo['pdf'] . " has been successfully sent to " . $faxinfo['fax_number'] . "

"; } } else { if (!empty($contentString)) { $contentString .= "

" . $faxinfo['pdf'] . " has been failed to sent on " . $faxinfo['fax_number'] . "

"; } else { $contentString = "

" . $faxinfo['pdf'] . " has been failed to sent on " . $faxinfo['fax_number'] . "

"; } } } } if (!empty($client_name)) { $contentString .= "

Client name : " . $client_name . "

"; } $data['email_body'] = $contentString; if (!empty($data['email'])) { sendEmail($data, $zip_file); } } function pdfInfoToJson($info,$file_path){ $json = ""; global $global_member_id; global $global_sertg_id; $client_id = 0; if(isset($_POST['client_id']) && $_POST['client_id'] > 0){ $client_id = $_POST['client_id']; } if(!empty($file_path)){ $file_path = __DIR__.$file_path."/".$global_member_id."/".$client_id."/".$global_sertg_id; if(!is_dir($file_path)){ mkdir($file_path,0777,true); } $file_path = $file_path."/".$global_sertg_id.".json"; if(file_exists($file_path)){ @unlink($file_path); } if(!empty($info)){ $json = json_encode($info); file_put_contents($file_path, $json); filePermissionSet($file_path); } } } function removeDirFilesFromDir($dir){ $dir = __DIR__.$dir; $files = glob($dir.'/*'); // get all file names if(!empty($files)){ foreach ($files as $nfile) { if (file_exists($nfile)){ @unlink($nfile); } } } } function sendFaxByringcentral($fileAndNumber, $data) { $result = ['status' => false, 'faxinfo' => []]; global $member_ID; $resultArray = []; $rcsdk = new SDK($data['ring_client_id'], $data['ring_client_secret'], $data['ring_server'], 'Fax|SMS|MMS', '1.0.0'); $platform = $rcsdk->platform(); // Authorize try { $platform->login($data['ring_account'], $data['ring_extension'], $data['ring_password']); if ($rcsdk->platform()->loggedIn()) { // echo "Yes authenticated";exit; } //$request = $rcsdk->createMultipartBuilder(); // Send Fax $faxStatusArray = []; if (!empty($fileAndNumber)) { foreach ($fileAndNumber as $faxInfo) { $request = $rcsdk->createMultipartBuilder()->setBody(array( 'to' => array( array('phoneNumber' => $faxInfo['fax_number']), ), 'faxResolution' => 'High', 'coverIndex' => 0 ))->add(fopen($faxInfo['pdf'], 'r'), basename($faxInfo['pdf'])) ->request('/account/~/extension/~/fax'); $response = $platform->sendRequest($request); $status = $response->response()->getStatusCode(); if ($status == 200) { $faxStatusArray[] = ['status' => true, 'pdf' => basename($faxInfo['pdf']), 'fax_number' => $faxInfo['fax_number'],'file_full_path'=>$faxInfo['pdf'],'db_key'=>$faxInfo['db_key'],'sequence'=>$faxInfo['sequence']]; } else { $faxStatusArray[] = ['status' => false, 'pdf' => basename($faxInfo['pdf']), 'fax_number' => $faxInfo['fax_number'],'file_full_path'=>$faxInfo['pdf'],'db_key'=>$faxInfo['db_key'],'sequence'=>$faxInfo['sequence']]; } } } // if($_POST['member_id'] == 533){ // //echo "
";print_r($fileAndNumber);exit;
       // }else{
           
       // }
        
        $result = ['status' => true, 'faxinfo' => $faxStatusArray];
    } catch (\Exception $e) {
        if (!empty($e->getMessage())) {
            global $global_member_id;
            $error_string = "Member ID: ".$global_member_id." Error message : ".$e->getMessage();
            errorLog("RingCentral Fax error", $error_string);
        }
        $result = ['status' => false, 'faxinfo' => $fileAndNumber];
    }

    return $result;
}

function checkDestinationNameExist($pdf_name) {
    $result = 0;
    if (!empty(DESTINATIONS_NAME)) {
        foreach (DESTINATIONS_NAME as $key => $dname) {
            if (strpos($pdf_name, $dname) !== false) {
                $result = $key;
                break;
            }
        }
    }

    return $result;
}


function get_destination_name() {
    $destination = ['', 'EXPERIAN DESTINATIONS', 'EQUIFAX DESTINATIONS', 'TRANS UNION DESTINATIONS',
        'INNOVIS DESTINATIONS', 'LEXISNEXIS DESTINATIONS', 'SAGESTREAM LLC DESTINATIONS',
        'CHEX SYSTEMS DESTINATIONS', 'MIB INC DESTINATIONS', 'FACTOR TRUST DESTINATIONS', 'OTHER', 'DATA FURNISHERS'];

    return $destination;
}

function getClientIforLS($conn, $client_id){
    $info = [];
    if ($client_id > 0) {
        $client_sql = "select clients.*,contacts.*"
                . " from clients INNER JOIN contacts ON contacts.client_id = clients.id "
                . "where contacts.is_primary_contact = 1 AND clients.id = $client_id";
        //echo $client_sql;exit;
        $client_sql_result = $conn->query($client_sql);
        $contact_info = [];
        if ($client_sql_result->num_rows > 0) {
            while ($row = $client_sql_result->fetch_assoc()) {
                
                $db_client_count = $row['count_letterstream'];
                
                if($db_client_count > 0){
                    $info['db_client_count'] = $db_client_count;
                }
                
                if ($row['is_letterstream_return_address'] == 1) {
                    $contact_info['letter_stream_name_1'] = $row['first_name'];
                    $contact_info['letter_stream_name_2'] = $row['last_name'];
                    $contact_info['letter_stream_address_1'] = $row['address'];
                    $contact_info['letter_stream_address_2'] = "";
                    $contact_info['letter_stream_city'] = $row['city'];
                    $contact_info['letter_stream_state'] = $row['state'];
                    $contact_info['letter_stream_zip'] = $row['zip_code'];
                    $info['from'] = letterStreamRetunAddressGenerate($contact_info);
                    $info['return_address_db'] = $info['from'];
                    $info['letter_stream_name_1'] = $contact_info['letter_stream_name_1'];
                    $info['letter_stream_name_2'] = $contact_info['letter_stream_name_2'];
                }
            }
        }
    }
    
    return $info;
}



function sendToLetterStream($conn, $api_key, $api_id, $info) {

    $db_client_count = time();
    
    if($info['db_client_count'] > 0){
        $db_client_count = $info['db_client_count'];
    }
    
    $client_id = $info['client_id'];
    
    $mailType = "firstclass";
    if(isset($_POST['mailType']) && $_POST['mailType'] == 'certified'){
        $mailType = "certified";
    }
    
    

    $unique_id = uniqueIdGenerateForLetterStream($client_id,$db_client_count); //this will only be accepted by our system one time
    $string_to_hash = substr($unique_id, -6) . $api_key . substr($unique_id, 0, 6);
    $hash = md5(base64_encode($string_to_hash));
    $data = array('a' => $api_id, 'h' => $hash, 't' => $unique_id);

    $new_return_address = $info['return_address'];
    $from_address = $info['from_address'];
    $pdf_path = $info['file_path'];
    $is_letterstream_duplex = $info['duplex'];
    
    
    $no_of_jobs = 1;
    
    $pi_di_str = $info['lettertypes'];
    
    
    //$db_client_count++;
   // $job_name = $info['client_name'] . strtotime(date('m/d/y H:i:s'));
    //echo $info['client_name']."====".$db_client_count."=====".$no_of_jobs."======".$client_id."=====".$pi_di_str;exit;
    $job_name = getJobName($info['client_name'], $db_client_count, $no_of_jobs, $client_id, $pi_di_str);
    
    // Update By 1 before sending  to letter stream
    updateLetterStreamCount($conn,$db_client_count,$no_of_jobs,$client_id);
    
    $data['job'] = $job_name;
    $data['from'] = $from_address;
    $data['responseformat'] = 'json';
    $data['to[]'] = $unique_id . ':' . $new_return_address;
    $data['debug'] = 3;
    $data['coversheet'] = 'Y';
    $data['duplex'] = $is_letterstream_duplex;
    $data['mailtype'] = $mailType;
    $data['single_file'] = curl_file_create(realpath($pdf_path));
    $data['pages'] = $info['total_pdf_pages'];
    //return $data;
    $URL = LETTER_STREAM_API;
    $response = makeCurlRequest($data, $URL, []);
    $response = json_decode($response);
    
    $authOk = false;
    $isUploaded = false;
    $authSuccess = $response->message[0]->code; // Auth success code -199
    $uploadSuccess = $response->message[1]->code; // Upload success code -105
    $authSuccess = trim($authSuccess);
    $uploadSuccess = trim($uploadSuccess);

    //pr($data);
    if ($authSuccess == -199 && ($uploadSuccess == -105 || $uploadSuccess == -100 )) {
        $successfully_sent_pdf = [
                        'file_path'=>$pdf_path,
                        'from_address'=>$data['from'],
                        'return_address'=>$new_return_address,
                        'duplex'=> $data['duplex'],
                        'mailType'=>$data['mailtype']
                    ];
        $finalresponse = ['status' => true, 'errorcode' => "",'letter_stream_data'=>$successfully_sent_pdf];
    } else {
        $isBureaus = false;
        $finalresponse = ['status' => false, 'errorcode' => $uploadSuccess];
        $letter_stream_info_for_log = json_encode($data);
        $letter_stream_info_for_log .= " #Client name : " . $client_name;
        $errorString = "#AuthStatus:" . $authSuccess . "#UploadStatus:" . $uploadSuccess .
                "#From Address:" . $info['from'] . "#To:" . $unique_id . ':' . $addressesByDestinationId[$address_id] . "#File Path:" . $pdf_path;
        errorLog("LetterStream rtg letters", $errorString . $letter_stream_info_for_log);
    }
    
    return $finalresponse;
}


function rtgerrorLog($data){
    $file = fopen(__DIR__."/rtg_letter_errors.txt","a");
    fwrite($file,json_encode($data));
    fclose($file);
}

function setAutomation($conn, $data,$velocity_type = 3) {
    //pr($data);
    $data['day_value'] = $data['day_value'];
    $data['automation_type'] = $data['automation_type'];
    $sql = "SELECT * FROM automation_schedules WHERE sertg_id = " . $data['sertg_id'];
    $process_count = 0;
    $current_date_time = date('Y-m-d H:i:s');
    if($data['automation_type'] == 4){
        $process_count = 1;
    }
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        if (isset($data['set_automation']) && $data['set_automation'] == 1) {
            $sql2 = "update automation_schedules set sertg_id = " . $data['sertg_id'] . ", "
                    . "member_id = " . $data['member_id'] . ", client_id ="
                    . " " . $data['client_id'] . ", type = " . $data['automation_type'] . ", velocity_type = ".$velocity_type.","
                    ."process_count = {$process_count},"
                    . "day_value = " . $data['day_value'] . ", modified_on = '" . $current_date_time . "',is_process = 0,last_process_datetime ='".$current_date_time."' where id = " . $row['id'];
        } else {
            $sql2 = "Delete from automation_schedules where id = " . $row['id'];
        }
    } else {
        $sql2 = "Insert into automation_schedules "
                . "(sertg_id,member_id,client_id,velocity_type,type,day_value,created_on,last_process_datetime,process_count) values (" .
                $data['sertg_id'] . "," . $data['member_id'] . ","
                . "" . $data['client_id'] . ", ".$velocity_type.", " . $data['automation_type'] . ", " . $data['day_value'] . ", '" . $current_date_time . "','".$current_date_time."',{$process_count})";
    }

    $final_result = $conn->query($sql2);
    
    if (isset($data['download_category']) && !empty($data['download_category'])) {
        $automationData['automation_id_list'] = $data['download_category'];
        $automation_schedule_id = $row['id'];
        if (!empty($automation_schedule_id) && $automation_schedule_id > 0) {
            deleteAutomationScheduleExportByAutomationScheduleId($conn, $automation_schedule_id);
        }
        if ($conn->insert_id > 0) {
            $automation_schedule_id = $conn->insert_id;
        }
        insertAutomationScheduleExport($conn, $automation_schedule_id, $automationData);
    }

    return $final_result;
}

function deleteAutomationScheduleExportByAutomationScheduleId($conn, $automation_schedule_id) {
    $sql = "DELETE FROM `automation_schedule_exports` WHERE `automation_schedule_id` = " . $automation_schedule_id;
    $result = $conn->query($sql);
}

function insertAutomationScheduleExport($conn, $automation_schedule_id, $data) {
    $current_date_time = date('Y-m-d H:i:s');
    $sql = "INSERT INTO automation_schedule_exports (automation_schedule_id,automation_id,created_on,modified_on) VALUES ";
    
    $insert_string = "";
    if (!empty($data['automation_id_list']) && $automation_schedule_id > 0) {
        foreach ($data['automation_id_list'] as $automation_id) {
            if (!empty($insert_string)) {
                $insert_string .= ",(" . $automation_schedule_id . "," . $automation_id . ",'" . $current_date_time . "','" . $current_date_time . "')";
            } else {
                $insert_string = "(" . $automation_schedule_id . "," . $automation_id . ",'" . $current_date_time . "','" . $current_date_time . "')";
            }
        }
        $sql .= $insert_string;
    }

    $result = $conn->query($sql);
}

function  isInconsistentClientId($conn, $inputData){
    $result = true;
    $sql = "SELECT * FROM clients where id = ".$inputData['client_id']." and cmsuser_id = ".$inputData['member_id'];
    //echo $sql;exit;
    $result = $conn->query($sql);
    //echo "
";print_r($result);exit;
    if($result->num_rows == 0){
       $result = false;
    }
    
    return $result;
}


function saveRTGLetters($conn, $inputData){
    $auth_user = getAuthUser();
    $user_type_name = getCurrentUserInfo();
    $employee_id = 0;
    if($user_type_name == "EMPLOYEE"){
        $employee_id = $auth_user['user_id'];
    }
    //isInconsistentClientId($conn, $inputData);
    $rtg_letters_id = "";
    $next_action_date = null;
    if(!empty($inputData['next_action_date'])){
        $next_action_date = $inputData['next_action_date'];
    }

    //if($_SESSION['userType'] )
    $dob = $inputData['dob'];
    $ssn = $inputData['ssn'];
    $member_id = $inputData['member_id'];
    $client_id = $inputData['client_id'];
    $report_type = $inputData['report_type'];
    $form_id = $inputData['form_id'];
    $form_data = $inputData['form_data'];
    $form_data = $conn->real_escape_string($form_data);
    $current_date_time = date('Y-m-d H:i:s');
    $lettertypes = implode(",", $inputData['lettertypes']);
    
    if(empty($report_type)){
        $report_type = 0;
    }
    
    $sql = 'insert into rtg_letters (employee_id, member_id, client_id,form_id, report_type,dob,ssn,lettertypes, data,next_action_date, created_at,updated_at) values(';
    $sql .= $employee_id.",";
    $sql .= $member_id.",".$client_id.",".$form_id.",".$report_type.",'".$dob."','".$ssn."','".$lettertypes."','".$form_data."','".$next_action_date."','".$current_date_time."','".$current_date_time."')";

    if ($conn->query($sql) === TRUE) {
        $rtg_letters_id = mysqli_insert_id($conn);
    }


    return $rtg_letters_id;
}

function updateRTGLetters($conn, $id, $inputData){
    //pr($inputData);exit;
    //isInconsistentClientId($conn, $inputData);
    $rtg_letters_id = 0;
    $next_action_date = null;
    if(!empty($inputData['next_action_date'])){
        $next_action_date = $inputData['next_action_date'];
    }
    $dob = $inputData['dob'];
    $ssn = $inputData['ssn'];
    $member_id = $inputData['member_id'];
    $client_id = $inputData['client_id'];
    $report_type = $inputData['report_type'];
    $form_id = $inputData['form_id'];
    $form_data = $inputData['form_data'];
    //$form_data = addslashes($form_data);
    $form_data = $conn->real_escape_string($form_data);
    
    $current_date_time = date('Y-m-d H:i:s');
    $lettertypes = implode(",", $inputData['lettertypes']);
    
    $sql = "UPDATE rtg_letters SET "
            . "dob='$dob', "
            . "ssn='$ssn', "
            . "member_id=$member_id, "
            . "client_id=$client_id, "
            . "report_type=$report_type, "
            . "lettertypes='$lettertypes', "
            . "data='$form_data', "
            . "next_action_date='$next_action_date', "
            . "updated_at='$current_date_time' "
            . "WHERE id = ".$id;
   // $sql = 'insert into rtg_letters (member_id, client_id,form_id, report_type,lettertypes, data,next_action_date, created_at) values(';
   // $sql .= $member_id.",".$client_id.",".$form_id.",".$report_type.",'".$lettertypes."','".$form_data."','".$next_action_date."','".$current_date_time."')";
   
   //  echo $sql;exit;     
    if ($conn->query($sql) === TRUE) {
        $rtg_letters_id = $id;
    }
    
    return $rtg_letters_id;
}


function letterEmailSendToClient($conn, $inputData) {
    
    $client_name = $inputData['client_name'];
    $client_email = $inputData['client_email'];
    $next_sending_email_date = $inputData['next_sending_email_date'];
    $selected_letter_type = $inputData['letter_type'];
    $letter_send_date_tmezone = $inputData['letter_send_date_tmezone'];
    $member_id = $inputData['member_id'];

    if (isset($inputData['set_schedule']) && $inputData['set_schedule'] == 1) {
        $member_sql = "select * from cmsusers where id = ".$member_id;
        $sel =  $conn->query($member_sql);
        while($row1 = $sel->fetch_assoc()) {
            $letter_email_signature = $row1['letter_email_signature'];
        }
        
        
        
        if ($selected_letter_type > 0 && !empty($next_sending_email_date) && !empty($next_sending_email_date)) {
            $sql = "INSERT INTO letter_email_schedules (member_id, client_email,client_name, datetime,letter_set, gmt,letter_email_signature) VALUES ($member_id,'$client_email','$client_name', '$next_sending_email_date',$selected_letter_type, '$letter_send_date_tmezone','$letter_email_signature')";
            $conn->query($sql);
        }
    } else {
        if ($selected_letter_type > 0) {
            //LETTER_TYPE_FOR_MAIL
            $data['email'] = $client_email;
            $data['email_subject'] = "Great News! We Have Started Your " . LETTER_TYPE_FOR_MAIL[$selected_letter_type] . " Set Of Letters";
            $email_body = "Hello " . $client_name . ",
We have just started your " . LETTER_TYPE_FOR_MAIL[$selected_letter_type] . " Set of Letters. We are notifying you to let you know." . "
We will keep you updated on all updates and Wins as they come in. " . "Thank you For choosing Us We look forward to helping you through this Journey.



"; $email_body .= nl2br($letter_email_signature); $letter_info = getLetterSetEmailContent($conn,$_POST['member_id'],$selected_letter_type); if(!empty($letter_info['email_subject'])){ $data['email_subject'] = $letter_info['email_subject']; } if(!empty($letter_info['email_body'])){ $email_body = nl2br($letter_info['email_body']); $email_body = str_replace('[client_name]', $client_name, $email_body); } $data['email_body'] = $email_body; sendRTGEmail($data, "", "DO NOT REPLY"); } } } function copyPdfToAnotherDir($file,$destination = "/../rtg_letters/letterstream/",$rtg_letter_id,$inputData){ $client_id = 0; $destination .= $inputData['member_id']; if(isset($inputData['client_id']) && $inputData['client_id'] > 0){ $client_id = $inputData['client_id']; } if(!empty($destination)){ $destination = __DIR__.$destination."/".$client_id."/"; } $file_path = ""; if(!empty($destination) && !empty($rtg_letter_id)){ $file_path = $destination.$rtg_letter_id; } if(!is_dir($file_path)){ mkdir($file_path,0777,true); } $files = glob($file_path."/*"); // get all file names foreach($files as $mfile){ // iterate files if(is_file($mfile)) @unlink($mfile); // delete file } $file_name = basename($file); if(!empty($file_path) && !empty($file_name)){ copy($file,$file_path."/".$file_name); } if(!empty($inputData['ls_data'])){ $json = json_encode($inputData['ls_data']); $json_file_path = $file_path."/".$rtg_letter_id.".json"; if(file_exists($json_file_path)){ @unlink($json_file_path); } file_put_contents($json_file_path, $json); } //ls_data } function getGoogleClient($clientId, $clientSec, $redirectUrl, $tokenObj = '', $tokenPath = '') { $client = new Google_Client(); $client->setApplicationName('RTG Google Drive API Quickstart'); $client->setScopes(Google_Service_Drive::DRIVE_FILE); $client->setClientId($clientId); $client->setClientSecret($clientSec); $client->setRedirectUri($redirectUrl); $client->setAccessType('offline'); $client->setApprovalPrompt('auto'); // Load previously authorized token from a file, if it exists. // The file token.json stores the user's access and refresh tokens, and is // created automatically when the authorization flow completes for the first // time. if (file_exists($tokenPath) && is_file($tokenPath)) { $accessTokenArray = json_decode(file_get_contents($tokenPath), true); if ($accessTokenArray != null) { $client->setAccessToken($accessTokenArray); $accessToken = $accessTokenArray; } } else if (is_string($tokenObj) && $tokenObj != null && $tokenObj != '') { $accessTokenArray = json_decode($tokenObj, true); $client->setAccessToken($accessTokenArray); // $accessToken = $accessTokenArray['access_token']; } // If there is no previous token or it's expired. if ($client->isAccessTokenExpired()) { // Refresh the token if possible, else fetch a new one. if ($client->getRefreshToken()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); } else { // Request authorization from the user. $authUrl = $client->createAuthUrl(); echo ' Document Click to Generate Token '; print '
'; if (isset($_GET['verify']) && $_GET['verify'] != '') { $authCode = $_GET['verify']; // header('location: '. $authUrl); // Exchange authorization code for an access token. if (isset($authCode)) { // $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); $client->setAccessToken($accessToken); } // Check to see if there was an error. if (array_key_exists('error', $accessToken)) { throw new Exception(join(', ', $accessToken)); } } } // Save the token to a file. // if (!file_exists(dirname($tokenPath))) { // mkdir(dirname($tokenPath), 0700, true); // } // file_put_contents($tokenPath, json_encode($client->getAccessToken())); } return $client; } //function errorLog($type, $error) { // $current_date = date('Y-m-d H:i:s'); // $file = fopen("rtg_letters_error.txt", "a"); // fwrite($file, "\n\n" . $current_date . " : " . $type . " : " . $error); // fclose($file); //}