<?php

namespace App\Http\Controllers;

use App\Models\UserWave;
use App\Services\CreditReportService;
use App\Utility\createDirZip;
use App\Utility\Email;
use App\Utility\PdfWriter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class EpicVelocityController extends Controller
{
    private $pdfObj = null;
    private $message;
    private $code;
    private $data;
    public function __construct()
    {
        $this->message = 'Fail';
        $this->code = config('constant.API_FAILED_CODE');
        $this->data=[];
    }
    public function generatepdf(Request $req) {
        $logData['action'] = 'GENERATE LETTER';
        $time = config('constant.MAX_TIME_LIMIT') ?? 60;
        set_time_limit($time);
        $universal = array();
        $pdf_layout_array = [
            '1' => 'lg-pdf',
            '2' => 'lg-pdf',
            '3' => 'lg-pdf',
            '4' => 'lg-pdf',
            '5' => 'lg-pdf',
            '6' => 'lg-pdf2',
            '7' => 'lg-pdf2',
            '8' => 'lg-pdf2',
            '9' => 'lg-pdf2',
            '10' => 'lg-pdf2',
            '11' => 'lg-pdf2',
            '12' => 'lg-pdf2',
            '13' => 'lg-pdf2',
            '14' => 'lg-pdf2',
            '15' => 'lg-pdf2',
            '16' => 'lg-pdf2',
            '17' => 'lg-pdf2',
            '18' => 'lg-pdf',
            '19' => 'lg-pdf2',
            '20' => 'lg-pdf2',
            '21' => 'lg-pdf2',
            '22' => 'lg-pdf2',
            '23' => 'lg-pdf2',
            '24' => 'lg-pdf2',
            '26' => 'lg-pdf2',
            '27' => 'lg-pdf2',
            '28' => 'lg-pdf2',
            '29' => 'lg-pdf2',
            '30' => 'lg-pdf2',
            '31' => 'lg-pdf2',
            '32' => 'lg-pdf2',
            '33' => 'lg-pdf2',
            '34' => 'lg-pdf2',
            '35' => 'lg-pdf2',
            '36' => 'lg-pdf2',
            '37' => 'lg-pdf2',
            '38' => 'lg-pdf2',
            '39' => 'lg-pdf2',
            '40' => 'lg-pdf2',
            '41' => 'lg-pdf2',
            '42' => 'lg-pdf2',
            '43' => 'lg-pdf2',
            '44' => 'lg-pdf2',
            '45' => 'lg-pdf2',
            '46' => 'lg-pdf2',
            '47' => 'lg-pdf2',
            '48' => 'lg-pdf2',
            '49' => 'lg-pdf2',
            '50' => 'lg-pdf2',
            '51' => 'lg-pdf2',
            '52' => 'lg-pdf2',
            '53' => 'lg-pdf2',
            '54' => 'lg-pdf2',
            '55' => 'lg-pdf2',
            '56' => 'lg-pdf2',
            '57' => 'lg-pdf2',
            '58' => 'lg-pdf2',
            '59' => 'lg-pdf2',
            '60' => 'lg-pdf2',
            '61' => 'lg-pdf2',
            '62' => 'lg-pdf2',
            '63' => 'lg-pdf2',
            '64' => 'lg-pdf2',
            '65' => 'lg-pdf2',
            '66' => 'lg-pdf2',
            '67' => 'lg-pdf2',
            '68' => 'lg-pdf2',
            '69' => 'lg-pdf2',
            '70' => 'lg-pdf2',
            '71' => 'lg-pdf2',
            '72' => 'lg-pdf2',
        ];
        $request = $req->all();

        $auth_user = auth()->user();
        $client_id = $auth_user->id;
        $request['client_email'] = "";
        $logData['email'] = $auth_user->email;
        $type_name = '';

        $current_html_content = $request['current_html_content'];

        if (empty($id)) {
            $id = isset($request['letter_id']) ? $request['letter_id'] : null;
        }


        $fileTypeString = "";
        if (!empty($selectedLetterTypes)) {
            foreach ($selectedLetterTypes as $type) {
                if (!empty($fileTypeString) && $fileTypeString != "_") {
                    $fileTypeString .= "_" . $lettesTypes->{$type};
                } else {
                    $fileTypeString = $lettesTypes->{$type};
                }
            }
        }
        $universal['today'] = $request['today'];
        $universal['cr_resource'] = $request['cr_resource'];
        $universal['name'] = $request['name'];
        $universal['address'] = $request['address'];
        $universal['dob'] = trim($request['dob']);
        $ssn = $auth_user->ssn;
        $universal['ssn'] = substr($ssn, -4); // get only last 4 digits of ssn.
        $universal['p_tracking_number'] = $request['p_tracking_number'];

        $destinations = array();
        $additional_destionations1 = [];
        $additional_destionations2 = [];
        $EXP_1 = "EXPERIAN PO BOX 9701, ALLEN, TX 75013";
        $EXP_2 = "EXPERIAN PO BOX 4500, ALLEN, TX 75013";
        $EQF_1 = "EQUIFAX PO Box740256, ATLANTA,GA 30374-0256";
        $EQF_2 = "EQUIFAX PO Box740241, ATLANTA,GA 30374-0241";
        $TRANS_1 = "Trans Union PO Box 2000, CHESTER, PA 19016-2000";;
        $TRANS_2 = "Trans Union PO Box 1000, CHESTER, PA 19022-1000";
        $TRANS_3 = "Trans Union PO Box 2000, CHESTER, PA 19022-2000";

        $destinations[] = $EXP_1;
        $destinations[] = $EXP_2;
        $destinations[] = $EQF_1;
        $destinations[] = $EQF_2;
        $destinations[] = $TRANS_1;
        $destinations[] = $TRANS_2;
        $destinations[] = $TRANS_3;

        $additional_destionations1[$EXP_1] = "Attn Darryl Gibson,<br/>Esq. (or acting/current Group General Counsel),<br/>Experian Information Solutions, Inc.,<br/>475 Anton Blvd.,<br/> Costa Mesa, CA 92626";
        $additional_destionations1[$EXP_2] = "Attn Darryl Gibson,<br/>Esq. (or acting/current Group General Counsel),<br/>Experian Information Solutions, Inc.,<br/>475 Anton Blvd.,<br/> Costa Mesa, CA 92626";

        $additional_destionations2[$EXP_1] = "Experian POB 9701, ATTN Consumer Fraud Department, Allen, TX 75013";
        $additional_destionations2[$EXP_2] = "Experian POB 9701, ATTN Consumer Fraud Department, Allen, TX 75013";

        $additional_destionations1[$EQF_1] = "ATTN John J. Kelley, III,<br/>Esq. (or acting/current CHIEF LEGAL OFFICER),<br/>Equifax Information services LLC.<br/>1550 Peachtree Street, N.W.,<br/>ATLANTA, GA 30309";
        $additional_destionations1[$EQF_2] = "ATTN John J. Kelley, III,<br/>Esq. (or acting/current CHIEF LEGAL OFFICER),<br/>Equifax Information services LLC.<br/>1550 Peachtree Street, N.W.,<br/>ATLANTA, GA 30309";

        $additional_destionations2[$EQF_1] = "EQUIFAX , ATTN FRAUD DEPARTMENT,POB 740256,  ATLANTA, GA 30374-0256";
        $additional_destionations2[$EQF_2] = "EQUIFAX , ATTN FRAUD DEPARTMENT,POB 740256,  ATLANTA, GA 30374-0256";

        $additional_destionations1[$TRANS_1] = "Attn: john Blenke ,<br/>Esq. (acting or current EVP and GENERAL COUNSEL),<br/>Transunion LLC,<br/>555 W. Adams Street,<br/>CHICAGO, IL";
        $additional_destionations1[$TRANS_2] = "Attn: john Blenke ,<br/>Esq. (acting or current EVP and GENERAL COUNSEL),<br/>Transunion LLC,<br/>555 W. Adams Street,<br/>CHICAGO, IL";
        $additional_destionations1[$TRANS_3] = "Attn: john Blenke ,<br/>Esq. (acting or current EVP and GENERAL COUNSEL),<br/>Transunion LLC,<br/>555 W. Adams Street,<br/>CHICAGO, IL";

        $additional_destionations2[$TRANS_1] = "Trans Union, Attn FRAUD DEPARTMENT, POB 2000, Chester , PA 19016-2000";
        $additional_destionations2[$TRANS_2] = "Trans Union, Attn FRAUD DEPARTMENT, POB 2000, Chester , PA 19016-2000";
        $additional_destionations2[$TRANS_3] = "Trans Union, Attn FRAUD DEPARTMENT, POB 2000, Chester , PA 19016-2000";

        /*$destinations[] = "EXPERIAN PO BOX 9701, ALLEN, TX 75013";
        $destinations[] = "EXPERIAN PO BOX 4500, ALLEN, TX 75013";
        $destinations[] = "EQUIFAX PO Box740256, ATLANTA,GA 30374-0256";
        $destinations[] = "EQUIFAX PO Box740241, ATLANTA,GA 30374-0241";
        $destinations[] = "Trans Union PO Box 2000, CHESTER, PA 19016-2000";
        $destinations[] = "Trans Union PO Box 1000, CHESTER, PA 19022-1000";
        $destinations[] = "Trans Union PO Box 2000, CHESTER, PA 19022-2000";*/
        $destinations[] = "INNOVIS PO Box 1640, Pittsburgh, PA 15230-1640";
        $destinations[] = "Innovis Consumer Assistance PO Box 530088, Atlanta, GA 30353-0088";
        $destinations[] = "LexisNexis PO Box 105108, Atlanta, GA 30348";
        $destinations[] = "SageStream, LLC, LexisNexis Risk Solutions Consumer Center P. O. Box 105108. Atlanta, Georgia 30348-5108";
        $destinations[] = "Chex Systems ATTN: Consumer Relations, 7805 Hudson Rd., Ste. 100, Woodbury, MN 55125";
        $destinations[] = "(US RESIDENTS) MIB Inc 50 Braintree Hill Park, Suite 400, Braintree, MA 02184-8734";
        $destinations[] = "(CANADIAN RESIDENTS) MIB Inc 330 university Avenue, Suite 501, Toronto, Canada M5G 1R7";
        $destinations[] = "FactorTrust PO Box 3653,Alpharhetta, GA 30023";

        $info_item = $request['info_item'];

        $data = array(); //main data array
        $files = array();
        $excludes = array();
        if (isset($request['info_item']['file']))
            $files = $request['info_item']['file'];
        if (isset($request['info_item']['exclude']))
            $excludes = $request['info_item']['exclude'];
        $univ_dest = $request['destination'];


        $content_image = array();
        $img_bottom = array();
        $excluded_array_keys = [];
        $letterImagesDirectory = "/epicvelocity/letters/account";
        $letterAttachmentDirectory = "/epicvelocity/letters/attachment";
        $letterImagesDirectory = storage_path($letterImagesDirectory);
        $letterAttachmentDirectory = storage_path($letterAttachmentDirectory);
        if ($request['action'] == 'new') {
            // for new upload file in account part
            if (!empty($request['letter_image_file'])) {
                $target_file = $letterImagesDirectory . '/' . $auth_user->id;
                if (!is_dir($target_file)) {
                    mkdir($target_file, 0777, true);
                }
                $image_count = 0;
                foreach ($request['letter_image_file'] as $keyf => $image) {
                    if (!in_array($keyf, $excluded_array_keys)) {
                        if (!empty($image)) {
                            $image_count++;
                            $temp = $auth_user->id . "_" . $image_count . time() . ".jpg";
                            $dataImg = str_replace('data:image/jpeg;base64,', '', $image);
                            $dataImg = base64_decode($dataImg);
                            $targeted_file = $target_file . "/" . $temp;
                            file_put_contents($targeted_file, $dataImg);
                            $this->filePermissionSet($targeted_file);
                            $content_image[$keyf] = $auth_user->id . "/" . $temp;
                        }
                    }
                }
            }

            //dd($request['attach_image_file']);
            // for existing file in attachment part
            if (!empty($request['attach_image_file'])) {
                $target_file_attachment = ltrim($letterAttachmentDirectory,"/") . '/' . $auth_user->id;
                if (!is_dir($target_file_attachment)) {
                    // mkdir($target_file_attachment, 0777, true);
                }

                $attach_count = 0;
                //dd($request['attach_image_file'],count($request['attach_image_file']));
                foreach ($request['attach_image_file'] as $keyf_attach => $attach) {

                    $isUploadMedia = $request['isUploadMedia'][$keyf_attach];
                    if (!in_array($keyf_attach, $excluded_array_keys)) {
                        if (!empty($attach)) {
                            $attach_count++;
                            $temp = $auth_user->id . "_" . $attach_count . time() . ".jpg";
                            $targeted_attach_file = $target_file_attachment . "/" . $temp;
                            //dd(getPublicFile($attach),$attach);
                            if ($isUploadMedia == 1) {
                                // copy(ltrim($attach,"/"), $targeted_attach_file);
                                //$img_bottom[$keyf_attach] = $attach;
                                $img_bottom[$keyf_attach] = '<img style="width: 100%;margin-top: 20px" src="'.getPublicFile($attach).'" >';
                                //$img_bottom[$keyf_attach] = "";
                            } else {
                                /*dd($attach);
                                $dataImg = str_replace('data:image/jpeg;base64,', '', $attach);
                                $dataImg = base64_decode($dataImg);
                                file_put_contents($targeted_attach_file, $dataImg);
                                $this->filePermissionSet($targeted_attach_file);*/
                                $img_bottom[$keyf_attach] = '<img src="'.$attach.'" style="width:100%;margin-top: 20px" />';
                            }
                            //$img_bottom[$keyf_attach] = $this->Auth->user('id') . "/" . $temp;
                            //$img_bottom[$keyf_attach] = $this->Auth->user('id') . "/" . $temp;
                        }
                    }
                }
            }


        }
        else if ($request['action'] == 'edit' || $request['action'] == 'create_new') {

            // for account part
            if (!empty($request['isImageChange'])) {
                $target_file = $letterImagesDirectory . '/' . $this->Auth->user('id');
                if (!is_dir($target_file)) {
                    mkdir($target_file, 0777, true);
                }
                $image_count = 0;
                foreach ($request['isImageChange'] as $imageFileKey => $value) {
                    $image = $request['letter_image_file'][$imageFileKey];
                    $oldImage = $request['oldImage'][$imageFileKey];
                    if (!in_array($imageFileKey, $excluded_array_keys)) {
                        if ($value == 2) { // 2 for new upload Image
                            if (!empty($image)) {
                                unlink($letterImagesDirectory . '/' . $oldImage);
                                $image_count++;
                                $temp = $this->Auth->user('id') . "_" . $image_count . time() . ".jpg";
                                $dataImg = str_replace('data:image/jpeg;base64,', '', $image);
                                $dataImg = base64_decode($dataImg);
                                $targeted_file = $target_file . "/" . $temp;
                                file_put_contents($targeted_file, $dataImg);
                                $this->filePermissionSet($targeted_file);
                                $content_image[$imageFileKey] = $this->Auth->user('id') . "/" . $temp;
                            }
                        } else if ($value == 1) { // 1 for remove image
                            unlink($letterImagesDirectory . '/' . $oldImage);
                        } else if ($value == 0) {
                            $content_image[$imageFileKey] = $image;
                        }
                    }
                }
            }

            // for attachment part

            if (!empty($request['isAttImageChange'])) {
                $target_file = $letterAttachmentDirectory . '/' . $this->Auth->user('id');
                if (!is_dir($target_file)) {
                    mkdir($target_file, 0777, true);
                }
                $image_att_count = 0;
                foreach ($request['isAttImageChange'] as $imageAttFileKey => $value_attach) {
                    $image_att = $request['attach_image_file'][$imageAttFileKey];
                    $oldImage_att = $request['oldAttImage'][$imageAttFileKey];
                    if (!in_array($imageAttFileKey, $excluded_array_keys)) {
                        if ($value_attach == 2) { // 2 for new upload Image
                            if (!empty($image_att)) {
                                unlink($letterAttachmentDirectory . '/' . $oldImage_att);
                                $image_att_count++;
                                $temp = $this->Auth->user('id') . "_" . $image_att_count . time() . ".jpg";
                                $dataImg = str_replace('data:image/jpeg;base64,', '', $image_att);
                                $dataImg = base64_decode($dataImg);
                                $targeted_file = $target_file . "/" . $temp;
                                file_put_contents($targeted_file, $dataImg);
                                $this->filePermissionSet($targeted_file);
                                $img_bottom[$imageAttFileKey] = $this->Auth->user('id') . "/" . $temp;
                            }
                        } else if ($value_attach == 1) { // 1 for remove image
                            unlink($letterAttachmentDirectory . '/' . $oldImage_att);
                        } else if ($value_attach == 0) {
                            $img_bottom[$imageAttFileKey] = $oldImage_att;
                        }
                    }
                }
            }
        }

        $db_content_image = $content_image;
        //dd($db_content_image);
        if (!isset($request['info_item'])) {
            //flash('No Content Box added');
            //return $this->redirect($this->referer());
            return  back()->with('error','No Content Box added');
        }
        $info_item['dest'] = array_values($info_item['dest']);
        $final_content_image = [];
        $new_dest_content_assoc = [];
        if (!empty($info_item['dest'])) {
            foreach ($info_item['dest'] as $dest_key => $dest) {
                if (!empty($dest)) {
                    foreach ($dest as $current_dest) {
                        if (!empty($current_dest) && $current_dest != 1) {
                            $new_dest_content_assoc[$current_dest][] = $info_item['content'][$dest_key];
                        }
                    }
                }
            }
        }

        if (!isset($request['bureau_only']) && !isset($request['df_only'])){
            $request['bureau_only'] = 1;
            $request['df_only'] = 1;
        }

        if (isset($request['bureau_only'])) {
            foreach ($info_item['template'] as $key => $value) {

                if (array_key_exists($key, $excludes))
                    continue;
                $data[$value]['type'] = 'bureau';
                $data[$value]['template'][] = $value;
                $data[$value]['wave'][] = $info_item['wave'][$key];
                $data[$value]['letter_type'][] = $info_item['letter_type'][$key];

                if(isset($info_item['content'][$key])) {
                    $data[$value]['content'][] = $info_item['content'][$key];
                }

                $a1 = array();

                if (isset($info_item['dest'][$key])) {
                    foreach ($info_item['dest'][$key] as $key2 => $value2) {
                        if (in_array($value2, $destinations)) {
                            $a1[] = $value2;
                        }
                    }
                }
                if (isset($univ_dest)) {
                    $a1 = array_merge($a1, $univ_dest);
                }
                $data[$value]['dest'][] = array_filter(array_unique($a1));

                if (array_key_exists($key, $files)) {
                    $data[$value]['file'][] = $files[$key];
                    $final_content_image[$value][] = $content_image[$key];
                }
                if (array_key_exists($key, $request['letter_image_file']))
                    $data[$value]['letter_image_file'][] = $request['letter_image_file'][$key];
            }
        }


        $key_index = 400;

        if (isset($request['df_only'])) {

            foreach ($info_item['template_df'] as $key => $value) {

                if (empty(trim($value)))
                    continue;
                if (array_key_exists($key, $excludes)) {
                    continue;
                }



                $template_id = explode('_', $value);
                $template_id = $template_id[1];

                $data[$key_index]['type'] = 'creditor';
                $data[$key_index]['template'][] = $value;
                $data[$key_index]['wave'][] = $info_item['wave'][$key];
                $data[$key_index]['letter_type'][] = $info_item['letter_type'][$key];
                $data[$key_index]['content'][] = $info_item['content'][$key];

                $a1 = array();

                if (isset($info_item['dest'][$key])) {
                    foreach ($info_item['dest'][$key] as $key2 => $value2) {
                        if (empty(trim($value)))
                            continue;
                        if (!in_array($value2, $destinations)) {
                            $a1[] = $value2;
                        }
                    }
                }
                $data[$key_index]['dest'][] = array_filter($a1);
                if (array_key_exists($key, $files)) {
                    $data[$key_index]['file'][] = $files[$key];
                    $final_content_image[$key_index][] = $content_image[$key];
                }
                if (array_key_exists($key, $request['letter_image_file']))
                    $data[$key_index]['letter_image_file'][] = $request['letter_image_file'][$key];

                $key_index ++;
            }
        }


        //dd($data);
        $dest = array();
        //$_SERVER['DOCUMENT_ROOT']
        //$destinationPath = $_SERVER['DOCUMENT_ROOT']. "/webroot/epicvelocity/letters"; // for production server
        $destinationPath = storage_path('app/public/resources/epicvelocity/letters'); // for localhost

        if (!is_dir($destinationPath)) {
            mkdir($destinationPath, 0777, true);
        }

        $folder_name = $destinationPath . '/' . $auth_user->id . "_" . time() . '-' . mt_rand(00000, 999999);

        try {
            if (!is_dir($folder_name)) {
                mkdir($folder_name, 0777, true);
            }
        } catch (Exception $e) {
            Log::error($e);

        }

        //array for bottom images.
        $img_bottom_clients = array();
        if (isset($request['identity_proof_file']) && !empty($request['identity_proof_file']))
            $img_bottom_clients[] = $request['identity_proof_file'];
        if (isset($reques['ssn_proof_file']) && !empty($reques['ssn_proof_file']))
            $img_bottom_clients[] = $reques['ssn_proof_file'];
        if (isset($request['address_proof_file']) && !empty($request['address_proof_file']))
            $img_bottom_clients[] = $request['address_proof_file'];
        if (isset($request['other_file']) && !empty($request['other_file']))
            $img_bottom_clients[] = $request['other_file'];


        $count = 1;

        $cb_item_per_letter = 1;
        $num_of_inquiry = 1;
        if (isset($request['num_of_account']) && !empty($request['num_of_account'])) {
            $cb_item_per_letter = $request['num_of_account'];
        }

        if (isset($request['num_of_inquiry']) && !empty($request['num_of_inquiry'])) {
            $num_of_inquiry = $request['num_of_inquiry'];
        }

        $dfAddressAssocPDF = []; // Data Furnisher Address & file assoc initialization
        foreach ($data as $key => $value) {
            $data[$key]['dest'] = array_unique($this->array_flatten($data[$key]['dest']));
            $temp_id = $data[$key]['template'][0];
            $temp_name = explode('_', $data[$key]['template'][0]);
            $template_type = explode('-', $temp_name[0]);
            $template_type = $template_type[0];
            if ($template_type == 'INQ') {
                $cb_item_per_letter = $num_of_inquiry;
            }

            if ($temp_name[1] == '40') {
                //continue;
            }

            $view_name = 'lg/pdf/' . $temp_name[1];


            // image_content
            $final_image_acc = [];
            if (!empty($final_content_image[$key])) {
                foreach ($final_content_image[$key] as $keyfile => $valuef) {
                    if (!empty($valuef)) {
                        $final_image_acc[] = $valuef;
                    }
                }
            }
            $content_image = $final_image_acc;

            // image_content

            $header_content = '';
            if ($temp_name[1] == 52) {
                $header_content = "<p><strong><u>Notice of Intent to Sue </u></strong></p>
                <p><u>(if you fail to act accordingly in response to this again applied </u><strong>CONSUMER DECLARATION of CHECK of CERTIFIED COMPLIANT and PHYSICALLY VERIFIABLE REPORTED INFORMATION with DEMAND to remove DEFICIENCIES! </strong></p>";
            }

            $total_destination_selected = count($data[$key]['dest']);
            $testData = [];

            foreach ($data[$key]['dest'] as $key2 => $value2) {

                $current_destination_name = $this->getDestinationByAddress($value2);

                if ($value2 == '' || $value2 == 1) {
                    continue;
                }

                if (count($data[$key]['content']) > $cb_item_per_letter) {

                    $content = array_chunk($data[$key]['content'], $cb_item_per_letter);

                    foreach ($content as $key3 => $value3) {

                        if (in_array($value2, $destinations)) {
                            if (isset($request['include_bureau_image'])) {
                                $fina_data = array('content' => $value3, 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => $img_bottom, 'img_bottom_clients' => $img_bottom_clients);
                            } else {
                                $fina_data = array('content' => $value3, 'destination' => $value2, 'universal' => $universal, 'content_image' => array(), 'img_bottom' => array(), 'img_bottom_clients' => array());
                            }
                        } else {
                            if (isset($request['include_creditor_image'])) {
                                $fina_data = array('content' => $value3, 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => $img_bottom, 'img_bottom_clients' => $img_bottom_clients);
                            } else {
                                $fina_data = array('content' => $value3, 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => array(), 'img_bottom_clients' => array());
                                //$test_content[] = ['df-content' => $fina_data['content']];
                            }
                        }

                        $html = '';

                        $content = $fina_data['content'];
                        $destination = $fina_data['destination'];
                        $avail_content = $new_dest_content_assoc[$value2] ?? "";
                        $content_image = $fina_data['content_image'];
                        $img_bottom = $fina_data['img_bottom'];
                        $img_bottom_clients = $fina_data['img_bottom_clients'];

                        $html = view($view_name,
                            compact(
                                'universal',
                                'fina_data',
                                'content',
                                'header_content',
                                'additional_destionations1',
                                'additional_destionations2',
                                'destination',
                                'avail_content',
                                'content_image',
                                'img_bottom',
                                'img_bottom_clients'
                            )
                        )->render();

                        $html = $this->removeGreenText($html);
                        //echo $html;exit;
                        $test_content[$key] = ['content' => array_keys($content), 'pdf' => $view_name];
                        $name2 = (explode(' ', $value2));
                        $client_name = str_replace(" ", "-", $request['name']);
                        if(!empty($client_name)){
                            $client_name = rtrim($client_name,",");
                        }
                        $date_time = time();
                        $file_name = $count . '_' . $client_name . '_' . $temp_name[0] . '_' . str_replace('/', '', $name2[0]) . '_' . $date_time . '.pdf'; //build name of pdf file
                        $count++;

                        $global_html[$value2] = ['html' => $html, 'destination_name' => $current_destination_name, 'file_name' => $file_name];
                        $global_destination_html[$current_destination_name] = $html;
                        $this->generateCurrentPDF($html, $folder_name . '/' . $file_name,$file_name);
                        if (!in_array($value2, $destinations)) {
                            $dfAddressAssocPDF[$folder_name . '/' . $file_name] = $value2;
                        }
                    }
                } else {

                    if (in_array($value2, $destinations)) {
                        if (isset($request['include_bureau_image'])) {
                            $fina_data = array('content' => $data[$key]['content'], 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => $img_bottom, 'img_bottom_clients' => $img_bottom_clients);
                        } else {
                            $fina_data = array('content' => $data[$key]['content'], 'destination' => $value2, 'universal' => $universal, 'content_image' => array(), 'img_bottom' => array(), 'img_bottom_clients' => array());
                        }
                    } else {
                        if (isset($request['include_creditor_image'])) {
                            $fina_data = array('content' => $data[$key]['content'], 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => $img_bottom, 'img_bottom_clients' => $img_bottom_clients);
                        } else {
                            $fina_data = array('content' => $data[$key]['content'], 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => array(), 'img_bottom_clients' => array());
                        }
                    }
                    $testData[] = $temp_name[1];
                    $html = '';
                    $content = $fina_data['content'];
                    $destination = $fina_data['destination'];
                    $avail_content = $new_dest_content_assoc[$value2] ?? "";
                    $content_image = $fina_data['content_image'];
                    $img_bottom = $fina_data['img_bottom'];
                    $img_bottom_clients = $fina_data['img_bottom_clients'];

                    $html = view($view_name,
                        compact(
                            'universal',
                            'fina_data',
                            'content',
                            'header_content',
                            'additional_destionations1',
                            'additional_destionations2',
                            'destination',
                            'avail_content',
                            'content_image',
                            'img_bottom',
                            'img_bottom_clients'
                        )
                        )->render();

                    $html = $this->removeGreenText($html);
                    //echo $html;exit;
                    $test_content[$key] = ['content' => array_keys($content), 'pdf' => $view_name];


                    $name2 = (explode(' ', $value2));

                    $client_name = str_replace(" ", "-", $request['name']);
                    if(!empty($client_name)){
                        $client_name = rtrim($client_name,",");
                    }
                    $date_time = time();
                    $file_name = $count . '_' . $client_name . '_' . $temp_name[0] . '_' . str_replace('/', '', $name2[0]) . '_' . $date_time . '.pdf'; //build name of pdf file

                    $count++;
                    $global_html[$value2] = ['html' => $html, 'destination_name' => $current_destination_name, 'file_name' => $file_name];
                    $global_destination_html[$current_destination_name] = $html;
                    $this->generateCurrentPDF($html, $folder_name . '/' . $file_name,$file_name);
                    if (!in_array($value2, $destinations)) {
                        $dfAddressAssocPDF[$folder_name . '/' . $file_name] = $value2; //['address'=>$value2,'pdf'=> $file_name];
                    }
                }

            }

        }

        $zip_file_name = $auth_user->id . "_" . time() . 'evlg-pdf.zip';
        $path = $folder_name;
        $zip_file = $destinationPath . '/' . $zip_file_name;

        $createZip = new createDirZip();
        $createZip->testZip($path, $zip_file);

        if (!file_exists($zip_file)){
            $this->Flash->error('No Letter generated.');
        }

        if (file_exists($zip_file)) {
            File::deleteDirectory($path);
            $json_content_image = "";
            $json_bottom_image = "";


            $is_df_only = 0;
            $is_bureau_only = 0;
            $is_include_creditor_image = 0;
            $is_include_bureau_image = 0;
            $is_audit_only = 0;
            if (isset($request['df_only'])) {
                $is_df_only = $request['df_only'];
            }

            if (isset($request['bureau_only'])) {
                $is_bureau_only = $request['bureau_only'];
            }

            if (isset($request['include_bureau_image'])) {
                $is_include_bureau_image = $request['include_bureau_image'];
            }

            if (isset($request['include_creditor_image'])) {
                $is_include_creditor_image = $request['include_creditor_image'];
            }

            if (isset($request['audit_only'])) {
                $is_audit_only = $request['audit_only'];
            }
            $epic_personal_info['client_name'] = $request['name'];
            $epic_personal_info['address'] = $request['address'];

            $download_type= $request['download_type'];

            if($download_type==1)
            {
                $type_name = 'Download';
                appLog($logData);
                PdfWriter::pdfDownload($zip_file);
            }
            else if ($download_type == 2) {
                $type_name = 'Email';
                $data['email'] = $auth_user->email;
                $data['email_body'] = "Please find your generated letter";
                $data['email_subject'] = "Credit zombies Letters";
                $from = null;
                //$this->sendRTGEmail($data, $zip_file);
                $fileSize =  filesize($zip_file)/1024/1024;
                if($fileSize < 25) {
                    (new Email())->send($data, $data['email_subject'], $from, $zip_file, 'email.letter', $data['email']);
                    //$this->pdfDownload($zip_file);
                    $response['message'] = "Your Letters has been sent to your email.";
                }else{
                    $response['message'] = "Email can not sent for exceed maximum attachment file size.";
                }
                echo json_encode($response);
                exit;
                // $this->pdfDownload($zip_file);
            }
            else if($download_type == 3) {
                $request['folder_name'] = $folder_name;
                $this->storePdfLetters($request['client_id'],$letterExtraEntity->letter_id,2,$zip_file,$request);

            } else {
                $conn = $this->conn;
                if (isset($request['download_category']) && $request['download_category'] > 0) {
                    $dropdown_category_id = $request['download_category'];
                    $other_data['letter_stream_html'] = $global_html;
                    $other_data['letter_stream_dest_html'] = $global_destination_html;
                    $other_data['letters_directory_info'] = $folder_name;
                    $other_data['client_id'] = $request['client_id'];
                    $other_data['client_name'] = $request['name'];
                    $other_data['DF'] = $dfAddressAssocPDF;
                    $other_data['set_automation'] = $request['set_automation'];
                    $other_data['sertg_id'] = $letterExtraEntity->letter_id;
                    $response = "Your file will send with due time.";
                    if($request['automation_type'] != 4){
                        $response = $this->sendToClient($conn, $dropdown_category_id, $zip_file, "", array(), $other_data);
                    }
                } else if (isset($request['formaction']) && $request['formaction'] == 'ajax') {
                    $response = ['status' => 1];
                }

                $this->deleteGeneratedPdfWithDir($folder_name);
                @unlink($zip_file);
                echo json_encode($response);
                exit;
            }
        } else {
            if ($this->request->is('ajax')) {
                echo json_encode('There was no file generated to send.');
                exit;
            }
            $this->Flash->error('No Letter generated.');
        }
        $logData['type'] = $type_name;
        appLog($logData);
        $this->deleteGeneratedPdfWithDir($folder_name);
        //return $this->redirect($this->referer());
    }

    public function getGeneratedPdf(Request $req) {

        $logData['action'] = 'TOTAL PDF COUNT';
        $time = config('constant.MAX_TIME_LIMIT') ?? 60;
        set_time_limit($time);

        $response['message'] = "We apologize but you have reached your capacity of letters to challenge at one time. Please Review your accounts again and re process.";
        $response['status'] = false;

        $universal = array();
        $pdf_layout_array = [
            '1' => 'lg-pdf',
            '2' => 'lg-pdf',
            '3' => 'lg-pdf',
            '4' => 'lg-pdf',
            '5' => 'lg-pdf',
            '6' => 'lg-pdf2',
            '7' => 'lg-pdf2',
            '8' => 'lg-pdf2',
            '9' => 'lg-pdf2',
            '10' => 'lg-pdf2',
            '11' => 'lg-pdf2',
            '12' => 'lg-pdf2',
            '13' => 'lg-pdf2',
            '14' => 'lg-pdf2',
            '15' => 'lg-pdf2',
            '16' => 'lg-pdf2',
            '17' => 'lg-pdf2',
            '18' => 'lg-pdf',
            '19' => 'lg-pdf2',
            '20' => 'lg-pdf2',
            '21' => 'lg-pdf2',
            '22' => 'lg-pdf2',
            '23' => 'lg-pdf2',
            '24' => 'lg-pdf2',
            '26' => 'lg-pdf2',
            '27' => 'lg-pdf2',
            '28' => 'lg-pdf2',
            '29' => 'lg-pdf2',
            '30' => 'lg-pdf2',
            '31' => 'lg-pdf2',
            '32' => 'lg-pdf2',
            '33' => 'lg-pdf2',
            '34' => 'lg-pdf2',
            '35' => 'lg-pdf2',
            '36' => 'lg-pdf2',
            '37' => 'lg-pdf2',
            '38' => 'lg-pdf2',
            '39' => 'lg-pdf2',
            '40' => 'lg-pdf2',
            '41' => 'lg-pdf2',
            '42' => 'lg-pdf2',
            '43' => 'lg-pdf2',
            '44' => 'lg-pdf2',
            '45' => 'lg-pdf2',
            '46' => 'lg-pdf2',
            '47' => 'lg-pdf2',
            '48' => 'lg-pdf2',
            '49' => 'lg-pdf2',
            '50' => 'lg-pdf2',
            '51' => 'lg-pdf2',
            '52' => 'lg-pdf2',
            '53' => 'lg-pdf2',
            '54' => 'lg-pdf2',
            '55' => 'lg-pdf2',
            '56' => 'lg-pdf2',
            '57' => 'lg-pdf2',
            '58' => 'lg-pdf2',
            '59' => 'lg-pdf2',
            '60' => 'lg-pdf2',
            '61' => 'lg-pdf2',
            '62' => 'lg-pdf2',
            '63' => 'lg-pdf2',
            '64' => 'lg-pdf2',
            '65' => 'lg-pdf2',
            '66' => 'lg-pdf2',
            '67' => 'lg-pdf2',
            '68' => 'lg-pdf2',
            '69' => 'lg-pdf2',
            '70' => 'lg-pdf2',
            '71' => 'lg-pdf2',
            '72' => 'lg-pdf2',
        ];
        $request = $req->all();

        $auth_user = auth()->user();
        $client_id = $auth_user->id;
        $request['client_email'] = "";
        $logData['email'] = $auth_user->email;

        $download_type = $request['download_type'];
        if($download_type == 1)
        {
            $logData['type'] = 'Download';
        }else if($download_type == 2){
            $logData['type'] = 'Email';
        }

        $current_html_content = $request['current_html_content'];

        if (empty($id)) {
            $id = isset($request['letter_id']) ? $request['letter_id'] : null;
        }


        $fileTypeString = "";
        if (!empty($selectedLetterTypes)) {
            foreach ($selectedLetterTypes as $type) {
                if (!empty($fileTypeString) && $fileTypeString != "_") {
                    $fileTypeString .= "_" . $lettesTypes->{$type};
                } else {
                    $fileTypeString = $lettesTypes->{$type};
                }
            }
        }
        $universal['today'] = $request['today'];
        $universal['cr_resource'] = $request['cr_resource'];
        $universal['name'] = $request['name'];
        $universal['address'] = $request['address'];
        $universal['dob'] = trim($request['dob']);
        $ssn = $auth_user->ssn;
        $universal['ssn'] = substr($ssn, -4); // get only last 4 digits of ssn.
        $universal['p_tracking_number'] = $request['p_tracking_number'];

        $destinations = array();
        $additional_destionations1 = [];
        $additional_destionations2 = [];
        $EXP_1 = "EXPERIAN PO BOX 9701, ALLEN, TX 75013";
        $EXP_2 = "EXPERIAN PO BOX 4500, ALLEN, TX 75013";
        $EQF_1 = "EQUIFAX PO Box740256, ATLANTA,GA 30374-0256";
        $EQF_2 = "EQUIFAX PO Box740241, ATLANTA,GA 30374-0241";
        $TRANS_1 = "Trans Union PO Box 2000, CHESTER, PA 19016-2000";;
        $TRANS_2 = "Trans Union PO Box 1000, CHESTER, PA 19022-1000";
        $TRANS_3 = "Trans Union PO Box 2000, CHESTER, PA 19022-2000";

        $destinations[] = $EXP_1;
        $destinations[] = $EXP_2;
        $destinations[] = $EQF_1;
        $destinations[] = $EQF_2;
        $destinations[] = $TRANS_1;
        $destinations[] = $TRANS_2;
        $destinations[] = $TRANS_3;

        $additional_destionations1[$EXP_1] = "Attn Darryl Gibson,<br/>Esq. (or acting/current Group General Counsel),<br/>Experian Information Solutions, Inc.,<br/>475 Anton Blvd.,<br/> Costa Mesa, CA 92626";
        $additional_destionations1[$EXP_2] = "Attn Darryl Gibson,<br/>Esq. (or acting/current Group General Counsel),<br/>Experian Information Solutions, Inc.,<br/>475 Anton Blvd.,<br/> Costa Mesa, CA 92626";

        $additional_destionations2[$EXP_1] = "Experian POB 9701, ATTN Consumer Fraud Department, Allen, TX 75013";
        $additional_destionations2[$EXP_2] = "Experian POB 9701, ATTN Consumer Fraud Department, Allen, TX 75013";

        $additional_destionations1[$EQF_1] = "ATTN John J. Kelley, III,<br/>Esq. (or acting/current CHIEF LEGAL OFFICER),<br/>Equifax Information services LLC.<br/>1550 Peachtree Street, N.W.,<br/>ATLANTA, GA 30309";
        $additional_destionations1[$EQF_2] = "ATTN John J. Kelley, III,<br/>Esq. (or acting/current CHIEF LEGAL OFFICER),<br/>Equifax Information services LLC.<br/>1550 Peachtree Street, N.W.,<br/>ATLANTA, GA 30309";

        $additional_destionations2[$EQF_1] = "EQUIFAX , ATTN FRAUD DEPARTMENT,POB 740256,  ATLANTA, GA 30374-0256";
        $additional_destionations2[$EQF_2] = "EQUIFAX , ATTN FRAUD DEPARTMENT,POB 740256,  ATLANTA, GA 30374-0256";

        $additional_destionations1[$TRANS_1] = "Attn: john Blenke ,<br/>Esq. (acting or current EVP and GENERAL COUNSEL),<br/>Transunion LLC,<br/>555 W. Adams Street,<br/>CHICAGO, IL";
        $additional_destionations1[$TRANS_2] = "Attn: john Blenke ,<br/>Esq. (acting or current EVP and GENERAL COUNSEL),<br/>Transunion LLC,<br/>555 W. Adams Street,<br/>CHICAGO, IL";
        $additional_destionations1[$TRANS_3] = "Attn: john Blenke ,<br/>Esq. (acting or current EVP and GENERAL COUNSEL),<br/>Transunion LLC,<br/>555 W. Adams Street,<br/>CHICAGO, IL";

        $additional_destionations2[$TRANS_1] = "Trans Union, Attn FRAUD DEPARTMENT, POB 2000, Chester , PA 19016-2000";
        $additional_destionations2[$TRANS_2] = "Trans Union, Attn FRAUD DEPARTMENT, POB 2000, Chester , PA 19016-2000";
        $additional_destionations2[$TRANS_3] = "Trans Union, Attn FRAUD DEPARTMENT, POB 2000, Chester , PA 19016-2000";

        /*$destinations[] = "EXPERIAN PO BOX 9701, ALLEN, TX 75013";
        $destinations[] = "EXPERIAN PO BOX 4500, ALLEN, TX 75013";
        $destinations[] = "EQUIFAX PO Box740256, ATLANTA,GA 30374-0256";
        $destinations[] = "EQUIFAX PO Box740241, ATLANTA,GA 30374-0241";
        $destinations[] = "Trans Union PO Box 2000, CHESTER, PA 19016-2000";
        $destinations[] = "Trans Union PO Box 1000, CHESTER, PA 19022-1000";
        $destinations[] = "Trans Union PO Box 2000, CHESTER, PA 19022-2000";*/
        $destinations[] = "INNOVIS PO Box 1640, Pittsburgh, PA 15230-1640";
        $destinations[] = "Innovis Consumer Assistance PO Box 530088, Atlanta, GA 30353-0088";
        $destinations[] = "LexisNexis PO Box 105108, Atlanta, GA 30348";
        $destinations[] = "SageStream, LLC, LexisNexis Risk Solutions Consumer Center P. O. Box 105108. Atlanta, Georgia 30348-5108";
        $destinations[] = "Chex Systems ATTN: Consumer Relations, 7805 Hudson Rd., Ste. 100, Woodbury, MN 55125";
        $destinations[] = "(US RESIDENTS) MIB Inc 50 Braintree Hill Park, Suite 400, Braintree, MA 02184-8734";
        $destinations[] = "(CANADIAN RESIDENTS) MIB Inc 330 university Avenue, Suite 501, Toronto, Canada M5G 1R7";
        $destinations[] = "FactorTrust PO Box 3653,Alpharhetta, GA 30023";

        $info_item = $request['info_item'];

        $data = array(); //main data array
        $files = array();
        $excludes = array();
        if (isset($request['info_item']['file']))
            $files = $request['info_item']['file'];
        if (isset($request['info_item']['exclude']))
            $excludes = $request['info_item']['exclude'];
        $univ_dest = $request['destination'];


        $content_image = array();
        $img_bottom = array();
        $excluded_array_keys = [];
        $letterImagesDirectory = "/epicvelocity/letters/account";
        $letterAttachmentDirectory = "/epicvelocity/letters/attachment";
        $letterImagesDirectory = storage_path($letterImagesDirectory);
        $letterAttachmentDirectory = storage_path($letterAttachmentDirectory);
        if ($request['action'] == 'new') {
            // for new upload file in account part
            if (!empty($request['letter_image_file'])) {
                $target_file = $letterImagesDirectory . '/' . $auth_user->id;
                if (!is_dir($target_file)) {
                    mkdir($target_file, 0777, true);
                }
                $image_count = 0;
                foreach ($request['letter_image_file'] as $keyf => $image) {
                    if (!in_array($keyf, $excluded_array_keys)) {
                        if (!empty($image)) {
                            $image_count++;
                            $temp = $auth_user->id . "_" . $image_count . time() . ".jpg";
                            $dataImg = str_replace('data:image/jpeg;base64,', '', $image);
                            $dataImg = base64_decode($dataImg);
                            $targeted_file = $target_file . "/" . $temp;
                            file_put_contents($targeted_file, $dataImg);
                            $this->filePermissionSet($targeted_file);
                            $content_image[$keyf] = $auth_user->id . "/" . $temp;
                        }
                    }
                }
            }

            //dd($request['attach_image_file']);
            // for existing file in attachment part
            if (!empty($request['attach_image_file'])) {
                $target_file_attachment = ltrim($letterAttachmentDirectory,"/") . '/' . $auth_user->id;
                if (!is_dir($target_file_attachment)) {
                    // mkdir($target_file_attachment, 0777, true);
                }

                $attach_count = 0;
                //dd($request['attach_image_file'],count($request['attach_image_file']));
                foreach ($request['attach_image_file'] as $keyf_attach => $attach) {

                    $isUploadMedia = $request['isUploadMedia'][$keyf_attach];
                    if (!in_array($keyf_attach, $excluded_array_keys)) {
                        if (!empty($attach)) {
                            $attach_count++;
                            $temp = $auth_user->id . "_" . $attach_count . time() . ".jpg";
                            $targeted_attach_file = $target_file_attachment . "/" . $temp;
                            //dd(getPublicFile($attach),$attach);
                            if ($isUploadMedia == 1) {
                                // copy(ltrim($attach,"/"), $targeted_attach_file);
                                //$img_bottom[$keyf_attach] = $attach;
                                $img_bottom[$keyf_attach] = '<img style="width: 100%;margin-top: 20px" src="'.getPublicFile($attach).'" >';
                                //$img_bottom[$keyf_attach] = "";
                            } else {
                                /*dd($attach);
                                $dataImg = str_replace('data:image/jpeg;base64,', '', $attach);
                                $dataImg = base64_decode($dataImg);
                                file_put_contents($targeted_attach_file, $dataImg);
                                $this->filePermissionSet($targeted_attach_file);*/
                                $img_bottom[$keyf_attach] = '<img src="'.$attach.'" style="width:100%;margin-top: 20px" />';
                            }
                            //$img_bottom[$keyf_attach] = $this->Auth->user('id') . "/" . $temp;
                            //$img_bottom[$keyf_attach] = $this->Auth->user('id') . "/" . $temp;
                        }
                    }
                }
            }


        }
        else if ($request['action'] == 'edit' || $request['action'] == 'create_new') {

            // for account part
            if (!empty($request['isImageChange'])) {
                $target_file = $letterImagesDirectory . '/' . $this->Auth->user('id');
                if (!is_dir($target_file)) {
                    mkdir($target_file, 0777, true);
                }
                $image_count = 0;
                foreach ($request['isImageChange'] as $imageFileKey => $value) {
                    $image = $request['letter_image_file'][$imageFileKey];
                    $oldImage = $request['oldImage'][$imageFileKey];
                    if (!in_array($imageFileKey, $excluded_array_keys)) {
                        if ($value == 2) { // 2 for new upload Image
                            if (!empty($image)) {
                                unlink($letterImagesDirectory . '/' . $oldImage);
                                $image_count++;
                                $temp = $this->Auth->user('id') . "_" . $image_count . time() . ".jpg";
                                $dataImg = str_replace('data:image/jpeg;base64,', '', $image);
                                $dataImg = base64_decode($dataImg);
                                $targeted_file = $target_file . "/" . $temp;
                                file_put_contents($targeted_file, $dataImg);
                                $this->filePermissionSet($targeted_file);
                                $content_image[$imageFileKey] = $this->Auth->user('id') . "/" . $temp;
                            }
                        } else if ($value == 1) { // 1 for remove image
                            unlink($letterImagesDirectory . '/' . $oldImage);
                        } else if ($value == 0) {
                            $content_image[$imageFileKey] = $image;
                        }
                    }
                }
            }

            // for attachment part

            if (!empty($request['isAttImageChange'])) {
                $target_file = $letterAttachmentDirectory . '/' . $this->Auth->user('id');
                if (!is_dir($target_file)) {
                    mkdir($target_file, 0777, true);
                }
                $image_att_count = 0;
                foreach ($request['isAttImageChange'] as $imageAttFileKey => $value_attach) {
                    $image_att = $request['attach_image_file'][$imageAttFileKey];
                    $oldImage_att = $request['oldAttImage'][$imageAttFileKey];
                    if (!in_array($imageAttFileKey, $excluded_array_keys)) {
                        if ($value_attach == 2) { // 2 for new upload Image
                            if (!empty($image_att)) {
                                unlink($letterAttachmentDirectory . '/' . $oldImage_att);
                                $image_att_count++;
                                $temp = $this->Auth->user('id') . "_" . $image_att_count . time() . ".jpg";
                                $dataImg = str_replace('data:image/jpeg;base64,', '', $image_att);
                                $dataImg = base64_decode($dataImg);
                                $targeted_file = $target_file . "/" . $temp;
                                file_put_contents($targeted_file, $dataImg);
                                $this->filePermissionSet($targeted_file);
                                $img_bottom[$imageAttFileKey] = $this->Auth->user('id') . "/" . $temp;
                            }
                        } else if ($value_attach == 1) { // 1 for remove image
                            unlink($letterAttachmentDirectory . '/' . $oldImage_att);
                        } else if ($value_attach == 0) {
                            $img_bottom[$imageAttFileKey] = $oldImage_att;
                        }
                    }
                }
            }
        }

        $db_content_image = $content_image;
        //dd($db_content_image);
        if (!isset($request['info_item'])) {
            //flash('No Content Box added');
            //return $this->redirect($this->referer());
            return  back()->with('error','No Content Box added');
        }
        $info_item['dest'] = array_values($info_item['dest']);
        $final_content_image = [];
        $new_dest_content_assoc = [];
        if (!empty($info_item['dest'])) {
            foreach ($info_item['dest'] as $dest_key => $dest) {
                if (!empty($dest)) {
                    foreach ($dest as $current_dest) {
                        if (!empty($current_dest) && $current_dest != 1) {
                            $new_dest_content_assoc[$current_dest][] = $info_item['content'][$dest_key];
                        }
                    }
                }
            }
        }

        if (!isset($request['bureau_only']) && !isset($request['df_only'])){
            $request['bureau_only'] = 1;
            $request['df_only'] = 1;
        }

        if (isset($request['bureau_only'])) {
            foreach ($info_item['template'] as $key => $value) {

                if (array_key_exists($key, $excludes))
                    continue;
                $data[$value]['type'] = 'bureau';
                $data[$value]['template'][] = $value;
                $data[$value]['wave'][] = $info_item['wave'][$key];
                $data[$value]['letter_type'][] = $info_item['letter_type'][$key];

                if(isset($info_item['content'][$key])) {
                    $data[$value]['content'][] = $info_item['content'][$key];
                }

                $a1 = array();

                if (isset($info_item['dest'][$key])) {
                    foreach ($info_item['dest'][$key] as $key2 => $value2) {
                        if (in_array($value2, $destinations)) {
                            $a1[] = $value2;
                        }
                    }
                }
                if (isset($univ_dest)) {
                    $a1 = array_merge($a1, $univ_dest);
                }
                $data[$value]['dest'][] = array_filter(array_unique($a1));

                if (array_key_exists($key, $files)) {
                    $data[$value]['file'][] = $files[$key];
                    $final_content_image[$value][] = $content_image[$key];
                }
                if (array_key_exists($key, $request['letter_image_file']))
                    $data[$value]['letter_image_file'][] = $request['letter_image_file'][$key];
            }
        }


        $key_index = 400;

        if (isset($request['df_only'])) {

            foreach ($info_item['template_df'] as $key => $value) {

                if (empty(trim($value)))
                    continue;
                if (array_key_exists($key, $excludes)) {
                    continue;
                }



                $template_id = explode('_', $value);
                $template_id = $template_id[1];

                $data[$key_index]['type'] = 'creditor';
                $data[$key_index]['template'][] = $value;
                $data[$key_index]['wave'][] = $info_item['wave'][$key];
                $data[$key_index]['letter_type'][] = $info_item['letter_type'][$key];
                $data[$key_index]['content'][] = $info_item['content'][$key];

                $a1 = array();

                if (isset($info_item['dest'][$key])) {
                    foreach ($info_item['dest'][$key] as $key2 => $value2) {
                        if (empty(trim($value)))
                            continue;
                        if (!in_array($value2, $destinations)) {
                            $a1[] = $value2;
                        }
                    }
                }
                $data[$key_index]['dest'][] = array_filter($a1);
                if (array_key_exists($key, $files)) {
                    $data[$key_index]['file'][] = $files[$key];
                    $final_content_image[$key_index][] = $content_image[$key];
                }
                if (array_key_exists($key, $request['letter_image_file']))
                    $data[$key_index]['letter_image_file'][] = $request['letter_image_file'][$key];

                $key_index ++;
            }
        }


        //dd($data);
        $dest = array();
        //$_SERVER['DOCUMENT_ROOT']
        //$destinationPath = $_SERVER['DOCUMENT_ROOT']. "/webroot/epicvelocity/letters"; // for production server
        $destinationPath = storage_path('app/public/resources/epicvelocity/letters'); // for localhost

//        if (!is_dir($destinationPath)) {
//            mkdir($destinationPath, 0777, true);
//        }
//
//        $folder_name = $destinationPath . '/' . $auth_user->id . "_" . time() . '-' . mt_rand(00000, 999999);
//
//        try {
//            if (!is_dir($folder_name)) {
//                mkdir($folder_name, 0777, true);
//            }
//        } catch (Exception $e) {
//            Log::error($e);
//
//        }

        //array for bottom images.
        $img_bottom_clients = array();
        if (isset($request['identity_proof_file']) && !empty($request['identity_proof_file']))
            $img_bottom_clients[] = $request['identity_proof_file'];
        if (isset($reques['ssn_proof_file']) && !empty($reques['ssn_proof_file']))
            $img_bottom_clients[] = $reques['ssn_proof_file'];
        if (isset($request['address_proof_file']) && !empty($request['address_proof_file']))
            $img_bottom_clients[] = $request['address_proof_file'];
        if (isset($request['other_file']) && !empty($request['other_file']))
            $img_bottom_clients[] = $request['other_file'];


        $count = 1;

        $cb_item_per_letter = 1;
        $num_of_inquiry = 1;
        $pdfCount = 0;
        if (isset($request['num_of_account']) && !empty($request['num_of_account'])) {
            $cb_item_per_letter = $request['num_of_account'];
        }

        if (isset($request['num_of_inquiry']) && !empty($request['num_of_inquiry'])) {
            $num_of_inquiry = $request['num_of_inquiry'];
        }

        $dfAddressAssocPDF = []; // Data Furnisher Address & file assoc initialization
        foreach ($data as $key => $value) {
            $data[$key]['dest'] = array_unique($this->array_flatten($data[$key]['dest']));
            $temp_id = $data[$key]['template'][0];
            $temp_name = explode('_', $data[$key]['template'][0]);
            $template_type = explode('-', $temp_name[0]);
            $template_type = $template_type[0];
            if ($template_type == 'INQ') {
                $cb_item_per_letter = $num_of_inquiry;
            }

            if ($temp_name[1] == '40') {
                //continue;
            }

            $view_name = 'lg/pdf/' . $temp_name[1];


            // image_content
            $final_image_acc = [];
            if (!empty($final_content_image[$key])) {
                foreach ($final_content_image[$key] as $keyfile => $valuef) {
                    if (!empty($valuef)) {
                        $final_image_acc[] = $valuef;
                    }
                }
            }
            $content_image = $final_image_acc;

            // image_content

            $header_content = '';
            if ($temp_name[1] == 52) {
                $header_content = "<p><strong><u>Notice of Intent to Sue </u></strong></p>
                <p><u>(if you fail to act accordingly in response to this again applied </u><strong>CONSUMER DECLARATION of CHECK of CERTIFIED COMPLIANT and PHYSICALLY VERIFIABLE REPORTED INFORMATION with DEMAND to remove DEFICIENCIES! </strong></p>";
            }

            $total_destination_selected = count($data[$key]['dest']);
            $testData = [];

            foreach ($data[$key]['dest'] as $key2 => $value2) {

                $current_destination_name = $this->getDestinationByAddress($value2);

                if ($value2 == '' || $value2 == 1) {
                    continue;
                }

                if (count($data[$key]['content']) > $cb_item_per_letter) {

                    $content = array_chunk($data[$key]['content'], $cb_item_per_letter);

                    foreach ($content as $key3 => $value3) {

                        if (in_array($value2, $destinations)) {
                            if (isset($request['include_bureau_image'])) {
                                $fina_data = array('content' => $value3, 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => $img_bottom, 'img_bottom_clients' => $img_bottom_clients);
                            } else {
                                $fina_data = array('content' => $value3, 'destination' => $value2, 'universal' => $universal, 'content_image' => array(), 'img_bottom' => array(), 'img_bottom_clients' => array());
                            }
                        } else {
                            if (isset($request['include_creditor_image'])) {
                                $fina_data = array('content' => $value3, 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => $img_bottom, 'img_bottom_clients' => $img_bottom_clients);
                            } else {
                                $fina_data = array('content' => $value3, 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => array(), 'img_bottom_clients' => array());
                                //$test_content[] = ['df-content' => $fina_data['content']];
                            }
                        }

                        $html = '';

                        $content = $fina_data['content'];
                        $destination = $fina_data['destination'];
                        $avail_content = $new_dest_content_assoc[$value2] ?? "";
                        $content_image = $fina_data['content_image'];
                        $img_bottom = $fina_data['img_bottom'];
                        $img_bottom_clients = $fina_data['img_bottom_clients'];

                        $html = view($view_name,
                            compact(
                                'universal',
                                'fina_data',
                                'content',
                                'header_content',
                                'additional_destionations1',
                                'additional_destionations2',
                                'destination',
                                'avail_content',
                                'content_image',
                                'img_bottom',
                                'img_bottom_clients'
                            )
                        )->render();

                        $html = $this->removeGreenText($html);
                        //echo $html;exit;
                        $test_content[$key] = ['content' => array_keys($content), 'pdf' => $view_name];
                        $name2 = (explode(' ', $value2));
                        $client_name = str_replace(" ", "-", $request['name']);
                        if(!empty($client_name)){
                            $client_name = rtrim($client_name,",");
                        }
                        $date_time = time();
                        $file_name = $count . '_' . $client_name . '_' . $temp_name[0] . '_' . str_replace('/', '', $name2[0]) . '_' . $date_time . '.pdf'; //build name of pdf file
                        $count++;

                        $global_html[$value2] = ['html' => $html, 'destination_name' => $current_destination_name, 'file_name' => $file_name];
                        $global_destination_html[$current_destination_name] = $html;
//                        $this->generateCurrentPDF($html, $folder_name . '/' . $file_name,$file_name);
                        $pdfCount++;
//                        if (!in_array($value2, $destinations)) {
//                            $dfAddressAssocPDF[$folder_name . '/' . $file_name] = $value2;
//                        }
                    }
                } else {

                    if (in_array($value2, $destinations)) {
                        if (isset($request['include_bureau_image'])) {
                            $fina_data = array('content' => $data[$key]['content'], 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => $img_bottom, 'img_bottom_clients' => $img_bottom_clients);
                        } else {
                            $fina_data = array('content' => $data[$key]['content'], 'destination' => $value2, 'universal' => $universal, 'content_image' => array(), 'img_bottom' => array(), 'img_bottom_clients' => array());
                        }
                    } else {
                        if (isset($request['include_creditor_image'])) {
                            $fina_data = array('content' => $data[$key]['content'], 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => $img_bottom, 'img_bottom_clients' => $img_bottom_clients);
                        } else {
                            $fina_data = array('content' => $data[$key]['content'], 'destination' => $value2, 'universal' => $universal, 'content_image' => $content_image, 'img_bottom' => array(), 'img_bottom_clients' => array());
                        }
                    }
                    $testData[] = $temp_name[1];
                    $html = '';
                    $content = $fina_data['content'];
                    $destination = $fina_data['destination'];
                    $avail_content = $new_dest_content_assoc[$value2] ?? "";
                    $content_image = $fina_data['content_image'];
                    $img_bottom = $fina_data['img_bottom'];
                    $img_bottom_clients = $fina_data['img_bottom_clients'];

                    $html = view($view_name,
                        compact(
                            'universal',
                            'fina_data',
                            'content',
                            'header_content',
                            'additional_destionations1',
                            'additional_destionations2',
                            'destination',
                            'avail_content',
                            'content_image',
                            'img_bottom',
                            'img_bottom_clients'
                        )
                    )->render();

                    $html = $this->removeGreenText($html);
                    //echo $html;exit;
                    $test_content[$key] = ['content' => array_keys($content), 'pdf' => $view_name];


                    $name2 = (explode(' ', $value2));

                    $client_name = str_replace(" ", "-", $request['name']);
                    if(!empty($client_name)){
                        $client_name = rtrim($client_name,",");
                    }
                    $date_time = time();
                    $file_name = $count . '_' . $client_name . '_' . $temp_name[0] . '_' . str_replace('/', '', $name2[0]) . '_' . $date_time . '.pdf'; //build name of pdf file

                    $count++;
                    $global_html[$value2] = ['html' => $html, 'destination_name' => $current_destination_name, 'file_name' => $file_name];
                    $global_destination_html[$current_destination_name] = $html;
//                    $this->generateCurrentPDF($html, $folder_name . '/' . $file_name,$file_name);
//                    if (!in_array($value2, $destinations)) {
//                        $dfAddressAssocPDF[$folder_name . '/' . $file_name] = $value2; //['address'=>$value2,'pdf'=> $file_name];
//                    }
                    $pdfCount++;
                }

            }

        }

        if($pdfCount <= config('constant.MAX_PDF_COUNT') )
        {
            $response['isGreaterThanFifty'] = false;
            $message = '';
            if($pdfCount > config('constant.MIN_PDF_COUNT_VALUE'))
            {
                $response['isGreaterThanFifty'] = true;
                $message = "Oops! Looks like you're trying to process more than 50 letters, Are you sure you need to challenge this many Items? Please Double Check The how-to video To Make Sure You Want To Move Forward To Challenge All Items Listed. If You Want to Continue To Process All The Letters Then Continue";
            }
            $response['message'] = $message;
            $response['status'] = true;
        }
        $logData['pdf_file_count'] = $pdfCount;
        $logData['response'] = $response;
        appLog($logData);
        echo json_encode($response);
        exit;

    }

    private function deleteGeneratedPdfWithDir($folder_name) {
        // delete generated pdf with directory

        try {
            if (substr($folder_name, strlen($folder_name) - 1, 1) != '/') {
                $folder_name .= '/';
            }

            $files = glob($folder_name . '*', GLOB_MARK);
            foreach ($files as $file) {
                @unlink($file);
            }
            rmdir($folder_name);
        } catch (\Exception $e) {

        }
    }

    private function array_flatten($array) {
        if (!is_array($array)) {
            return FALSE;
        }
        $result = array();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $result = array_merge($result, $this->array_flatten($value));
            } else {
                $result[$key] = $value;
            }
        }
        return $result;
    }

    private function uploadMediaHTML($uploadmedias) {
        $count = 0;
        $html = "";
        if (!empty($uploadmedias)) {
            foreach ($uploadmedias as $uploadmedia) {
                $file = config('constant.UPLOAD_MEDIA_PATH') . DIRECTORY_SEPARATOR.$uploadmedia->user_id . DIRECTORY_SEPARATOR . $uploadmedia->image_path;
                $count++;
                $html .= '<div class="col-md-12 img-content" id="img-content-' . $count . '">
                                     <div class="col-md-12" style="padding-top:10px;padding-bottom:10px">
                                         <div class="row">
                                             <div class="col-md-12 text-center">
                                                 <img id="att_image_' . $count . '" class="letter-attach-img" src="' . getPublicFile($file) . '" alt="">
                                                 <input type="hidden" id="attach_image_file_' . $count . '" name="attach_image_file[]" value="'.$file. '"/>
                                                 <input type="hidden" id="isUploadMedia_' . $count . '" name="isUploadMedia[]" value="1"/>
                                             </div>
                                         </div>
                                     </div>
                                     <div class="col-md-offset-3 col-md-6">
                                        <input onchange="uploadphotos(this,false)" type="file" name="img_bottom[]" id="attachment_img_' . $count . '" class="form-control no-bdr">
                                    </div>
                                     <div class="col-md-1" style="margin-top: 5px;margin-right: 20px">
                                         <label id="label1">
                                             <a style="cursor:hand;cursor:pointer;padding: 1px 6px;" onclick="clearAttImage(' . $count . ')" data-id="4">Clear</a>
                                         </label>
                                     </div>
                                    <div class="col-md-1" style="margin-top: 5px;margin-right: 20px">
                                        <label id="label1"><a onclick="addImage()" id="add-image-btn" style="padding: 1px 6px;" class="btn btn-success"><i class="fa fa-plus"></i></a></label>
                                      <label id="label1"><a onclick="removeImage(' . $count . ')" id="remove" style="padding: 1px 6px;" class="btn btn-danger"><i class="fa fa-minus"></i></a></label>
                                    </div>
                                    <script type="text/javascript">
                                        image_count = ' . $count . ';
                                    </script>
                                 </div>';
            }
        }


        return $html;
    }

    private function getClientInfo($inputData)
    {
        $data = array();
        $uploadmedia_html = "";
        $creditReportObj = app(\App\Models\Creditreport::class);
        $today = date('Y-m-d');
        $html = "";
        $clientInfo = $inputData['auth_user'];
        $clientInfo->dob = $clientInfo->birth_date;

        $credit_report_data = $creditReportObj->getCreditReportInfoByUserId($clientInfo->id);

        $uploadmedia = null;
        if (!empty($clientInfo)) {
            $source_type = $clientInfo->credit_report_company_type;
            $clientInfo->firstname = $clientInfo->first_name . " " . $clientInfo->last_name;
            if (!empty($clientInfo->street_name)) {
                $clientInfo->street_name = " " . $clientInfo->street_name;
            } else {
                $clientInfo->street_name = "";
            }

            if (!empty($clientInfo->city)) {
                $clientInfo->city = ", " . $clientInfo->city;
            } else {
                $clientInfo->city = "";
            }

            if (!empty($clientInfo->state)) {
                $clientInfo->state = ", " . $clientInfo->state;
            } else {
                $clientInfo->state = "";
            }

            if (!empty($clientInfo->zip_code)) {
                $clientInfo->zip_code = " " . $clientInfo->zip_code;
            } else {
                $clientInfo->zip_code = "";
            }

            $clientInfo->json_address = $clientInfo->street_no . $clientInfo->street_name . $clientInfo->city .$clientInfo->state .$clientInfo->zip_code;

            $clientInfo->today = $today;
            $clientInfo->created_on = date('d/m/Y', strtotime($clientInfo->created_on));
            //$clientInfo->cr_data = "Identity IQ " . $clientInfo->created_on;
            $report_type_name = "Identity IQ";
            if ($source_type == 3) {
                $report_type_name = "Smart Credit";
            }
            $clientInfo->cr_data = $report_type_name . " " . date("m/d/Y");
            $uploadmedia = app(\App\Models\Uploadmedia::class)->getUploadMediaByUserId($clientInfo->id);
        }

        $data['report'] = CreditReportService::getCreditReportContent($credit_report_data->user_id,$credit_report_data->file_name);
        $data['uploadmedia'] = $this->uploadMediaHTML($uploadmedia);
        $data['client'] = $clientInfo;

        return $data;
    }

    public function getLetter(Request $request){
        $creditreport= auth()->user();
        $auth_user_id = $creditreport->id;
        $credit_report_eligibility=[
            'is_show_alert'=>false,
            'message'=>'',
            'is_show_refresh_date'=>false
        ];
        if($request->ajax()){
            $inputData = $request->all();
            $response = [];
            if($inputData['action'] == "GET_CLIENT_INFO"){
                $inputData['auth_user'] = $creditreport;
                $response = $this->getClientInfo($inputData);
            }
            //return response()->json($response,200);
            echo json_encode($response);
            die();
        }
        $p_tracking_number = $this->getNumber();
//        $waves=$this->generateWaves($creditreport);

        if(getSession('is_first_login') == 1){
            unSetSession('is_first_login');
            $credit_report_eligibility['is_show_alert']=true;
            $credit_report_eligibility['message']='Great Job! import your credit report next.';
            setSession('video_first_time',true);
            $credit_report_eligibility['is_show_refresh_date'] = true;
        }
        else{
            if($creditreport->is_import == config('constant.IMPORT_REPORT_STATUS.ELIGIBLE'))
            {
                unSetSession('eligible_for_import');
                $credit_report_eligibility['is_show_alert']=true;
                $credit_report_eligibility['message']='Congratulations! Your next Credit Report is Ready To Import.';
            }

        }

        return view('epicvelocity.getletter',compact('p_tracking_number','creditreport','credit_report_eligibility'));
    }

    private function getNumber(){

        $number1 = mt_rand(1000, 9999);
        $number2 = mt_rand(1000, 9999);
        $number3 = mt_rand(1000, 9999);
        $number4 = mt_rand(1000, 9999);
        $number5 = mt_rand(1000, 9999);

        return $number1.' '.$number2.' '.$number3.' '.$number4.' '.$number5;
    }

    private function getDestinationByAddress($address) {
        $result = [
            'EXPERIAN PO BOX 9701, ALLEN, TX 75013' => 'EXPERIAN DESTINATIONS',
            'EXPERIAN PO BOX 4500, ALLEN, TX 75013' => 'EXPERIAN DESTINATIONS',
            'EQUIFAX PO Box740256, ATLANTA,GA 30374-0256' => 'EQUIFAX DESTINATIONS',
            'EQUIFAX PO Box740241, ATLANTA,GA 30374-0241' => 'EQUIFAX DESTINATIONS',
            'Trans Union PO Box 2000, CHESTER, PA 19016-2000' => 'TRANS UNION DESTINATIONS',
            'Trans Union PO Box 1000, CHESTER, PA 19022-1000' => 'TRANS UNION DESTINATIONS',
            'Trans Union PO Box 2000, CHESTER, PA 19022-2000' => 'TRANS UNION DESTINATIONS',
            'INNOVIS PO Box 1640, Pittsburgh, PA 15230-1640' => 'INNOVIS DESTINATIONS',
            'Innovis Consumer Assistance PO Box 530088, Atlanta, GA 30353-0088' => 'INNOVIS DESTINATIONS',
            'LexisNexis PO Box 105108, Atlanta, GA 30348' => 'LEXISNEXIS DESTINATIONS',
            'SageStream, LLC, LexisNexis Risk Solutions Consumer Center P. O. Box 105108. Atlanta, Georgia 30348-5108' => 'SAGESTREAM LLC DESTINATIONS',
            'Chex Systems ATTN: Consumer Relations, 7805 Hudson Rd., Ste. 100, Woodbury, MN 55125' => 'CHEX SYSTEMS DESTINATIONS',
            '(US RESIDENTS) MIB Inc 50 Braintree Hill Park, Suite 400, Braintree, MA 02184-8734' => 'MIB INC DESTINATIONS',
            '(CANADIAN RESIDENTS) MIB Inc 330 university Avenue, Suite 501, Toronto, Canada M5G 1R7' => 'MIB INC DESTINATIONS',
            'FactorTrust PO Box 3653,Alpharhetta, GA 30023' => 'FACTOR TRUST DESTINATIONS',
        ];

        return $result[$address] ?? "";
    }

    private function removeGreenText($html) {
        $html = preg_replace('#<span class="span-cl-green">KEEP OPEN</span>#', '', $html);
        $html = preg_replace('#<span class="span-cl-green">STAY CURRENT</span>#', '', $html);
        $html = preg_replace('#<span class="span-cl-green" title="KEEP AT NO GREATER THAN 30% of reported credit limit but BEST IF AT OR BELOW 10% of the reported credit limit!">KEEP AT 10%</span>#', '', $html);
        $html = preg_replace('#<span class="span-cl-green" title="NEVER GO OVER 50% at any time">NEVER GO OVER 50%</span>#', '', $html);
        $html = preg_replace('#<span class="span-cl-green" title="OBVIOUSLY PAY BILLS IN FULL ON TIME ALWAYS, DO NOT MISS , OR BE LATE OR HAVE INCOMPLETE PAYMENT IN ACCOUNT HISTORY">' . "DON'T BE LATE</span>#", '', $html);
        $html = preg_replace('#<p class="span-cl-green">OBVIOUSLY PAY BILLS IN FULL ON TIME ALWAYS, DO NOT MISS , OR BE LATE OR HAVE INCOMPLETE PAYMENT IN ACCOUNT HISTORY</p>#', '', $html);
        return $html;
    }

    private function generateCurrentPDF($html, $file_path) {
//        echo $html;exit;
        if($this->pdfObj instanceof PdfWriter){
            $pdfWriter = $this->pdfObj;
        }else{
            $pdfWriter = new PdfWriter();
        }
       //echo $html;exit;
        $pdfWriter->write($html, $file_path);
       // $pdfWriter->mpdfWrite($html, $file_path,basename($file_path));
//        $pdfWriter->snappyImage($html, $file_path);
    }

    private function generateWaves($user)
    {
        $userWave=$user['wave'];
        $waves=[];
        for($i=1;$i<=$userWave;$i++)
        {
            $waves[$i]='Wave '.$i;
        }
        return $waves;
    }

    private function filePermissionSet($file_path, $code = 0664) {
//        chmod($file_path, $code);
    }


}
