<?php

namespace App\Http\Controllers;
use EF;
Use PDF;
use App\Head;
use App\Plot;
use App\User;
use App\Branch;
use App\Account;
use App\Booking;
use App\Journal;
use App\Nominee;

use App\Payment;
use App\Payroll;
use App\Contract;
use App\Transfer;
use App\Installment;
use App\MinuteSheet;
use App\Transaction;
use App\PayrollDetail;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Illuminate\Contracts\Encryption\DecryptException;

class ReportController extends Controller
{
    public function index()
    {
        $inventory   = new Plot;
        $branch      = new Branch;
        $booking     = new Booking;
        $head        = new Head;
        $installment = new Installment;
        $branch      = new Branch;
        $transaction = new Transaction;
        $user        = new User;
        $minute_sheet = new MinuteSheet;

        $condition = ['Approve'];

        return view('reports.reports',
            [
                'user_list'          => $user->getUserListByType(['Employee']),
                'minute_sheet_list' => $minute_sheet->getMinuteSheetList(),
                'block_list'         => $inventory->getPlotListByColumn('block_name'),
                'branch'             => $branch->getBranchList(),
                'branch_labels'      => EF::branchWhiteLabel(),
                'plot_labels'        => EF::plotWhiteLabel(),
                'category_list'      => $inventory->getPlotListByColumn('category'),
                'dimension_list'     => $inventory->getPlotListByColumn('dimensions'),
                'type_list'          => $inventory->getPlotListByColumn('type'),

                'size_list'          => $inventory->getPlotListByColumn('size'),
                'status_list'        => $inventory->getPlotListByColumn('status'),
                'branch_list'        => $branch->getBranchList(),
                'booking_list'       => $booking->getAllBookings($condition),
                'head_list'          => $head->getAllHeads(),
                'installment_type'   => $installment->getInstallmentsByColoumn('type_of_installment'),
                'account_status_list'  => $transaction->getTransactionByColumn('status'),

            ]
        );

    }

