<?php

namespace App\Http\Controllers;


use App\Models\Client;
use App\Models\ClientAlternativePerson;
use App\Models\ClientKYCDoc;
use App\Models\CompanyBranch;
use App\Models\HistoryClient;
use App\Models\User;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;


class ClientController extends Controller
{
    /**Client Particulars**/
    public function clientParticulars($id){
        $client = [];
        if(Client::firstWhere('c_id', $id)){
            $client = Client::where('c_id', $id)->first();
        }
        return $client;
    }


    /**
     * Display a listing of the resource.
     *
     * @return Application|Factory|View|\Illuminate\Http\Response
     */
    public function index()
    {

        $list = $unauthorized = [];

        if(app('CompanySetup')->verify_clients == 1){
            $list = Client::where('confirmed', 1)->orderBy('nms', 'asc')->get();

            /*Client::where('confirmed', 1)->orderBy('nms', 'asc')
                ->chunk(100, function($users) use ($list) {
                    foreach ($users as $user) {
                        $list[] = $user;
                    }
                });*/
        }else{
            $list = Client::orderBy('nms', 'asc')->get();
            /*Client::orderBy('nms', 'asc')
                ->chunk(100, function($users) use ($list) {
                    foreach ($users as $user) {
                        $list[] = $user;
                    }
                });*/
        }
        $disabled = Client::where('status', 0)->orderBy('nms', 'asc')->get();
        $prospects = Client::where('is_prospect', 1)->orderBy('nms', 'asc')->get();
        $unauthorized = Client::where('confirmed', 0)->orderBy('nms', 'asc')->get();
       /* Client::where('confirmed', 0)->orderBy('nms', 'asc')
            ->chunk(100, function($users) use ($unauthorized) {
                foreach ($users as $user) {
                    $unauthorized[] = $user;
                }
         });*/
        $trash = Client::where('deleted', 1)->orderBy('deleted_at', 'desc')->get();
        return view('clients', compact('list','unauthorized', 'disabled', 'prospects', 'trash'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Application|Factory|View|\Illuminate\Http\Response
     */
    public function create($module = null)
    {
        //return view('add-client');
        $branches = CompanyBranch::where('status', 1)->orderby('name', 'asc')->get();
        $riskmanagers = [];
        $subagents = [];
        $users = User::where('e_status', 1)->orderby('firstname', 'asc')->get();
        $schemes = [];
        return view('/add-client', compact('branches','module','riskmanagers', 'subagents', 'users', 'schemes'));
    }

    /**Edit Client Details**/
    public function showEditClientDetails($id){
        $client = Client::where('c_id', $id)->first();
        return view('edits.edit-client-details', compact('client', 'id'));
    }

    /**Save Client Details**/
    public function storeEditClientDetails($id, Request $request){
        $branch = $request['branch'];
        $module = $request['module'];
        $category = $request['category'];
        $subCategory = $request['sub-category'] ?? null;
        $title = $request['title'];
        $gender = $request['gender'];
        $names = $request['names'];
        $phone = $request['phone'];
        $email = $request['email'];
        $altPhone = $request['alt-phone'];
        $altEmail = $request['alt-email'];
        $idNo = $request['id-no'];
        $pin = $request['pin'];
        $dob = $request['dob'];
        $box = $request['box'];
        $address = $request['address'];
        $occupation = $request['occupation'];


        /**Get the Client Instance**/
        $client = Client::where('c_id', $id)->first();
        $res= 'empty name';
        if($names != null){
            $res = 'error';
            if($client->update(
                [
                    'branch' => $branch,
                    'module' => $module,
                    'category' => $category,
                    'sub_cat' => $subCategory,
                    'title' => $title,
                    'gnd' => $gender,
                    'nms' => $names,
                    'pn' => $phone,
                    'em' => $email,
                    'alt_pn' => $altPhone,
                    'alt_em' => $altEmail,
                    'id_no' => $idNo,
                    'pin' => $pin,
                    'dob' => $dob,
                    'pob' => $box,
                    'address' => $address,
                    'occp' => $occupation
                ]
            )){
                $res = 'success';

                /**Register a Log for the Entry**/
                $add_history = new HistoryClient;
                $narration = 'Client Details have been updated by '. auth()->user()->firstName .' '. auth()->user()->lastName.' on '. date('d/m/Y h:i:s a');

                $add_history->c_id = $id;
                $add_history->narration = $narration;
                $add_history->created_by = auth()->user()->id;
                $add_history->save();
            }
        }
        return $res;
    }

    public function approveForm(int $id)
    {
       $client = Client::where('c_id', $id)->first();

       return view('libs.approve-client', compact('client'));
    }

    /*APPROVE CLIENT ACCOUNT*/
    public function approve(Request $request, int $id)
    {
        $comment = $request['comments'];
        if(!empty($comment)){
            $client = Client::where('c_id', $id)->first();

            $client->confirmed = 1;
            $client->confirmed_comments = $comment;
            $client->confirmed_by = auth()->user()->id;
            $client->confirmed_at = now();
            if($client->save()){

                $add_history = new HistoryClient;
                $narration = 'Client (<b>'.$client->nms.'</b>) account was approved by '. auth()->user()->firstName .' '. auth()->user()->lastName.' on '. date('d/m/Y h:i:s a');

                $add_history->c_id = $id;
                $add_history->narration = $narration;
                $add_history->created_by = auth()->user()->id;
                $add_history->save();

                $res = 'success';
            }else{
                $res = 'error';
            }
        }else{
            $res = 'empty comment';
        }
        return $res;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    public function store(Request $request, $docId = null, $module = null)
    {
        $request->validate([
            'c_id' => ['number', 'max:10', 'unique:clnts'],
            'fl_no' => ['string', 'max:10', 'unique:clnts'],
            'em' => ['string', 'email', 'max:50'],
            'alt_em' => ['string', 'email', 'max:50']
        ]);

        $category = $request->category;
        if($category == 1){
            $sub_category = $request->sub_category;
        }else{
            $sub_category = "";
        }
        $c_name = $request['nms'];
        $module = $request['module'];
        $phone = $request['pn'];
        $email = $request['email'];
        $idno = $request['idn'];
        $pin = $request['kra'];
        $dob = $request['dob'];
        $address = $request['address'];
        $box = $request['box'];
        $occp = $request['occupation'];
        $tel = $request['office_tel'];
        $alt_email = $request['alt_email'];
        $gender = $request['gender'];

        $symbol = strtoupper(substr($c_name,0,1));
        $last_no = 0;
        if(Client::where('fl_no',  'LIKE',"%{$symbol}%")->first()){
            $last = Client::where('fl_no',  'LIKE',"%{$symbol}%")->orderBy('fl_no', 'DESC')->first();
            $last_no = substr($last->fl_no,1);
        }

        $next_no = $last_no + 1;
        $full_number = sprintf('%1$04d', $next_no);
        $fl_no = $symbol.$full_number;

        $sales_type = $request['sales-type'];

        $branch = 1;
        $introduce_by = $account_handler = $sub_agent = $source = null;
        if($request->branch != null){
            $branch = $request['branch'];
        }
        if(isset($request['source'])){
            $source = $request['source'];
        }
        if($request['brought_by'] != null){
            $introduce_by = $request['brought_by'];
        }
        if($request['account_handler'] != null){
            $account_handler = $request['account_handler'];
        }
        if($request['sub_agent'] != null){
            $sub_agent = $request['sub_agent'];
        }
        $scheme = $request['scheme'] ?? null;

        if($category == null){
            return 'empty category';
        }else{
            // we need to check and confirm that the client does not exist in our database
            if(Client::where('module', $module)->where('nms', $c_name)->where('id_no', $idno)->where('pin', $pin)->first()){
                return 'client exist';
            }else{
                if(empty($sales_type)){
                    return 'empty sales type';
                }else{
                    $init = new Client;
                    $randomNumbers = new RandomNumbersController();
                    $suggestedNumber = $randomNumbers->getRandomNumbers(10);
                    //return $suggested Number;
                    if(!$randomNumbers->numberExists($suggestedNumber, 'c_id')){
                        $c_id = $suggestedNumber;
                    }else{
                        return "System Error";
                    }

                    if($sales_type == 'direct'){
                        $sales_type_id = 0;
                    }else{
                        $sales_type_id = 1;
                    }

                    $init->c_id = $c_id;
                    $init->fl_no = $fl_no;
                    $init->module = $module;
                    $init->category = $category;
                    $init->sub_cat = $sub_category;
                    $init->branch = $branch;
                    $init->nms = $c_name;
                    $init->gnd = $gender;
                    $init->dob = $dob;
                    $init->pn = $phone;
                    $init->alt_pn = $tel;
                    $init->id_no = $idno;
                    $init->em = $email;
                    $init->pin = $pin;
                    $init->alt_em = $alt_email;
                    $init->pob = $box;
                    $init->address = $address;
                    $init->occp = $occp;
                    $init->created_by = auth()->user()->id;
                    $init->introduced_by = $introduce_by;
                    $init->handled_by = $account_handler;
                    $init->sales_type = $sales_type_id;
                    $init->leeds = $source;
                    $init->sub_agent = $sub_agent;
                    $init->scheme = $scheme;

                    if($init->save()){
                        if($docId > 0){
                            DB::table('clnt_kyc_docs')->where('c_id', $docId)
                                ->update(['c_id'=>$c_id, 'status'=>'1']);
                            /*$docInit = ClientKYCDoc::where('c_id', $docId)->get();

                            $docInit->c_id = $c_id;
                            $docInit->status = '1';
                            $docInit->save();*/
                        }

                        $add_history = new HistoryClient;
                        $narration = 'Client (<b>'.$c_name.'</b>) was added by '. auth()->user()->firstName .' '. auth()->user()->lastName.' on '. date('d/m/Y h:i:s a');

                        $add_history->c_id = $c_id;
                        $add_history->narration = $narration;
                        $add_history->created_by = auth()->user()->id;
                        $add_history->save();


                        if($request->has('alt_nm')){
                            foreach ($request['alt_nm'] as $key => $val){
                                $alt_name = $request->alt_nm[$key];
                                $alt_relation = $request->rltn[$key];
                                $alt_person_phone = $request->alt_tel[$key];
                                $alt_person_email = $request->alt_psn_email[$key];
                                if($alt_name != null){
                                    $init2 = new ClientAlternativePerson;

                                    $init2->c_id = $c_id;
                                    $init2->name = $alt_name;
                                    $init2->relationship = $alt_relation;
                                    $init2->phone = $alt_person_phone;
                                    $init2->email = $alt_person_email;
                                    $init2->save();
                                }
                            }
                        }
                        //return view('client/'.$c_id);
                        return $c_id;
                    }else{
                        return 'Error occurred';
                    }
                }
            }
        }
    }

    /**Download Client Documents**/


    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return Application|Factory|View|\Illuminate\Http\Response
     */
    public function show(int $ids)
    {

        $id = $ids;
        $clients = Client::where('status', '1')->orderBy('nms', 'asc')->get();
        $client = Client::where('c_id', $id)->first();
        $riskManager = [];


        $projects = [];
        $unauthorized = [];
        $quotes = [];

        $uid = User::where('id', $client->created_by)->first();
        $history = HistoryClient::where('c_id', $client->c_id)->orderby('created_at', 'desc')->get();

        $documents = [];
        if(ClientKYCDoc::where('c_id', $id)->first()){
            $documents = ClientKYCDoc::where('c_id', $id)->get();
        }

        return view('client', compact('clients','client','quotes','unauthorized','projects','documents','riskManager','history', 'uid'));

        //$history = HistoryClient::where('c_id', $id)->orderby('created_at', 'desc')->get();
        //return view('client', compact('history'))->with('error', 'not Found');
    }

    /**ClientPolicies**/
    public function showClientPolicies($id){
        $client = Client::firstWhere('c_id', $id);
        $policies = [];
        if($client->clientPolicies != null){
            $policies = $client->clientPolicies;
        }
        //dd($policies);
        return view('libs.client-policy-list', compact('policies'));
    }


    public function search(){
        $clients = Client::orderBy('nms', 'asc')->get();
        return view('libs.search-client', compact('clients'));
    }

    /**SEARCH CLIENT FOR FINANCE USE**/
    public function searchClientFinance(){

        $clients = Client::orderBy('nms', 'asc')->get();
        return view('libs.search-client-finance', compact('clients'));
    }

    /**Search a Client by Typing the Name of Client**/
    public function searchClientByName($name){
        $clients = [];
        if(Client::where('nms', 'like', '%' . $name . '%')->first()){
            $clients =  Client::where('nms', 'like', '%' . $name . '%')->get();
        }
        return view('search.search-client-by-name', compact('clients'));
    }

    /**Return Client ID for the Searched Client By Name**/
    public function searchedClientId(Request $request){
        $name = $request['client-name'] ?? 'empty' ;
        $id = 'no client';
        if($name != 'empty'){
            $id = 'not exist';
            $client = Client::where('nms', $name)->first();
            if($client){
                $id = $client->c_id;
            }
        }
        return $id;
    }

    /**Search a Client by Typing the Name of Client**/
    public function searchClientByNameAddId($name){
        $clients = [];
        if(Client::where('nms', 'like', '%' . $name . '%')->first()){
            $clients =  Client::where('nms', 'like', '%' . $name . '%')->get();
        }
        return view('search.search-client-by-name-add-id', compact('clients'));
    }

    /**Search a Client by Typing the Name of Client**/
    public function searchClientByNameAddIdTwo($name){
        $clients = [];
        if(Client::where('nms', 'like', '%' . $name . '%')->first()){
            $clients =  Client::where('nms', 'like', '%' . $name . '%')->get();
        }
        return view('search.search-client-by-name-add-id-two', compact('clients'));
    }



    /**Add Premium Receipt/Payment on Client's Policies**/
    public function showAddPremiumReceipt($id, $module = null,$type = null ){
       $client = $this->clientParticulars($id);
       $clients = Client::where('confirmed', 1)->orderBy('nms', 'asc')->get();
       if($client){
           $baseCurrency = $otherCurrencies = [];
           if(CompanyCurrency::where('type', 'base')->first()){
               $baseCurrency = CompanyCurrency::where('type', 'base')->first();
           }
           if(CompanyCurrency::where('type', 'other')->first()){
               $otherCurrencies = CompanyCurrency::where('type', 'other')->get();
           }
           $modesOfPayment = CompanyMainPaymentMode::orderBy('name', 'asc')->get();
           /**Get All Insurer's where the Client has a Policy with**/
           $insurers = [];
           if(Policy::where('c_id',$id)->first()){
               $insurers = Policy::where('c_id',$id)->where('first_confirmed', 1)->distinct()->get(['ins_id']);
               /*foreach ($insurers as $row){
                   if(Insurer::where('ins_id', $row->ins_id)->first()){
                       $ins_id = $row->ins_id;
                       $name = Insurer::where('ins_id', $row->ins_id)->first()->nm;
                       $insurers = [
                           'id' => $ins_id,
                           'name' => $name
                       ];
                   }
               }*/
           }
           //dd($insurers);

           $data = [
               'insurers' => $insurers,
               'modes' => $modesOfPayment,
           ];


           return view('add-premium-receipt', compact('client','clients','type', 'module','data', 'baseCurrency', 'otherCurrencies'));
       }
       return view('erros.404');
    }

    /**Store Client Receipt/Payment**/
    public function updateAddPremiumReceipt($id, Request $request,$type = null, $module = null):string
    {
        $client = $this->clientParticulars($id);
        $user = auth()->user()->id;
        $branch = auth()->user()->branch;

        $option = $request['option'];
        //$receiptingType = $request['receipt-items'];
        $bankAccount = null;
        if($option == 'pay us'){
            $bankAccount = $request['account'] ?? 'empty';
        }
        $insurer = 'multiple';
        if($option == 'pay insurer'){
           $insurer = $request['insurer'] ?? 'empty';
        }
        $mode = $request['payment-mode'];
        $subMode = null;
        if(CompanyMainPaymentMode::where('id', $mode)->first()){
            if(CompanySubModesOfPayment::where('mode_id', $mode)->first()){
                $subMode = $request['sub-mode'] ?? 'empty';
            }
        }
        $ref = $request['ref'];
        $insurerReceipt = 'none';
        if($option == 'pay insurer'){
            $insurerReceipt = $request['insurer-receipt'];
        }
        $narration = $request['narration'];
        $currency = $request['currency'];
        $conversionRate = 1;
        if($request->has('conversion-rate')){
            $conversionRate = $request['conversion-rate'] ?? 'empty';
        }
        $datePaid = $request['date-paid'];
        $amountPaid = preg_replace('/,/','',$request['total-amount']);

        $res = 'empty option';
        if(!empty($option)){
            $res = 'empty insurer';
            if($insurer != 'empty'){
                $res = 'empty account';
                if($bankAccount != 'empty'){
                    $res = 'empty mode';
                    if(!empty($mode)){
                        $res = 'empty sub-mode';
                        if($subMode != 'empty'){
                            $res = 'empty ref';
                            if(!empty($ref)){
                                $res = 'empty insurer receipt';
                                /*if(!empty($insurerReceipt)){$res = 'empty narration';   }*/
                                if(!empty($narration)){
                                    $res = 'empty conversion rate';
                                    if($conversionRate != 'empty'){
                                        $res = 'empty date';
                                        if(!empty($datePaid)){
                                            $res = 'zero amount';
                                            if($amountPaid > 0){
                                                /**Create an Instance of Direct Payment and Insert the Record**/
                                                if($option == 'pay insurer'){
                                                    $init = new DirectPremiumPayment;

                                                    $newPV = 1001;
                                                    if(DirectPremiumPayment::first()){
                                                        $lastPV = DirectPremiumPayment::orderBy('pv_id', 'desc')->first()->pv_id;
                                                        $newPV = $lastPV + 1;
                                                    }
                                                    /**Generate a Unique Stamp**/
                                                    $stamp = (new RandomNumbersController)->getRandomMix(30);

                                                    $res = 'error';
                                                    if(!DirectPremiumPayment::where('stamp', $stamp)->first()){
                                                        /**Create a Direct Payment Voucher**/
                                                        $res = (new DirectPremiumPaymentController)->createNewDirectPayment($init, $datePaid, $newPV,$insurer, $id,$branch,$mode, $subMode,$ref, $insurerReceipt,$narration, $amountPaid,$currency, $conversionRate,$stamp, $user);

                                                        /**If it's Successful, then Allocate the Payment**/
                                                        if($res == 'success'){
                                                            /**Add DPV to Client's Statement**/  //Insert the Amount Paid as a Negative Value
                                                            /**We need to ensure that we can get the ID of the DPV that has been done to ensure that we can store the ID in the table: We use the Stamp above**/
                                                            $dpvID = DirectPremiumPayment::where('stamp', $stamp)->first()->pv_id ?? null;

                                                            $clientStatement = new BillMasterClient;
                                                            (new BillMasterClientController)->insertNewPremiumPayment($clientStatement,$id,'credit',$dpvID,$datePaid,$insurer,'DPV','Direct Payment Voucher',-$amountPaid,$currency,$conversionRate);

                                                            /**Proceed to Allocate the Direct Payment Voucher**/
                                                            foreach ($request['debit-note'] as $key => $value){
                                                                $amountAllocated = $request['amount-paid'][$key];
                                                                $pl_cd = $request['debit-note'][$key];
                                                                if($amountAllocated > 0){
                                                                    $allocate = new AllocatePolicyPremiumPaid;

                                                                    $res = (new AllocatePolicyPremiumPaidController)->singleAllocation($allocate, 'DPV',$newPV,$pl_cd,$amountAllocated,'Direct Payment',$user);
                                                                }
                                                            }
                                                            if($res == 'success'){
                                                                $res = '/direct-payment-voucher/'.$stamp.'?type=summary';
                                                                if($module == 'finance'){
                                                                    $res = '/direct-payment-voucher/'.$stamp.'/finance?type=summary';
                                                                }
                                                            }
                                                        }
                                                    }

                                                }/**For a Premium Payment to Us, Create a Receipt for this**/
                                                else{
                                                    $init = new Receipt();

                                                    /**Check if Initial Receipts No have been defined**/
                                                    if(!Receipt::withTrashed()->orderBy('rct_id', 'desc')->first()){
                                                        if(CompanyDocumentNumber::where('type', 'receipt')->first()){
                                                            $newRCT = CompanyDocumentNumber::where('type', 'receipt')->first()->number;
                                                        }else{
                                                            $newRCT = 1;
                                                        }
                                                    }else{
                                                        $lastRCT = Receipt::withTrashed()->orderBy('rct_id', 'desc')->first()->rct_id;
                                                        $newRCT = $lastRCT + 1;
                                                    }
                                                    /**Generate a Unique Stamp**/
                                                    $stamp = (new RandomNumbersController)->getRandomMix(30);

                                                    $res = 'error';
                                                    if(!Receipt::where('stamp', $stamp)->first()){
                                                        /**Create a Receipt from Payment Made**/
                                                        $res = (new ReceiptController())->createNewReceipt($init, $datePaid, $newRCT,$bankAccount,'premium', $id,null,$branch,$mode, $subMode,$ref,$narration, $amountPaid,$currency, $conversionRate,$stamp, $user);

                                                        /**If it's Successful, then Allocate the Receipt**/
                                                        if($res == 'success'){
                                                            /**Update Document Number/Starting number so that we don't use the Set Receipt Number Again**/
                                                            if(CompanyDocumentNumber::where('type', 'invoice')->first()){
                                                                if($newRCT == CompanyDocumentNumber::where('type', 'receipt')->first()->number){
                                                                    $start_no = CompanyDocumentNumber::where('type', 'receipt')->where('number', $newRCT)->first();

                                                                    $start_no->no_used = 1;
                                                                    $start_no->save();
                                                                }
                                                            }

                                                            /**Add RCT to Client's Statement**/ //Insert the Amount Paid as a Negative Value
                                                            /**We need to ensure that we can get the ID of the Receipt that has been done to ensure that we can store the ID in the table: We use the Stamp above**/
                                                            $receiptID = Receipt::where('stamp', $stamp)->first()->rct_id ?? null;

                                                            $clientStatement = new BillMasterClient;
                                                            (new BillMasterClientController)->insertNewPremiumPayment($clientStatement,$id,'credit',$receiptID,$datePaid,null,'RCT','Premium Receipt',-$amountPaid,$currency,$conversionRate);

                                                            /**Allocate the Receipt Now from the Payment made by the Client**/
                                                            foreach ($request['debit-note'] as $key => $value){
                                                                $amountAllocated = $request['amount-paid'][$key];
                                                                $pl_cd = $request['debit-note'][$key];
                                                                if($amountAllocated > 0){
                                                                    $allocate = new AllocatePolicyPremiumPaid;

                                                                    $res = (new AllocatePolicyPremiumPaidController)->singleAllocation($allocate, 'RCT',$newRCT,$pl_cd,$amountAllocated,'Premium Receipt',$user);

                                                                }
                                                            }

                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return $res;
    }


    /**Show Client Statement Now**/
    public function showStatement(Request $request, $id=null, $type=null,$module=null)
    {
        $clients = Client::where('status', 1)->orderBy('nms', 'ASC')->get();
        $insurers = Insurer::where('status', 1)->get();
        $currencies = CompanyCurrency::where('status', 1)->get();

        if(Client::where('c_id', $id)->first()){
            if($type == 'un-allocated'){
                $statementType = 'Un-Allocated Statement';
            }elseif($type == 'allocated'){
                $statementType = 'Allocated Statement';
            }else{
                $statementType = 'Un-Allocated Statement';
            }

            /**Default Dates/Statement Periods**/
            $from =  \Carbon\Carbon::now()->format('Y').'-01-01';
            $to = now();
            $currency = null;
            /**Check to See if Filter was used**/
            $insurer = null;
            if($request->has('search')){
                $type = $request['statement-type'];
                if($type == 'allocated'){
                    $statementType = 'Allocated Statement';
                }else{
                    $statementType = 'Un-Allocated Statement';
                }
                $from = $request['from']." 00:00:00";
                $to = $request['to']." 23:59:59";
                $type = $request['statement-type'];
                /**Insurer Option**/
                $insurer = $request['insurer'];
                if($insurer != 'all'){
                    if(Insurer::where('ins_id', $insurer)->first()){
                        $insurerName = Insurer::where('ins_id', $insurer)->first()->nm;
                    }
                }
                $currency = $request['currency'];
                if($currency != 'all'){
                    if(CompanyCurrency::where('id', $currency)->first()){
                        $currencyName = CompanyCurrency::where('id', $currency)->first()->abbr;
                    }
                }
            }

            $search = [
                'from' => $from,
                'to' => $to,
                'type' => $statementType,
                'insurer' => $insurer,
                'insurerName' => $insurerName ?? 'ALL INSURERS',
                'currency' => $currency,
                'currencyName' => $currencyName ?? 'ALL CURRENCIES'
            ];


            $client = Client::where('c_id', $id)->first();
            $result = $this->getClientStatement($id,$type ?? 'un-allocated', $currency,$from, $to, $insurer);

            $aging = $this->getClientAgingBalance($id);
            /**Download Links**/
            $dateFrom = date('Y-m-d', strtotime($from));
            $dateTo = date('Y-m-d', strtotime($to));

            /**If Type is Null, automatically make it to be un-allocated statement**/
            if($type == null){
                $type = 'un-allocated';
            }
            $download = [
                'pdf' =>'client-statement-pdf/'.$id.'/'.$type.'/'.$dateFrom.'/'.$dateTo.'/'.$currency.'/'.$insurer,
                'excel' => 'client-statement-excel/'.$id.'/'.$type.'/'.$dateFrom.'/'.$dateTo.'/'.$currency.'/'.$insurer
            ];

            return  view('client-statement', compact('client','result','aging','type','clients','module','insurers','currencies','id', 'search', 'download'));
        }else{
            return  view('client-statement', compact('type','clients','module','id'));

        }
    }

    /**Work on a Client Statement**/
    public function getClientStatement($id, $type, $currency=null, $from=null, $to=null,$insurer=null,$view=null):string{
        $client = Client::where('c_id', $id)->first();
        /**If Start Date is Specified, then confirm to check if we can get the Opening Balances**/
        if($from == null){
            $from = \Carbon\Carbon::now()->format('Y').'-01-01';
        }
        if($to == null){
            $to = \Carbon\Carbon::now()->format('Y-m-d');
        }

        /**Opening Balance Details**/
        $openingBalance = BillMasterClient::where('c_id', $id)->whereDate('date', '<', $from)->where([
            [function($list) use ($insurer,$currency ) {
                /**CHECK FOR SELECTED INSURER**/
                if($insurer != null ){
                    if($insurer != 'all'){
                        $list = $list->where('insurer', $insurer);
                    }
                }
                /**CHECK FOR SELECTED CURRENCY**/
                if($currency != null){
                    if($currency != 'all'){
                        $list = $list->where('currency', $currency);
                    }
                }
            }]
        ])->sum('amount');


        /**Statement List**/
        $list = BillMasterClient::where('c_id', $id)->whereBetween('date', [$from, $to])->where([
            [function($list) use ($insurer,$currency ) {
                /**CHECK FOR SELECTED INSURER**/
                if($insurer != null ){
                    if($insurer != 'all'){
                        $list = $list->where('insurer', $insurer);
                    }
                }
                /**CHECK FOR SELECTED CURRENCY**/
                if($currency != null){
                    if($currency != 'all'){
                        $list = $list->where('currency', $currency);
                    }
                }
            }]
        ])->orderBy('date', 'asc')->get();

        $table = '';
        $sumDr=$sumCr=$sumOther=0;
        /**Show the Opening Balance Row: Consider View Option**/
        //Only Show Opening Balance for Un-allocated Statement
        if($type != 'allocated'){
            $table = '<tr>';
            $table .= '<td class="ar" colspan="6" style="border-bottom: 2px solid black"></td>';
            $table .= '<td style="padding: 5px 3px;border-bottom: 2px solid black"><i class="error"><b>Opening Balance</b></i></td>';
            if($openingBalance > 0){
                $table .= '<td style="border-bottom: 2px solid black;text-align: right">'.number_format($openingBalance,2).'</td>';
                $sumDr += $openingBalance;
            }else{
                $table .= '<td style="border-bottom: 2px solid black;text-align: right">0.00</td>';
            }
            if($openingBalance < 0){
                $table .= '<td style="border-bottom: 2px solid black;text-align: right">'.number_format($openingBalance,2).'</td>';
                $sumCr += $openingBalance;
            }else{
                $table .= '<td style="border-bottom: 2px solid black;text-align: right">0.00</td>';
            }
            $table .= '<td style="border-bottom: 2px solid black;text-align: right">'.number_format($openingBalance,2).'</td>';
            $table .= '</tr>';
        }



        /**If User Selected Allocated Statement type**/
        $x = 0;
        if($type == 'allocated'){
            $totalBalance = 0;
            /**Allocated Statement Involves Entries with their respective allocations**/
            foreach ($list as $row){
                $x++;
                /**Only Get Debit Entries**/
                if($row->type == 'debit'){
                    if(Policy::where('pl_cd', $row->ref)->first()){
                        $plcy = Policy::where('pl_cd', $row->ref)->first();
                        $dr = $row->amount;
                        $authorizedCreditNotes = (new PolicyCreditEndorsementController)->authorizedCredits($row->ref)['total_amount'];
                        $premium_paid = (new AllocatePolicyPremiumPaidController)->totalAllocatedPremium( $row->ref);

                        /**Calculate the Balance of your Policy**/
                        $balance = (new TradeDebtorsController)->policyDebt($row->ref)['amount'];
                        //dd($balance);
                        $totalBalance +=$balance;
                        $transType = $ref = $link ='';
                        if($row->trans_type == 'new'){
                            $transType = 'NEW BUSINESS';
                            $ref = 'DN'.$row->ref;
                        }elseif ($row->trans_type == 'renewal'){
                            $transType = 'RENEWAL';
                            $ref = 'DN'.$row->ref;
                        }elseif ($row->trans_type == 'endorsement'){
                            $transType = 'DEBIT ENDORSEMENT';
                            $ref = 'END'.$row->ref;
                        }
                        $link = '<a href="/policy/'.$row->ref.'?type=summary" class="inner" target="_blank" style="color: red; font-weight: bold">'.$ref.'</a>';

                        /**Show your Table Here**/
                        $table .= '<tr>';
                        $table .= '<td style="border-bottom: 2px solid black" class="ar">'.$x.'</td>';
                        if($view == null){
                            $table .= '<td style="padding: 6px;border-bottom: 2px solid black">'.$link.'</td>';
                        }else{
                            $table .= '<td style="padding: 6px;border-bottom: 2px solid black">'.$ref.'</td>';
                        }
                        $table .= '<td style="border-bottom: 2px solid black">'.date('d-m-Y', strtotime($row->date)).'</td>';
                        $table .= '<td style="border-bottom: 2px solid black">'.$transType.'</td>';
                        /**Insurer Details**/
                        $insurer = '';
                        if($row->insurerDetails != null){
                            $insurer = $row->insurerDetails->nm;
                        }
                        $table .= '<td style="border-bottom: 2px solid black"><b>'.$insurer.'</b></td>';
                        $table .= '<td style="border-bottom: 2px solid black">'.$row->plcy_no.'</td>';
                        $table .= '<td style="border-bottom: 2px solid black">'.$plcy->policyIndividualItems($row->ref).'</td>';
                        $table .= '<td style="border-bottom: 2px solid black;text-align: right">'.number_format($dr,2).'</td>';
                        $table .= '<td style="border-bottom: 2px solid black;text-align: right">('.number_format(abs($authorizedCreditNotes),2).')</td>';
                        $table .= '<td style="border-bottom: 2px solid black;text-align: right">('.number_format(abs($premium_paid),2).')</td>';
                        $table .= '<td style="border-bottom: 2px solid black;text-align: right">'.number_format($balance,2).'</td>';
                        $table .= '</tr>';
                        /**Sum all Figures per Column**/
                        $sumDr +=$dr;
                        $sumCr +=$authorizedCreditNotes;
                        $sumOther +=$premium_paid;
                    }

                }
            }
            /**Add a Totals Section**/
            if($view != null){
                $table .= '<tr >';
                $table .= '<td colspan="7"></td>';
                $table .= '<td class="error" style="padding: 6px;text-align: right;border-bottom: 2px solid black;font-size: 6pt;font-weight: bold">'.number_format($sumDr,2).'</td>';
                $table .= '<td class="error" style="text-align: right;border-bottom: 2px solid black;font-size: 6pt;font-weight: bold">('.number_format(abs($sumCr),2).')</td>';
                $table .= '<td class="error" style="text-align: right;border-bottom: 2px solid black;font-size: 6pt;font-weight: bold">('.number_format(abs($sumOther),2).')</td>';
                $table .= '<td class="error" style="text-align: right;border-bottom: 2px solid black;font-size: 6pt;font-weight: bold">'.number_format($totalBalance,2).'</td>';
                $table .= '</tr>';
            }else{
                $table .= '<tr >';
                $table .= '<td colspan="7"></td>';
                $table .= '<td class="error" style="padding: 6px;text-align: right;border-bottom: 2px solid black;font-size: 9pt;font-weight: bold">'.number_format($sumDr,2).'</td>';
                $table .= '<td class="error" style="text-align: right;border-bottom: 2px solid black;font-size: 9pt;font-weight: bold">('.number_format(abs($sumCr),2).')</td>';
                $table .= '<td class="error" style="text-align: right;border-bottom: 2px solid black;font-size: 9pt;font-weight: bold">('.number_format(abs($sumOther),2).')</td>';
                $table .= '<td class="error" style="text-align: right;border-bottom: 2px solid black;font-size: 9pt;font-weight: bold">'.number_format($totalBalance,2).'</td>';
                $table .= '</tr>';
            }




        }else{
            $balance = $openingBalance;
            $dr=$cr=$other=0;
            foreach ($list  as $row){
                $x++;
                $balance += $row->amount;
                /**Entries Details**/
                $transType = $ref = $link ='';
                if($row->trans_type == 'new'){
                    $transType = 'NEW BUSINESS';
                    $ref = 'DN'.$row->ref;
                    $link = '<a href="/policy/'.$row->ref.'?type=summary" class="inner" target="_blank" style="color: red; font-weight: bold">'.$ref.'</a>';
                }elseif ($row->trans_type == 'renewal'){
                    $transType = 'RENEWAL';
                    $ref = 'DN'.$row->ref;
                    $link = '<a href="/policy/'.$row->ref.'?type=summary" class="inner" target="_blank" style="color: red; font-weight: bold">'.$ref.'</a>';
                }elseif ($row->trans_type == 'endorsement'){
                    if($row->type == 'debit'){
                        $transType = 'DEBIT ENDORSEMENT';
                        $ref = 'END'.$row->ref;
                        $link = '<a href="/policy/'.$row->ref.'?type=summary" class="inner" target="_blank" style="color: red; font-weight: bold">'.$ref.'</a>';
                    }elseif ($row->type == 'credit'){
                        $transType = 'CREDIT ENDORSEMENT';
                        $ref = 'CN'.$row->ref;
                        $link = '<a href="/credit-note/'.$row->ref.'?type=summary" class="inner" target="_blank" style="color: red; font-weight: bold">'.$ref.'</a>';
                    }
                }elseif ($row->trans_type == 'RCT'){
                    $transType = 'RECEIPT';
                    $ref = 'RCT'.$row->ref;
                    /**Get Stamp of Receipt**/
                    $receiptStamp = '';
                    if(Receipt::where('rct_id', $ref)->first()){
                        $receiptStamp = Receipt::where('rct_id', $ref)->first()->stamp;
                    }
                    $link = '<a href="/receipt/'.$receiptStamp.'?type=summary" class="inner" target="_blank" style="color: red; font-weight: bold">'.$ref.'</a>';
                }elseif ($row->trans_type == 'RCT Reversal'){
                    $transType = 'RECEIPT REVERSAL';
                    $ref = 'REVERSAL'.$row->ref;
                    /**Get Stamp of Receipt**/
                    $receiptStamp = '';
                    if(Receipt::where('rct_id', $ref)->first()){
                        $receiptStamp = Receipt::where('rct_id', $ref)->first()->stamp;
                    }
                    $link = '<a href="/receipt/'.$receiptStamp.'?type=summary" class="inner" target="_blank" style="color: red; font-weight: bold">'.$ref.'</a>';
                }elseif ($row->trans_type == 'DPV'){
                    $transType = 'DIRECT PAYMENT';
                    $ref = 'DPV'.$row->ref;
                    /**Get Stamp of Receipt**/
                    $dpvStamp = '';
                    if(DirectPremiumPayment::where('pv_id', $ref)->first()){
                        $dpvStamp = DirectPremiumPayment::where('pv_id', $ref)->first()->stamp;
                    }
                    $link = '<a href="/direct-payment-voucher/'.$dpvStamp.'?type=summary" class="inner" target="_blank" style="color: red; font-weight: bold">'.$ref.'</a>';
                }elseif ($row->trans_type == 'DPV Reversal'){
                    $transType = 'DIRECT PAYMENT REVERSAL';
                    $ref = 'REVERSAL'.$row->ref;
                    /**Get Stamp of Receipt**/
                    $dpvStamp = '';
                    if(DirectPremiumPayment::where('pv_id', $ref)->first()){
                        $dpvStamp = DirectPremiumPayment::where('pv_id', $ref)->first()->stamp;
                    }
                    $link = '<a href="/direct-payment-voucher/'.$dpvStamp.'?type=summary" class="inner" target="_blank" style="color: red; font-weight: bold">'.$ref.'</a>';
                }

                /**Get if the amount is for a Debit, Credit or a Payment**/
                if($row->amount > 0){
                    $dr = $row->amount;
                    $cr=0;
                }else{
                    $dr = 0;
                    $cr = abs($row->amount);
                    /*if($row->trans_type == 'RCT' || $row->trans_type == 'DPV'){
                        $other = abs($row->amount);
                    }else{
                        $cr = abs($row->amount);
                    }*/
                }

                $table .= '<tr>';
                $table .= '<td style="border-bottom: 2px solid black" class="ar">'.$x.'.</td>';
                if($view == null){
                    $table .= '<td style="padding: 6px;border-bottom: 2px solid black">'.$link.'</td>';
                }else{
                    $table .= '<td style="padding: 6px;border-bottom: 2px solid black">'.$ref.'</td>';
                }
                $table .= '<td style="border-bottom: 2px solid black">'.date('d-m-Y', strtotime($row->date)).'</td>';
                $table .= '<td style="border-bottom: 2px solid black">'.$transType.'</td>';
                /**Insurer Details**/
                $insurer = '';
                if($row->insurerDetails != null){
                    $insurer = $row->insurerDetails->nm;
                }
                $table .= '<td style="border-bottom: 2px solid black"><b>'.$insurer.'</b></td>';
                $table .= '<td style="border-bottom: 2px solid black">'.$row->plcy_no.'</td>';

                if($row->type == 'debit'){
                    /**For Debit type, check/find the Individual Items from Policy Model**/
                    if(Policy::where('pl_cd', $row->ref)->first()){
                        $plcy = Policy::where('pl_cd', $row->ref)->first();
                        $table .= '<td style="border-bottom: 2px solid black">'.$plcy->policyIndividualItems($row->ref).'</td>';
                    }else{
                        $table .= '<td style="border-bottom: 2px solid black"></td>';
                    }
                }else{
                    /**For Credit type, Just Print the Details**/
                    $table .= '<td style="border-bottom: 2px solid black">'.$row->details.'</td>';
                }

                $table .= '<td style="border-bottom: 2px solid black;text-align: right">'.number_format($dr,2).'</td>';
                $table .= '<td style="border-bottom: 2px solid black;text-align: right">'.number_format($cr,2).'</td>';
                $table .= '<td style="border-bottom: 2px solid black;text-align: right">'.number_format($balance,2).'</td>';
                $table .= '</tr>';

                /**Sum all Figures per Column**/
                $sumDr +=$dr;
                $sumCr +=$cr;
            }
            /**Add a Totals Section**/

            if($view != null){
                $table .= '<tr >';
                $table .= '<td colspan="7"></td>';
                $table .= '<td class="error" style="padding: 6px;text-align: right;border-bottom: 2px solid black;font-size: 6pt;font-weight: bold">'.number_format($sumDr,2).'</td>';
                $table .= '<td class="error" style="text-align: right;border-bottom: 2px solid black;font-size: 6pt;font-weight: bold">'.number_format($sumCr,2).'</td>';
                $table .= '<td class="error" style="text-align: right;border-bottom: 2px solid black;font-size: 6pt;font-weight: bold">'.number_format($balance,2).'</td>';
                $table .= '</tr>';
            }else{
                $table .= '<tr >';
                $table .= '<td colspan="7"></td>';
                $table .= '<td class="error" style="padding: 6px;text-align: right;border-bottom: 2px solid black;font-size: 9pt;font-weight: bold">'.number_format($sumDr,2).'</td>';
                $table .= '<td class="error" style="text-align: right;border-bottom: 2px solid black;font-size: 9pt;font-weight: bold">'.number_format($sumCr,2).'</td>';
                $table .= '<td class="error" style="text-align: right;border-bottom: 2px solid black;font-size: 9pt;font-weight: bold">'.number_format($balance,2).'</td>';
                $table .= '</tr>';
            }

        }

        return $table;
    }

    /**Create a Function to Perform Aging of Client Balances**/
    public function getClientAgingBalance($id,$view=null):string{
        $client = Client::where('c_id', $id)->first();
        /**Do a Table to show the Aging of Balances**/
        $table = '';
        if($client != null){
            if($view == 'pdf'){
                $table = '<table style="width: 100%; border-collapse: collapse; margin-top: 3%; font-size: 6pt">';
            }else{
                $table = '<table style="width: 100%; border-collapse: collapse; margin-top: 3%; font-size: 6pt">';
            }

            /**Heading Row**/
            $table .= '<tr style="border: 2px solid black">';
            $table .= '<th style="padding: 6px; width: 16% ;text-align: center;border-right: 2px solid black">Current Total Balance</th>';
            $table .= '<th style="width: 14%;text-align: center;border-right: 2px solid black">< 30 Days</th>';
            $table .= '<th style="width: 14%;text-align: center;border-right: 2px solid black">30 to 60 Days</th>';
            $table .= '<th style="width: 14%;text-align: center;border-right: 2px solid black">61 to 90 Days</th>';
            $table .= '<th style="width: 14%;text-align: center;border-right: 2px solid black">91 to 180 Days</th>';
            $table .= '<th style="width: 14%;text-align: center;border-right: 2px solid black">181 to 365 Days</th>';
            $table .= '<th style="width: 14%;text-align: center">>365 Days</th>';
            $table .='</tr>';
            /**Data Row**/
            //Current Balance of the Client is the Sum of all entries in the Bill Master Section
            $currentBalance = $lessThanThirty = $thirtyAndSixty = $sixtyAndNinety =$ninetyAndOneEighty = $oneEightyAndThreeSixtyFive = $moreThanThreeSixtyFive =0;
            if($client->statement != null){
                $currentBalance = $client->statement->sum('amount');
                /**Balance where Date is less than 30 Days**/
                $thirtyDaysAgo = \Carbon\Carbon::now()->subMonth()->format('Y-m-d');
                $lessThanThirty = BillMasterClient::where('c_id', $id)->whereBetween('date', [$thirtyDaysAgo, now()])->sum('amount');
                /**Balance where Date is Between 30 and 60 Days**/
                $sixtyDaysAgo = \Carbon\Carbon::now()->subMonths(2)->format('Y-m-d');
                $thirtyAndSixty = BillMasterClient::where('c_id', $id)->whereBetween('date', [$sixtyDaysAgo, $thirtyDaysAgo])->sum('amount');
                /**Balance where Date is Between 61 and 90 Days**/
                $ninetyDaysAgo = \Carbon\Carbon::now()->subMonths(3)->format('Y-m-d');
                $sixtyAndNinety = BillMasterClient::where('c_id', $id)->whereBetween('date', [$ninetyDaysAgo, $sixtyDaysAgo])->sum('amount');
                /**Balance where Date is Between 91 and 180 Days**/
                $sixMothsAgo = \Carbon\Carbon::now()->subMonths(6)->format('Y-m-d');
                $ninetyAndOneEighty = BillMasterClient::where('c_id', $id)->whereBetween('date', [$sixMothsAgo, $ninetyDaysAgo])->sum('amount');
                /**Balance where Date is Between 181 and 365 Days**/
                $oneYearAgo = \Carbon\Carbon::now()->subYear()->format('Y-m-d');
                $oneEightyAndThreeSixtyFive = BillMasterClient::where('c_id', $id)->whereBetween('date', [$oneYearAgo, $sixMothsAgo])->sum('amount');
                /**Balance where Date is More than a Year Ago(365 Days)**/
                $moreThanThreeSixtyFive = BillMasterClient::where('c_id', $id)->whereDate('date', '<', $oneYearAgo)->sum('amount');
            }
            $table .= '<tr style="padding: 6px;border: 2px solid black">';
            $table .= '<td style="padding: 6px;text-align: center;border-right: 2px solid black"><b>'.number_format($currentBalance,2).'</b></td>';
            $table .= '<td style="text-align: center;border-right: 2px solid black"><b>'.number_format($lessThanThirty,2).'</b></td>';
            $table .= '<td style="text-align: center;border-right: 2px solid black"><b>'.number_format($thirtyAndSixty,2).'</b></td>';
            $table .= '<td style="text-align: center;border-right: 2px solid black"><b>'.number_format($sixtyAndNinety,2).'</b></td>';
            $table .= '<td style="text-align: center;border-right: 2px solid black"><b>'.number_format($ninetyAndOneEighty,2).'</b></td>';
            $table .= '<td style="text-align: center;border-right: 2px solid black"><b>'.number_format($oneEightyAndThreeSixtyFive,2).'</b></td>';
            $table .= '<td class="error" style="text-align: center"><b>'.number_format($moreThanThreeSixtyFive,2).'</b></td>';
            $table .='</tr>';

            $table .= '</table>';
        }

        return $table;
    }


    /**Download and Printing**/
    //1. PDF Statement
    public function pdfStatement($id,$type=null,$from=null,$to=null,$currency=null,$insurer=null ){
        $client = Client::where('c_id', $id)->first();
        if($client){
            /**Remove View Variable from Null so that it can display pdf Options**/
            $view = 'pdf';

            /**PREPARED BY SECTION: This will Check for the User Generating this Statement**/
            $userName = $userSign = "";
            if(auth()->user()){
                $userName = auth()->user()->firstName.". ".auth()->user()->lastName;
                if(file_exists(auth()->user()->sign_dir)){
                    $userSign = auth()->user()->sign_dir;
                }
            }
            /**1. LOCATION AND ADDRESS DETAILS**/
            $branch = "";
            if($client->branch != app('CompanyDetails')->id){
                $branchDetails = [];
                if(CompanyBranch::where('id', $client->branch)->first()){
                    $branchDetails = CompanyBranch::where('id', $client->branch)->first();
                    $branch = $branchDetails->name." Branch - ";
                }
            }else{
                $branch = "Head Office - ";
                $branchDetails = app('CompanyDetails');
            }
            $address = $branch;
            $address .= $branchDetails->address.", ";
            $address .= $branchDetails->box.", ";
            $address .= $branchDetails->city;

            /**2. CONTACT DETAILS**/
            $tel = $branchDetails->tel;
            $phone = $branchDetails->phone;
            $email = $branchDetails->em;
            $website = $branchDetails->website;

            /**CHECK AND ADD WATERMARK**/
            $addWaterMark = "";
            $waterMark = null;
            if($waterMark == 'AddWaterMark'){
                if(file_exists(app('CompanyDetails')->logo_dir)){
                    $addWaterMark = app('CompanyDetails')->logo_dir;
                }
            }
            /**GENERATE A QRCODE FOR YOUR DOCUMENTS**/
            $qrDetails = "Customer Name:- ".$client->nms;
            $qrDetails .= " Printed:- ".now();
            $qrCode = QrCode::size(40)->generate($qrDetails);
            $code = (string)$qrCode;

            $trademark = "<div style='margin-top: 5px'>";
            $trademark .= '<table style="width: 100%; border-collapse: collapse;margin-bottom: 10px; font-size: 10px">';
            $trademark .= '<tr>';
            $trademark .= '<td style="text-align: left">Powered By <img src="images/powered_by.jpg" style="width: 40px; height: 10px"></td>';
            $trademark .= '<td style="text-align: right">On Behalf of '.app('CompanyDetails')->comp_name.'</td>';
            $trademark .= '<tr>';
            $trademark .= '</table>';
            $trademark .= '</div>';

            /**Show Aging on Statement**/
            $showAging = 'no';
            if($insurer == 'all' && $currency == 'all' && $type != 'allocated'){
                $showAging = 'yes';
            }
            /**Statement Period**/
            if($from != null){
                $periodFrom = date('d/m/Y', strtotime($from));
            }else{
                $to = now();
                $periodFrom =  '01/01/'.\Carbon\Carbon::now()->format('Y');
            }
            if($to != null){
                $periodTo = date('d/m/Y', strtotime($to));
            }else{
                $periodTo =  date('d/m/Y', strtotime(now()));
            }
            $period = $periodFrom.'&nbsp;&nbsp; to &nbsp;&nbsp;'.$periodTo;

            /**Statement Currency**/
            $currencyName = $currencyAbbr = '';
            if($currency == null || $currency == 'all'){
                /**This means that the Statement is in Base Currency**/
                $currencyDetail = CompanyCurrency::where('type', 'base')->first();
            }else{
                $currencyDetail = CompanyCurrency::where('id', $currency)->first();
            }
            /**If Currency Exists, Get Name and Abbr**/
            if($currencyDetail){
                $currencyName = $currencyDetail->name;
                $currencyAbbr = $currencyDetail->abbr;
            }

            $data = [
                'client' => $client,
                'comp_name' => app('CompanyDetails')->comp_name,
                'comp_address' => html_entity_decode($address),
                'comp_phone' => $phone,
                'comp_tel' => $tel,
                'comp_email' => $email,
                'comp_website' => $website,
                'background_color' => app('CompanyDetails')->background_color,
                'text_color'=> app('CompanyDetails')->text_color,
                'qrCode' => $code,
                'created_by' => $userName,
                'signed_by' => $userSign,
                'type' => $type,
                'period' => $period,
                'currencyName' => $currencyName,
                'currencyAbbr' => $currencyAbbr,
                'showAging' => $showAging,
                'result' => $this->getClientStatement($id,$type ?? 'un-allocated', $currency,$from, $to, $insurer,$view),
                'aging' => $this->getClientAgingBalance($id,$view)
            ];

            /**PDF DATA LOADING**/
            $pdf = PDF::loadView('pdfs.client-statement-pdf', $data, [],
                [
                    'title' => 'STATEMENT OF ACCOUNT',
                    'watermark_image_path' => $addWaterMark,
                    'show_watermark_image' => true,
                    'watermark_text_alpha'       => 0.2,
                    'set_footer'=> $trademark,
                    'margin_bottom'              => 10,
                    'margin_left'              => 5,
                    'margin_right'              => 5,
                ]
            );
            /**DOWNLOAD TITLE/NAME**/
            $docName = "STATEMENT OF ACCOUNT.".$client->nms;

            return $pdf->stream($docName.'.pdf');
        }
        return view('errors.404');

    }




    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