    public function employeeProfile($id)
    {
        try
        {
            // CRYPT
            $id = decrypt($id);
            // END
            $user = new User;

            $user   = $user->getUserById($id);

            if(isset($user->id))
            {
                $contract = new Contract;



                parent::setLogMessage($user->name.' profile has been viewed');

                parent::getLogMessage();

                $pdf = PDF::loadView('reports.employee_profile',[

                    'user'          => $user,
                    'active_contract' => $contract->getContractByUser($user->id),


                ]);

                return $pdf->setPaper('a4', 'portrait')->stream('Employee Profile.pdf');
            }


        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');


        return redirect()->back();

    }

    public function showAllReceipt($id)
    {
            // CRYPT
            $id = decrypt($id);
            // END


            $booking = new Booking;

            $curr_booking   = $booking->getBookingById($id);

            if(isset($curr_booking->id))
            {

                $payment = new Payment;

                $installment_receipt = $payment->getInstallmentPaymentList($id,EF::getGenericTableIndex()['Installment']);

                 $commission_receipt = $payment->getCommissionPaymentList($id,EF::getGenericTableIndex()['Commission']);

                 $receipt_list = $installment_receipt->merge($commission_receipt);


                 parent::setLogMessage('All receipt document has been viewed');
                 parent::getLogMessage();

                $pdf = PDF::loadView('documents.all_receipts',[

                    'booking'       => $curr_booking,
                    'user'          => $curr_booking->user,
                    'plot'          => $curr_booking->plot,
                    'receipt_list'  => $receipt_list,

                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('All Receipts.pdf');


            }
    }

    public function bookingForm($id)
    {

    	try
    	{
    	    // CRYPT
    		$id = decrypt($id);
    		// END

    		// VARIABLE DECLARATION
    		$booking = new Booking;
            $nominee = new Nominee;
            $first_nominee = array();
    		// END

    		$curr_booking   = $booking->getBookingById($id);

           $balance_detail = $booking->getBalanceDetail($id);



    		if(isset($curr_booking->id))
    		{

                 $nominee_list = $nominee->getBookingNok($curr_booking->id,$curr_booking->user->id,["Nominee"]);

                if(@count($nominee_list) > 0)
                {
	    		   $first_nominee = $nominee_list[0];
                }

                 parent::setLogMessage('Booking Form has been viewed');
                 parent::getLogMessage();

                $pdf = PDF::loadView('documents.booking_form',[

                    'booking'       => $curr_booking,
                    'user'          => $curr_booking->user,
                    'plot'          => $curr_booking->plot,
                    'nominee'       => $first_nominee,
                    'balancedetail' => $balance_detail,

                ]);

        		return $pdf->setPaper('legal', 'portrait')->stream('Booking Form.pdf');


    		}



    	}
    	catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');


       return redirect()->back();
    }

        public function allotmentForm($id)
    {

        try
        {
            // CRYPT
            $id = decrypt($id);
            // END

            // VARIABLE DECLARATION
            $booking = new Booking;
            $nominee = new Nominee;
            $payment = new Payment;
            $first_nominee = array();
            // END

            $curr_booking   = $booking->getBookingById($id);

           $balance_detail = $booking->getBalanceDetail($id);






            if(isset($curr_booking->id))
            {

                $installment = new Installment;

                $payment_installments = $installment->getInstallmentByType($curr_booking->id,['Down Payment']);


                $installments_id = [];

                foreach($payment_installments as $rows)
                {
                    array_push($installments_id, $rows->id);
                }

               $installment_receipt = $payment->getInstallmentPaymentList($curr_booking->id,EF::getGenericTableIndex()['Installment']);

                 $commission_receipt = $payment->getCommissionPaymentList($curr_booking->id,EF::getGenericTableIndex()['Commission']);

                 $receipt_list = $installment_receipt->merge($commission_receipt);


                 $nominee_list = $nominee->getBookingNok($curr_booking->id,$curr_booking->user->id,["Nominee"]);

                 $co_owner = $nominee->getBookingNok($curr_booking->id,$curr_booking->user->id,["Co-Owner"]);

                 if(@count($co_owner) > 0){
                    $co_owner = $co_owner->first()->user;
                 }
                 else{
                    $co_owner = '';
                 }

                 

                if(@count($nominee_list) > 0)
                {
                   $first_nominee = $nominee_list[0];
                }

                $balance_detail  = $booking->getBalanceDetail($curr_booking->id);
                 $booking_installments = $installment->getBookingInstallments($curr_booking->id);



                 $installment_count = @count($installment->getBookingInstallmentByType($curr_booking->id,'Installment'));

                 if($curr_booking->plan_type ==  'One Time')
                 {
                    $payment_term = 'One Time Payment';
                 }
                 else
                 {
                    if($installment_count > 0)
                    {
                        $payment_term = $installment_count.' '.$curr_booking->installment_mode.' Installments';
                    }
                    else
                    {
                        $payment_term = ' Monthly Installments';
                    }
                 }



                $pdf = PDF::loadView('documents.confirmation_of_allotment',[

                    'booking'          => $curr_booking,
                    'user'             => $curr_booking->user,
                    'plot'             => $curr_booking->plot,
                    'nominee'          => $first_nominee,
                    'balancedetail'    => $balance_detail,
                    'payment_receipts' => $receipt_list,
                    'print_date'       => date('Y-m-d'),
                    'co_owner'         => $co_owner,
                    'installment'        => $booking_installments,
                    'installment_list'  => $installments_id,

                    'installment_balance'=> $installment->sumInstallmentByBooking($curr_booking->id),
                    'payment_term'   =>  $payment_term,

                ]);

                return $pdf->setPaper('legal', 'portrait')->stream('Booking Form.pdf');
            }



        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');


       return redirect()->back();
    }


    public function paymentForm($id)
    {

        try
        {
            // CRYPT
            $id = decrypt($id);
            // END

            // VARIABLE DECLARATION
            $booking         = new Booking;

            $installment     = new Installment;
            // END

            $curr_booking       = $booking->getBookingById($id);



            if(isset($curr_booking->id))
            {
                 $balance_detail  = $booking->getBalanceDetail($curr_booking->id);
                 $booking_installments = $installment->getBookingInstallments($curr_booking->id);
                 $payment = new Payment;

                 $installment_receipt = $payment->getInstallmentPaymentList($id,EF::getGenericTableIndex()['Installment']);

                 $commission_receipt = $payment->getCommissionPaymentList($id,EF::getGenericTableIndex()['Commission']);

                 $receipt_list = $installment_receipt->merge($commission_receipt);





                $pdf = PDF::loadView('documents.payment_plan',[

                    'booking'            => $curr_booking,
                    'user'               => $curr_booking->user,
                    'plot'               => $curr_booking->plot,
                    'balance_detail'     => $balance_detail,
                    'installment'        => $booking_installments,

                    'installment_balance'=> $installment->sumInstallmentByBooking($curr_booking->id),
                    'receipt_list' => $receipt_list,

                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Payment Plan.pdf');
            }



        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');


       return redirect()->back();
    }

    public function nokDetail($id)
    {

        try
        {
            // CRYPT
            $id = decrypt($id);
            // END

            // VARIABLE DECLARATION
            $booking         = new Booking;
            $nominee         = new Nominee;

            // END

            $curr_booking       = $booking->getBookingById($id);


            if(isset($curr_booking->id))
            {
                 $balance_detail  = $booking->getBalanceDetail($curr_booking->id);
                 $nok_list = $nominee->getBookingNok($curr_booking->id,$curr_booking->user->id,["Co-Owner"]);

                $pdf = PDF::loadView('documents.nok_detail',[

                    'booking'            => $curr_booking,
                    'user'               => $curr_booking->user,
                    'plot'               => $curr_booking->plot,
                    'balance_detail'     => $balance_detail,
                    'nok_list'           => $nok_list

                ]);

                return $pdf->setPaper('a4', 'portrait')->stream('Nok Detail.pdf');
            }



        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');


       return redirect()->back();
    }

    public function nomineeDetail($id)
    {

        try
        {
            // CRYPT
            $id = decrypt($id);
            // END

            // VARIABLE DECLARATION
            $booking         = new Booking;
            $nominee         = new Nominee;

            // END

            $curr_booking       = $booking->getBookingById($id);


            if(isset($curr_booking->id))
            {
                 $balance_detail  = $booking->getBalanceDetail($curr_booking->id);
                    $nominee_list = $nominee->getBookingNok($curr_booking->id,$curr_booking->user->id,["Nominee"]);
                $pdf = PDF::loadView('documents.nominee_detail',[

                    'booking'            => $curr_booking,
                    'user'               => $curr_booking->user,
                    'plot'               => $curr_booking->plot,
                    'balance_detail'     => $balance_detail,
                    'nominee_list'       => $nominee_list

                ]);

                return $pdf->setPaper('a4', 'portrait')->stream('Nominee Detail.pdf');
            }



        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');


       return redirect()->back();
    }

    public function customerSummary($id)
    {

        try
        {
            // CRYPT
            $id = decrypt($id);
            // END

            // VARIABLE DECLARATION
            $booking         = new Booking;

            $installment     = new Installment;
            $payment         = new Payment;
            // END

            $curr_booking       = $booking->getBookingById($id);



            if(isset($curr_booking->id))
            {
                 $balance_detail  = $booking->getBalanceDetail($curr_booking->id);
                 $booking_installments = $installment->getBookingInstallments($curr_booking->id);
                 $payments             = $payment->getInstallmentPaymentList($curr_booking->id,EF::getGenericTableIndex()['Installment']);



                $pdf = PDF::loadView('documents.customer_summary',[

                    'booking'            => $curr_booking,
                    'user'               => $curr_booking->user,
                    'plot'               => $curr_booking->plot,
                    'balance_detail'     => $balance_detail,
                    'installment'        => $booking_installments,
                    'payment'            => $payments,

                ]);

                return $pdf->setPaper('a4', 'portrait')->stream('Customer Summary.pdf');
            }



        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');


       return redirect()->back();
    }

     public function cancelBooking($id)
    {

        try
        {
            // CRYPT
            $id = decrypt($id);
            // END

            // VARIABLE DECLARATION
            $booking         = new Booking;

            $installment     = new Installment;
            $payment         = new Payment;
            // END

            $curr_booking       = $booking->getBookingById($id);



            if(isset($curr_booking->id))
            {
                 $balance_detail  = $booking->getBalanceDetail($curr_booking->id);
                 $booking_installments = $installment->getBookingInstallments($curr_booking->id);
                  $payments             = $payment->getInstallmentPaymentList($curr_booking->id,EF::getGenericTableIndex()['Installment']);


                $pdf = PDF::loadView('documents.cancel_bookingform',[

                    'booking'            => $curr_booking,
                    'user'               => $curr_booking->user,
                    'plot'               => $curr_booking->plot,
                    'balance_detail'     => $balance_detail,
                    'installment'        => $booking_installments,
                    'payment'            => $payments,

                ]);

                return $pdf->setPaper('a4', 'portrait')->stream('Cancellation Form.pdf');
            }



        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');


       return redirect()->back();
    }
    public function transferHistory($id)
    {

        try
        {
            // CRYPT
            $id = decrypt($id);
            // END

            // VARIABLE DECLARATION
            $booking             = new Booking;
            $transfer            = new Transfer;
            // END


            $curr_booking       = $booking->getBookingById($id);



            if(isset($curr_booking->id))
            {
                 $balance_detail          = $booking->getBalanceDetail($curr_booking->id);
                 $bookingtransfers        =  $transfer->getTransferByBookingId($curr_booking->id);



                $pdf = PDF::loadView('documents.transfer_history',[

                    'booking'            => $curr_booking,
                    'user'               => $curr_booking->user,
                    'plot'               => $curr_booking->plot,
                    'balance_detail'     => $balance_detail,
                    'transfer'           => $bookingtransfers

                ]);

                return $pdf->setPaper('a4', 'portrait')->stream('Transfer History.pdf');
            }



        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');


       return redirect()->back();
    }
    public function transferBooking($id)
    {

        try
        {
            // CRYPT
            $id = decrypt($id);
            // END

            // VARIABLE DECLARATION
            $transfer         = new Transfer;
            $booking          = new Booking;

            $installment     = new Installment;
            $payment         = new Payment;
            // END

            $curr_transfer       = $transfer->getTransferById($id);




            if(isset($curr_transfer->id))
            {

                $curr_booking     = $booking->getBookingById($curr_transfer->booking_id);
                if(isset($curr_booking->id))
                {
                     $balance_detail  = $booking->getBalanceDetail($curr_booking->id);
                      $owner            = $curr_transfer->getowner;



                $pdf = PDF::loadView('documents.transfer_bookingform',[

                    'booking'          => $curr_booking,
                    'transfer'         => $curr_transfer,
                    'user'             => $curr_booking->user,
                    'plot'             => $curr_booking->plot,
                    'owner'            => $owner,
                    'balance_detail'   => $balance_detail,
                    'payment'          => $payment->getPaymentHistory($curr_booking->id,$owner->id,EF::getGenericTableIndex()['Installment'])
                ]);

                return $pdf->setPaper('a4', 'portrait')->stream('Transfer Booking.pdf');
                }


            }



        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');


       return redirect()->back();
    }
    public function paymentReceipt($id)
    {
         try
        {
            // CRYPT
            $id = decrypt($id);
            // END

            // VARIABLE DECLARATION
            $booking             = new Booking;
            $payment             = new Payment;
            // END

           $curr_payment  = $payment->getPaymentByIdWithRecycle($id);

           if(isset($curr_payment->id))
            {

                $data = [

                    'payment' => $curr_payment,
                    'plot' => $curr_payment->booking->plot,
                    'user' => $curr_payment->user,
                    'watermark' =>  $curr_payment

                ];


                $pdf = PDF::loadView('documents.payment_receipt',$data);

                return $pdf->setPaper('a4', 'landscape')->stream('Payment Receipt.pdf');
            }



        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');


       return redirect()->back();

    }

    public function voucherPreview($id)
    {

         $compound_list = EF::getVoucherType();

         try
        {
            // CRYPT
            $id = decrypt($id);


            // END

            // VARIABLE DECLARATION
            $transaction  = new Transaction;
            $journal      = new Journal;
            // END

           $curr_transaction  = $transaction->getTransactionById($id);

           if(isset($curr_transaction->id))

            {


                if($curr_transaction->compound_type == $compound_list[0])
                {
                     $curr_journals = $journal->getJorunalByTransactionId($curr_transaction->id);


                }
                 elseif($curr_transaction->compound_type == $compound_list[1])
                {
                     $curr_journals = $journal->getJorunalByTransactionId($curr_transaction->id,'credit');

                }
                elseif($curr_transaction->compound_type == $compound_list[2])
                {
                     $curr_journals = $journal->getJorunalByTransactionId($curr_transaction->id,'credit');
                }
                else{

                }
                if(count($curr_journals) > 0)
                {
                    $pdf = PDF::loadView('documents.voucher_preview',[

                                    'transaction' => $curr_transaction,
                                    'journals'    => $curr_journals,
                                    'bank_detail'  => $transaction->getChequeNumber($curr_transaction->id),

                                     ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Voucher Preview.pdf');
                }

            }



        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');

       return redirect()->back();

    }

     public function voucherRejectPreview($id)
    {

         $compound_list = EF::getVoucherType();

         try
        {
            // CRYPT
            $id = decrypt($id);


            // END

            // VARIABLE DECLARATION
            $transaction  = new Transaction;
            $journal      = new Journal;
            // END

           $curr_transaction  = $transaction->getRejectedTransactionById($id);

           if(isset($curr_transaction->id))

            {


                if($curr_transaction->compound_type == $compound_list[0])
                {
                     $curr_journals = $journal->getRejectedJorunalByTransactionId($curr_transaction->id);


                }
                 elseif($curr_transaction->compound_type == $compound_list[1])
                {
                     $curr_journals = $journal->getRejectedJorunalByTransactionId($curr_transaction->id,'credit');

                }
                elseif($curr_transaction->compound_type == $compound_list[2])
                {
                     $curr_journals = $journal->getRejectedJorunalByTransactionId($curr_transaction->id,'credit');
                }
                else{

                }
                if(count($curr_journals) > 0)
                {
                    $pdf = PDF::loadView('documents.voucher_preview',[

                                    'transaction' => $curr_transaction,
                                    'journals'    => $curr_journals,
                                    'bank_detail'  => $transaction->getChequeNumber($curr_transaction->id),

                                     ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Voucher Preview.pdf');
                }

            }



        }
        catch (DecryptException $e)
        {

        }

        parent::errorMessage('No such record found.');

       return redirect()->back();

    }
    public function bookingReport(Request $request)
    {
        try
        {

            $branch_labels = EF::branchWhiteLabel();

            $form_collect = $request->input();

            $from      = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to        = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            // CRYPT
            $plot_condition['category']    = decrypt($form_collect['category']);

            // $plot_condition['block_name']  = decrypt($form_collect['block']);

            $plot_condition['size']        = decrypt($form_collect['size']);

            $plot_condition['type']        = decrypt($form_collect['type']);

            $booking_condition['branch_id']   = decrypt($form_collect[$branch_labels['module']]);

            $format    = ($form_collect['format']);

            $booking_condition['bookings.status'] = 'Approve';

            $branch = new Branch;




            $plot_condition    = parent::filterConditionalArray($plot_condition);

            $booking_condition = parent::filterConditionalArray($booking_condition);


            $booking = new Booking;

            $booking_list = $booking->bookingWiseReport($from,$to,$plot_condition[0],$booking_condition[0]);

            $date_fromat = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');

            $curr_branch = $branch->getBranchById(decrypt($form_collect[$branch_labels['module']]));

            if(isset($curr_branch->id))
            {
                $branch_name = $curr_branch->name;
            }
            else
            {
                $branch_name = '';

            }

            $title = $plot_condition[1].' '.' '.$branch_name.' '.$date_fromat;



            if(!$format)
            {
                $pdf = PDF::loadView('reports.booking_report',[

                     'booking_list'  => $booking_list,
                     'format'        => true,
                     'title'         => $title,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Booking Report.pdf');
            }
            else
            {
                $excel = view('reports.booking_report',[

                     'booking_list'  => $booking_list,
                     'title'         => $title,
                     'format'        => false,

                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Booking Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();


        }

    }

    public function incomeReport(Request $request)
    {
        try
        {
            $title = "";
            $booking = new Booking;

            $user    = new User;

            $role = new Role;

            $form_collect  = $request->input();

            $from          = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to            = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            // CRYPT
            $booking_id       = decrypt($form_collect['booking']);

            $user_id          = decrypt($form_collect['user']);

            $role_id          = decrypt($form_collect['user_type']);

            $generic_type     = EF::getGenericTableIndex()['Installment'];


            $branch           = decrypt($form_collect[EF::branchWhiteLabel()['module']]);


            $payment_condition = ['generic_type_id' => $generic_type];
            $booking_condition = [];

            $plot_condition = [];

            $curr_booking       = $booking->getBookingById($booking_id);

            if(isset($curr_booking->id))
            {
                $booking_condition += ['booking_id' => $curr_booking->id];

                $title .= $curr_booking->plot->plot_id.' '. $curr_booking->plot->type.' ';
            }

            $curr_branch = new Branch;

            $curr_branch = $curr_branch->getBranchById($branch);

            if(isset($curr_branch->id))
            {
                $payment_condition += ['branch_id' => $curr_branch->id];
                $title.= ' '.$curr_branch->name.' ';

            }

            $curr_user          = $user->getUserById($user_id);

            if(isset($curr_user->id))
            {
                $payment_condition += ['user_id' => $curr_user->id];

                $title .= $curr_user->name.' ';
            }

            $payment_condition += ['role_id' => $role_id];

            $payment_condition  = parent::filterConditionalArray($payment_condition);
            $booking_condition  = parent::filterConditionalArray($booking_condition);


            $format        = ($form_collect['format']);


            $payment = new Payment;

            $booking_payments = $payment->incomeWiseReport($from,$to,$payment_condition[0],$booking_condition[0]);

            $date_format = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');


            $title.= $date_format;


            if(!$format)
            {
                $pdf = PDF::loadView('reports.income_report',[

                     'booking_payments'  => $booking_payments,
                     'format'        => true,
                     'title'         => $title,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Income Report.pdf');
            }
            else
            {
                $excel = view('reports.income_report',[

                     'booking_payments'  => $booking_payments,
                     'title'         => $title,
                     'format'        => false,

                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Income Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();

        }

    }

     public function collectionReport(Request $request)
    {
        try
        {
            $title = "";
            $booking = new Booking;

            $user    = new User;

            $form_collect  = $request->input();

            $from          = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to            = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            // CRYPT
            $booking_id       = decrypt($form_collect['booking']);

            $user_id          = decrypt($form_collect['user']);

            $generic_type     = EF::getGenericTableIndex()['Installment'];


            $branch           = decrypt($form_collect[EF::branchWhiteLabel()['module']]);


            $payment_condition = ['generic_type_id' => $generic_type];
            $booking_condition = [];

            $plot_condition = [];

            $curr_booking       = $booking->getBookingById($booking_id);

            if(isset($curr_booking->id))
            {
                $booking_condition += ['booking_id' => $curr_booking->id];

                $title .= EF::showPlotFormat($curr_booking->plot);
            }

            $curr_branch = new Branch;

            $curr_branch = $curr_branch->getBranchById($branch);

            if(isset($curr_branch->id))
            {
                $payment_condition += ['branch_id' => $curr_branch->id];
                $title.= ' '.$curr_branch->name.' ';

            }

            $curr_user          = $user->getUserById($user_id);

            if(isset($curr_user->id))
            {
                $payment_condition += ['user_id' => $curr_user->id];

                $title .= $curr_user->name.' ';
            }


            $payment_condition  = parent::filterConditionalArray($payment_condition);
            $booking_condition  = parent::filterConditionalArray($booking_condition);


            $format        = ($form_collect['format']);


            $payment = new Payment;

            $payment_list = $payment->getCollectionReport($from,$to,$payment_condition[0],$booking_condition[0]);

            $date_format = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');





            $title.= $date_format;


            if(!$format)
            {
                $pdf = PDF::loadView('reports.collection_report',[

                     'payment_list'  => $payment_list,
                     'format'        => true,
                     'title'         => $title,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Income Report.pdf');
            }
            else
            {
                $excel = view('reports.income_report',[

                     'booking_payments'  => $booking_payments,
                     'title'         => $title,
                     'format'        => false,

                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Income Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();

        }

    }

    public function expenseReport(Request $request)
    {
        try
        {
            $booking = new Booking;

            $user    = new User;

            $form_collect  = $request->input();

            $from          = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to            = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            // CRYPT
            $booking_id       = decrypt($form_collect['booking']);

            $user_id          = decrypt($form_collect['user']);

            $payment_condition = [];
             $plot_condition = [];

            $curr_booking       = $booking->getBookingById($booking_id);
            if(isset($curr_booking->id))
            {
                $payment_condition += ['booking_id' => $curr_booking->id];
            }



            $curr_user          = $user->getUserById($user_id);

             if(isset($curr_user->id))
            {
                $payment_condition += ['user_id' => $curr_user->id];
            }



            $payment_condition  = parent::filterConditionalArray($payment_condition);



            $format        = ($form_collect['format']);


            $payment = new Payment;

            $booking_payments = $payment->expenseWiseReport($from,$to,$payment_condition[0]);

            $date_format = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');

            if(isset($curr_booking->id))
            {
                $title = $curr_booking->plot->plot_id.' '. $curr_booking->plot->block_name.''. $date_format;
            }
            else
            {
                $title = $date_format;
            }

            if(!$format)
            {
                $pdf = PDF::loadView('reports.expense_report',[

                     'booking_payments'  => $booking_payments,
                     'format'        => true,
                     'title'         => $title,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Expense Report.pdf');
            }
            else
            {
                $excel = view('reports.expense_report',[

                     'booking_payments'  => $booking_payments,
                     'title'         => $title,
                     'format'        => false,

                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Expense Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();


        }

    }


    public function accountReport(Request $request)
    {
        try
        {
            $booking    = new Booking;
            $account    = new Account;
            $branch     = new Branch;
            $head       = new Head;
            $user       = new User;

            $form_collect  = $request->input();

            $from          = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to            = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            // CRYPT
            $booking_id       = decrypt($form_collect['booking']);

            $user_id          = decrypt($form_collect['user']);

            $subhead_id       = decrypt($form_collect['subhead']);

            $head_id          = decrypt($form_collect['head']);

            $status           = decrypt($form_collect['status']);

            $nature           = decrypt($form_collect['nature']);

            $role_id          = decrypt($form_collect['user_type']);

            $mode             = $form_collect['mode'];


            $curr_branch      = decrypt($form_collect[EF::branchWhiteLabel()['module']]);

            $curr_booking       = $booking->getBookingById($booking_id);

            $curr_account       = $account->getAccountById($subhead_id);

            $curr_user          = $user->getUserById($user_id);

            $account_condition = [];

            $view_condition = [];


            $account_condition = ['booking_id' => $booking_id , 'user_id' => $user_id , 'account_id'=> $subhead_id,'branch_id' => $curr_branch, 'mode' => $mode ,'role_id'=> $role_id];

            $transaction_condition = ['status' => $status];

            $head_condition = ['heads.id' => $head_id];

            $account_condition  = parent::filterConditionalArray($account_condition);

            $transaction_condition  = parent::filterConditionalArray($transaction_condition);

            $head_condition  = parent::filterConditionalArray($head_condition);

            $format             = ($form_collect['format']);

            if($nature != "0")
            {
                $nature_list = [$nature];

                $view_condition['heads.nature'] = $nature;
            }
            else
            {
                $nature_list = EF::getNatureList();

            }

            if($subhead_id != "0")
            {
                $view_condition['journals.account_id'] = $subhead_id;
            }

            $title= '';

            if($mode != "0")
            {
                $view_condition['journals.mode'] = $mode;

                $title  .= $mode.', ';
            }

            $journal = new Journal;

            $ledger = $journal->accountWiseReport($from,$to,$account_condition[0],$transaction_condition[0],$nature_list);

            $date_format = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');


            // SET TITLE INFORMATION


            $curr_head = $head->getHeadById($head_id);

            if(isset($curr_head->id))
            {
                $title .= $curr_head->name.', ';
            }

            if(isset($curr_account->id))
            {
               $title .= $curr_account->name.', ';
            }

            if($nature != "0")
            {
                $title .=$nature.', ';
            }

            if(isset($curr_booking->id))
            {
                $title .= $curr_booking->plot->plot_id.' '. $curr_booking->plot->type.', ';
            }



            if(isset($curr_branch->id))
            {
                $title .= ' '.$curr_branch->name.', ';
            }

            if(isset($curr_user->id))
            {
               $title .= $curr_user->name.", ";
            }


            $title .= $date_format;

            $title  = rtrim($title,', ');

            // $excel = view('reports.account_report',[

            //      'ledger'            => $ledger,
            //      'title'             => $title,
            //      'format'            => false,
            //      'subhead'           => $subhead_id,
            //      'nature'            => $nature,
            //      'view_condition'    => $view_condition,
            // ]);

            // header("Content-Type: application/xls");

            // header("Content-Disposition: attachment; filename=Account Report.xls");

            // echo $excel;

            if(!$format)
            {
                $pdf = PDF::loadView('reports.account_report',[

                     'ledger'        => $ledger,
                     'format'        => true,
                     'title'         => $title,
                     'subhead'       => $subhead_id,
                     'nature'        => $nature,
                     'view_condition' => $view_condition,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Account Report.pdf');
            }
            else
            {
                $excel = view('reports.account_report',[

                     'ledger'            => $ledger,
                     'title'             => $title,
                     'format'            => false,
                     'subhead'       => $subhead_id,
                     'nature'        => $nature,
                     'view_condition' => $view_condition,


                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Account Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();

        }

    }

    public function trialReport(Request $request)
    {
        try
        {
            $branch_labels = EF::branchWhiteLabel();

            $journal    = new Journal;
            $branch     = new Branch;

            $form_collect  = $request->input();



            $from          = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to            = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            $branch_id       = decrypt($form_collect[$branch_labels['module']]);
            $trial_condition = [];


            $curr_branch       = $branch->getBranchById($branch_id);


            if(isset($curr_branch->id))
            {
                 $trial_condition = ['journals.branch_id' => $branch_id ];
            }
            $trial_condition  = parent::filterConditionalArray($trial_condition);

            $format             = ($form_collect['format']);

            $account_list = $journal->trialWiseReport($from,$to,$trial_condition[0]);



            $date_format = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');

            $title = '';

            if(isset($curr_branch->id))
            {
               $title .= $curr_branch->name ;
            }

                $title .= $date_format;

            if(!$format)
            {
                $pdf = PDF::loadView('reports.trial_report',[


                     'format'        => true,
                     'title'         => $title,
                     'account_list'  => $account_list,
                     'from'          => $from,
                     'journal'       => $journal,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Account Report.pdf');
            }
            else
            {
                $excel = view('reports.trial_report',[

                     'title'             => $title,
                     'format'            => false,
                     'account_list'      => $account_list,
                       'from'            => $from,
                       'journal'       => $journal,

                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Trial Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();

        }

    }

    public function ledgerReport(Request $request)
    {
        try
        {

            $form_collect  = $request->input();



            $from          = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to            = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            // CRYPT
            $account_id         = decrypt($form_collect['account_id']);

            $format             = ($form_collect['format']);


            $journal = new Journal;

            $ledger = $journal->ledgerWiseReport($from,$to,$account_id);

            $opening_balance = $journal->getOpeningBalance($from,$account_id);


            $date_format = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');

            $title = $date_format;

            $account_controller = new AccountController;

            if(!$format)
            {
                $pdf = PDF::loadView('reports.ledger_report',[

                     'ledger'          => $account_controller->filterAccounts($ledger),
                     'opening_balance' => $opening_balance,
                     'format'          => true,
                     'title'           => $title,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Ledger Report.pdf');
            }
            else
            {
                $excel = view('reports.ledger_report',[

                     'ledger'            => $ledger,
                     'opening_balance'   => $opening_balance,
                     'title'             => $title,
                     'format'            => false,

                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Ledger Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();

        }

    }

    public function inventoryReport(Request $request)
    {
        try
        {
            $form_collect = $request->input();
            // CRYPT
            $plot_condition['category']    = decrypt($form_collect['category']);

            $plot_condition['type']  = decrypt($form_collect['type']);

            $plot_condition['size']        = decrypt($form_collect['size']);

            $plot_condition['branch_id']   = decrypt($form_collect[EF::branchWhiteLabel()['module']]);

            $plot_condition['status']   = decrypt($form_collect['status']);

            $format = $form_collect['format'];

            $branch = new Branch;

            $curr_branch  = $branch->getBranchById($plot_condition['branch_id']);

            $title = "";

            if(isset($curr_branch->id))
            {
                $title .= $curr_branch->name.', ';
            }

            if($plot_condition['category'] != "0")
            {
                $title .= $plot_condition['category'].', ';
            }

            if($plot_condition['size'] != "0")
            {
                $title .= $plot_condition['size'].', ';
            }

            if($plot_condition['type'] != "0")
            {
                $title .= $plot_condition['type'].', ';
            }

            if($plot_condition['status'] != "0")
            {
                $title .= $plot_condition['status'].', ';
            }

            $plot_condition    = parent::filterConditionalArray($plot_condition);

            $inventory = new Plot;

            $inventory_list = $inventory->inventoryReport($plot_condition[0]);


            $title = rtrim($title,', ');
            // $title = $plot_condition[1];

            if(!$format)
            {
                $pdf = PDF::loadView('reports.inventory_report',[

                    'inventory_list'  => $inventory_list,
                    'title'           => $title,
                     'format'         => true,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Inventory Report.pdf');
            }
            else
            {
                $excel = view('reports.inventory_report',[

                     'inventory_list'  => $inventory_list,
                     'title'         => $title,
                     'format'        => false,

                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Inventory Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();


        }
    }

    public function commissionReport(Request $request)
    {
        try
        {
            $title = "";
            $form_collect = $request->input();

            $from = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to    = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            $date_format = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');

            $form_collect = $request->input();
            // CRYPT
            $commission_condition['user_id']     = decrypt($form_collect['user']);

            $booking_id  = decrypt($form_collect['booking']);

            $commission_condition['status']      = decrypt($form_collect['status']);

            $commission_condition['branch_id']      = decrypt($form_collect[EF::branchWhiteLabel()['module']]);

            $commission_condition['role_id']     = decrypt($form_collect['user_type']);

            $generic_type     = EF::getGenericTableIndex()['Commission'];

            $commission_condition['generic_type_id'] = $generic_type;


            $booking_condition = [];

            $booking = new Booking;

            $curr_booking       = $booking->getBookingById($booking_id);

            if(isset($curr_booking->id))
            {
                $booking_condition += ['booking_id' => $curr_booking->id];
                $title .= $curr_booking->plot->plot_id.' '. $curr_booking->plot->type.' ';
            }


            $curr_branch = new Branch;

            $curr_branch = $curr_branch->getBranchById($commission_condition['branch_id']);

            if(isset($curr_branch->id))
            {
                $title.= ' '.$curr_branch->name.' ';

            }

            $curr_user = new User;

            $curr_user = $curr_user->getUserById($commission_condition['user_id']);

            if(isset($curr_user->id))
            {
                $title.= ' '.$curr_user->name.' ';

            }


            $format = $form_collect['format'];

            $commission_condition = parent::filterConditionalArray($commission_condition);
            $booking_condition    = parent::filterConditionalArray($booking_condition);


            $commission = new Payment;

            $commission_list = $commission->commissionReport($from,$to,$commission_condition[0],$booking_condition[0]);

            $title .= $date_format;

            if(!$format)
            {
                $pdf = PDF::loadView('reports.commission_report',[

                     'commission_list'  => $commission_list,
                     'format'           => true,
                     'title'            => $title,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Commission Report.pdf');
            }
            else
            {
                $excel = view('reports.commission_report',[

                     'commission_list'  => $commission_list,
                     'title'            => $title,
                     'format'           => false,

                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Commission Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();


        }
    }

    public function installmentReport(Request $request)
    {
        try
        {
            $title = "";

            $booking = new Booking;



            $form_collect = $request->input();

            $from = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to    = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            $date_format = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');

            $form_collect = $request->input();
            // CRYPT

            $installment_condition['booking_id']  = decrypt($form_collect['booking']);

            $installment_condition['installments.branch_id']  = decrypt($form_collect[EF::branchWhiteLabel()['module']]);


            $type = decrypt($form_collect['payment_type']);



            $curr_booking  = $booking->getBookingById($installment_condition['booking_id']);


            $format = $form_collect['format'];

            $installment = new Installment;

            $curr_branch = new Branch;

            $curr_branch = $curr_branch->getBranchById($installment_condition['installments.branch_id']);

            if(isset($curr_branch->id))
            {
                $title.= ' '.$curr_branch->name.' ';

            }


            if($type == "0")
            {
                $installment_condition = parent::filterConditionalArray($installment_condition);

                $title .= $date_format;

                $installment = new Installment;
                $installment_list = $installment->completeInstallmentReport($from,$to,$installment_condition[0]);



            if(!$format)
            {
                $pdf = PDF::loadView('reports.complete_installment_report',[

                     'installment_list'  => $installment_list,
                     'format'            => true,
                     'title'             => $title,
                     'from'  => $from,
                     'to' => $to,
                    'installment_type'   => $installment->getInstallmentsByColoumn('type_of_installment'),


                ]);
                return $pdf->setPaper('a4', 'landscape')->stream('Installment Report.pdf');
            }
            else
            {
                $excel = view('reports.complete_installment_report',[

                     'installment_list'  => $installment_list,
                     'title'             =>  $title,
                     'from'  => $from,
                     'to' => $to,
                     'format'            =>  false,
                    'installment_type'   => $installment->getInstallmentsByColoumn('type_of_installment'),



                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Installment Report.xls");

                echo $excel;

            }

            }
            else
            {
                      $installment_condition['type_of_installment'] = $type;

            $installment_condition = parent::filterConditionalArray($installment_condition);
             $installment_list = $installment->installmentReport($from,$to,$installment_condition[0]);




            if(isset($curr_booking->id))
            {
                $title .= $curr_booking->plot->plot_id.' '. $curr_booking->plot->block_name.''. $date_format;
            }

                $title .= $date_format;

            if(!$format)
            {
                $pdf = PDF::loadView('reports.installment_report',[

                     'installment_list'  => $installment_list,
                     'format'            => true,
                     'title'             => $title,
                     'payment_type'      => $type,
                     'from'  => $from,
                     'to' => $to,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Installment Report.pdf');
            }
            else
            {
                $excel = view('reports.installment_report',[

                     'installment_list'  => $installment_list,
                     'title'             =>  $title,
                     'format'            =>  false,
                     'payment_type'      => $type,
                     'from'  => $from,
                     'to' => $to,

                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Installment Report.xls");

                echo $excel;

            }

            }


        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();


        }
    }




    public function accountWiseIncome(Request $request)
    {
       try
        {
            $booking    = new Booking;
            $account    = new Account;
            $branch     = new Branch;
            $head       = new Head;
            $user       = new User;

            $form_collect  = $request->input();

            $from          = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to            = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            // CRYPT
            $booking_id       = decrypt($form_collect['booking']);

            // $user_id          = decrypt($form_collect['user']);

            // $subhead_id       = decrypt($form_collect['subhead']);

            // $head_id          = decrypt($form_collect['head']);

            // $status           = decrypt($form_collect['status']);

            // $nature           = decrypt($form_collect['nature']);

            $curr_branch      = decrypt($form_collect[EF::branchWhiteLabel()['module']]);

            $curr_booking       = $booking->getBookingById($booking_id);

            $curr_account       = $account->getAccountById($subhead_id);

            // $curr_user          = $user->getUserById($user_id);

            $account_condition = [];

            $view_condition = [];


            $account_condition = ['booking_id' => $booking_id, 'branch_id' => $curr_branch];

            $transaction_condition = ['status' => $status];

            $head_condition = ['heads.id' => $head_id];

            $account_condition  = parent::filterConditionalArray($account_condition);

            $transaction_condition  = parent::filterConditionalArray($transaction_condition);

            $head_condition  = parent::filterConditionalArray($head_condition);

            $format             = ($form_collect['format']);

            if($nature != "0")
            {
                $nature_list = [$nature];

                $view_condition['heads.nature'] = $nature;
            }
            else
            {
                $nature_list = EF::getNatureList();

            }

            if($subhead_id != "0")
            {
                $view_condition['journals.account_id'] = $subhead_id;
            }

            $journal = new Journal;

            $ledger = $journal->accountWiseReport($from,$to,$account_condition[0],$transaction_condition[0],$nature_list);

            $date_format = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');


            // SET TITLE INFORMATION
            $title = '';

            $curr_head = $head->getHeadById($head_id);

            if(isset($curr_head->id))
            {
                $title .= $curr_head->name.', ';
            }

            if(isset($curr_account->id))
            {
               $title .= $curr_account->name.', ';
            }

            if($nature != "0")
            {
                $title .=$nature.', ';
            }

            if(isset($curr_booking->id))
            {
                $title .= $curr_booking->plot->plot_id.' '. $curr_booking->plot->type.', ';
            }



            if(isset($curr_branch->id))
            {
                $title .= ' '.$curr_branch->name.', ';
            }

            if(isset($curr_user->id))
            {
               $title .= $curr_user->name.", ";
            }


            $title .= $date_format;

            $title  = rtrim($title,', ');

            if(!$format)
            {
                $pdf = PDF::loadView('reports.account_report',[

                     'ledger'        => $ledger,
                     'format'        => true,
                     'title'         => $title,
                     'subhead'       => $subhead_id,
                     'nature'        => $nature,
                     'view_condition' => $view_condition,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Account Report.pdf');
            }
            else
            {
                $excel = view('reports.account_report',[

                     'ledger'            => $ledger,
                     'title'             => $title,
                     'format'            => false,
                     'subhead'       => $subhead_id,
                     'nature'        => $nature,
                     'view_condition' => $view_condition,


                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Account Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();

        }
    }

    public function accountWiseExpense(Request $request)
    {
        $form_collect  = $request->input();

        $from          = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

        $to            = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));
    }

    public function profitLossReport(Request $request)
    {
        try
        {

            $journal    = new Journal;
            $branch     = new Branch;

            $form_collect  = $request->input();

            $from          = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to            = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            $format    = ($form_collect['format']);


            $profit_loss = $journal->getNatureWiseReport($from,$to);

            $account     = new AccountController;

            $profit_loss = $account->getRetainEarning($profit_loss);


            $date_format = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');

            $title = '';


            $title .= $date_format;

            if(!$format)
            {
                $pdf = PDF::loadView('reports.profitloss_report',$profit_loss + [
                     'format'        => true,
                     'title'         => $title,

                ]);

                return $pdf->setPaper('a4', 'portrait')->stream('Profit Loss Report.pdf');
            }
            else
            {
                $excel = view('reports.profitloss_report',$profit_loss + [

                   'format'        => true,
                    'title'         => $title,
                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Trial Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();

        }
    }

    public function balanceSheetReport(Request $request)
    {
        try
        {

            $journal    = new Journal;
            $branch     = new Branch;

            $form_collect  = $request->input();

            $from          = str_replace('1970-01-01','1970-01-01',date('Y-m-d',strtotime($form_collect['from_date'])));

            $to            = str_replace('1970-01-01','2099-01-01',date('Y-m-d',strtotime($form_collect['to_date'])));

            $format    = ($form_collect['format']);


            $balance_sheet = $journal->getNatureWiseReport($from,$to);

            $account     = new AccountController;

            $retain_earning = $account->getRetainEarning($balance_sheet)['net_profit'];


            $date_format = str_replace('(1970-01-01 - 2099-01-01)',' ','('.$from.' - '.$to.')');

            $title = '';


            $title .= $date_format;

            if(!$format)
            {
                $pdf = PDF::loadView('reports.balance_sheet',[

                     'format'        => true,
                     'title'         => $title,
                     'balance_sheet'   => $balance_sheet,
                     'retain_earning' => $retain_earning,
                     // 'reportObject'  => new ReportController,
                ]);

                return $pdf->setPaper('a4', 'portrait')->stream('Balance Sheet Report.pdf');
            }
            else
            {
                $excel = view('reports.balance_sheet',[

                     'format'        => true,
                     'title'         => $title,
                     'balance_sheet'   => $balance_sheet,
                     'retain_earning' => $retain_earning,

                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Trial Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();

        }
    }

    public function salarySlipReport(Request $request)
    {
        try{

            // DECLARATION PORTION
            $contract_list        = [];

            $deduction_list       = [];

            $contract_detail_list = [];

            $payroll_details = new PayrollDetail;

            $payroll = new Payroll;
            // END DECLARATION PORTION


            // FETCH DATA FROM "FORM MODEL"
            $form_collect = $request->input();


            $user_id = decrypt($form_collect['user']);

            $minute_sheet_id     = decrypt($form_collect['minute_sheet']);
            // FETCH DATA FROM "FORM MODEL"

            // FETCH DATA FROM QUERY AREA

            $payroll_detail_list = $payroll_details->getPayrollDetail($user_id,$minute_sheet_id);

            $payroll = $payroll->getPayrollByUser($user_id,$minute_sheet_id);

            if(isset($payroll->id))
            {

            $net_salary = $payroll_details->calculateNetSalary($payroll->user_id,$payroll->minute_sheet_id);

            $taxable_salary = ($net_salary['basic_salary']) + ($net_salary['allowance_sum'] - $net_salary['deduction_sum'] - $net_salary['non_taxable_allowances']);

            $final_tax_amount = $payroll_details->calculateTax($taxable_salary)['monthly_tax_amount'];





            // END FETCH DATA FROM QUERY AREA

            if(@count($payroll_detail_list) > 0 && isset($payroll->id))
            {

                foreach ($payroll_detail_list as $rows)
                {
                    if ($rows->contract_id > 0 && $rows->contract_detail_id == 0)
                    {
                        array_push($contract_list,$rows);
                    }

                    if ($rows->deduction_id > 0)
                    {
                        array_push($deduction_list, $rows);
                    }

                    if ($rows->contract_detail_id > 0)
                    {
                        array_push($contract_detail_list, $rows);
                    }
                }

                $pdf = PDF::loadView('reports.salary_slip',[
                       'user'                   => $payroll->user,
                       'minute_sheet'           => $payroll->minuteSheet,
                       'deduction_list'         => $deduction_list,
                       'contract_detail_list'   => $contract_detail_list,
                       'contract_list'          => $contract_list,
                       'payroll'                => $payroll,
                       'final_tax_amount'       => $final_tax_amount,

                ]);

                return $pdf->setPaper('legal','potrait')->stream('salarySlip.pdf');
            }

            }



            else
            {
                parent::errorMessage('Record Not Found');

                return redirect('reports');
            }
        }
        catch(DecryptException $e)
        {

        }
    }



     public function dueInstallmentReport(Request $request)
    {
        try
        {


            $title = "";

            $booking_condition = [];

            $condition = [];

            $from      =  $request->from_date;

            $to        =  $request->to_date;

            $form_collect  = $request->input();


            $booking_id      = decrypt($form_collect['booking']);

            $project_id      = decrypt($form_collect['project']);

            // dd($booking_id,  $project_id );

            if ( $project_id > 0) {
               $condition += ['branch_id' => $project_id];

            }

            // $branch           = decrypt($form_collect[EF::branchWhiteLabel()['module']]);

            $booking = new Booking;

            $curr_booking       = $booking->getBookingById($booking_id);

            if(isset($curr_booking->id))
            {
                $booking_condition += ['booking_id' => $curr_booking->id];


                $title.=' Reg No. '.$curr_booking->file_number.' Article No. '.$curr_booking->plot->plot_id.' ';

            }


            $title.= rtrim(EF::dateFormat($request->from_date).' - '.EF::dateFormat($request->to_date),'- ');

        
            $installment = new Installment;


            $installment_list = $installment->getDueInstallmentReport($from,$to,$condition ,$booking_condition)->groupBy('booking_id');


         
          
            $format    = $form_collect['format'];


            if(!$format)
            {
                $pdf = PDF::loadView('reports.due_installment_report',[

                      'installment_list'  => $installment_list,
                      'format'        => true,
                      'title'         => $title,
                ]);

                return $pdf->setPaper('a4', 'landscape')->stream('Income Report.pdf');
            }
            else
            {
                $excel = view('reports.due_installment_report',[

                    'installment_list'  => $installment_list,
                     'title'         => $title,
                     'format'        => false,

                ]);

                header("Content-Type: application/xls");

                header("Content-Disposition: attachment; filename=Due Installment Report.xls");

                echo $excel;

            }

        }

        catch (DecryptException $e)
        {
            parent::errorMessage('No such record found.');

           return redirect()->back();

        }

    }



}
