<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\VoucherRequest;
use Illuminate\Contracts\Encryption\DecryptException;
use Crypt;
use App\User;
use App\Booking;
use App\Head;
use App\Account;
use App\Installment;
use App\Branch;
use App\Commission;
use App\Payment;
use App\Transaction;
use App\Journal;
use App\GenericType;

use EF;

class VoucherController extends Controller
{
    private $generic_index;

    public function __construct()
    {
       $this->generic_index = EF::getGenericTableIndex();
    }

    public function index()
    {
        $branch = new Branch;
        $head = new Head;
        $account = new Account;

        $trasnaction = new Transaction;

        $view_voucher = view('components.voucher.table_voucher',[
            'trasnaction'   => $trasnaction->getUnpaidTransaction(),
        ]);

        return view('voucher.manage_voucher',
            [
             'head_list'      =>  $head->getAllHeads(),
             'subhead_list'        => $account->getAllSubhead(),

             // 'compund_list'   =>  $head->getAllHeads(),


             'branch'         => $branch->getBranchList(),

             'voucher_id'     => uniqid(),
             'view_voucher'  => $view_voucher
            ]);
    }


    public function rejectVoucher()
    {
        $trasnaction = new Transaction;

        return view('voucher.reject_voucher',
            [
             'trasnaction_list'   => $trasnaction->geAlltRejectedTransaction(),
            ]);
    }

    // public function showDatatableVouchers()
    // {
    //     $trasnaction = new Transaction;
    //     $transaction_list = $trasnaction->getUnpaidTransaction();

    //     $count = 0;
    //     return DataTables::of($transaction_list)

    //     ->addColumn('count', function($rows) use (&$count) {
    //         return strval(++$count);
  
    //     })
    //     ->addColumn('option', function($rows) use (&$count) {
    //         $uniqId = 'row_'.uniqid();
    //         $view = '<input type="checkbox"  name="transaction[]" class="checkbox_transaction" onclick="show_approve_selected(this,event,"'.$uniqId.'")" value="'.Crypt::encrypt($rows->id).'">';
            
    //         return $view;
    //     })
    //     ->addColumn('created_at', function($rows) {
    //         return EF::dateFormat($rows->created_at);
    //     })
    //     ->addColumn('clearance_date', function($rows) {
    //         $view = '<input disabled type="date" name="date[]" class="form-control form-control-sm">';
    //         return $view;
    //     })
    //     ->addColumn('voucher_approval', function($rows) {
    //         $view = '<select disabled name="status[]">
    //         <option value="Approve">Approve</option>
    //         <option value="Reject">Reject</option>
    //      </select>';
    //         return $view;
    //     })
    //     ->addColumn('temp_no', function($rows) {
    //         $view = '<a target="_blank" href="'.
    //         route('document.voucherpreview',['id' => Crypt::encrypt($rows->id)])
    //         .'" > VR / '.sprintf('%04d', $rows->id).'</a>';
    //         return $view;
    //     })
    //     ->addColumn('branch', function($rows) {
    //         return $rows->getBranch($rows->id);
    //     })
    //     ->addColumn('status', function($rows){
    //         $view = '';
    //         if($rows->status == "Unapprove")
    //         {
    //           $view = '<span class="badge badge-danger">'.EF::getstatus($rows->status).'</span>';
    //         }

    //         return $view;
    //       })
    //     ->addColumn('payment_detail', function($rows) {
    //         return wordwrap($rows->description,50,'<br>');
    //     })
    //     ->addColumn('debit', function($rows) {
    //         $journal_list = $rows->getJournalListByTransaction($rows->id);
            
    //         return EF::numberFormat($journal_rows->debit);
    //     })
    //     ->addColumn('credit', function($rows) {
    //         $journal_list = $rows->getJournalListByTransaction($rows->id);
    //         return wordwrap($rows->description,50,'<br>');
    //     })

        
        
    //     ->rawColumns(['status','count','branch_name','salesperson','booking_details','tags','action'])
    //     ->make(true);
    // }


    public function viewGeneralVoucher($voucher_type){

        // TODO User Types

        $user = new User;

        $booking = new Booking;

        $account = new Account;

        $generic_type = new GenericType;

        $approve_booking = $booking->getAllBookings(['Approve']);

        $head   = new Head();

        $branch = new Branch;


        return view('voucher.modals.general_voucher',
            [
                'generic_list'   => $generic_type->getAllGenericList(),
                'user_type_list' => EF::getUserTypeWithRole(),
                // 'booking_list'   => $approve_booking,
                'head_list'      => $head->getAllHeads(),
                'voucher_id'     => uniqid(),
                'branch'         => $branch->getBranchList(),
                'filter_subhead_list'   => $account->getAllSubheadByType($voucher_type),
                'subhead_list'          => $account->getAllSubhead(),
                'voucher_type'          => $voucher_type,



            ]);
    }
    public function viewDebitVoucher($voucher_type){
        $user = new User;

        $booking= new Booking();

        $head= new Head();
        $branch = new Branch;
        $account = new Account;
        $generic_type = new GenericType;

        $data['account_section'] = '<div class="card-header"><strong>Credit Account </strong></div>
                                    <div class="card-body form-fieldset">'.view('components.voucher.account_section',[

                                        'subhead_list'          => $account->getAllSubhead(),
                                        'filter_subhead_list'   => $account->getAllSubheadByType($voucher_type),
                                        'voucher_type'          => $voucher_type,
                                        'convention'            => 'credit',
                                        'unique_id'             => uniqid(),

                                    ])->render().'</div></div>';

        $data['view'] = View('voucher.modals.multiple_debit_voucher',
            [
                'user_type_list' => EF::getUserTypeWithRole(),
                // 'booking_list'   => $booking->getAllBookings(['Approve']),
                'head_list'      => $head->getAllHeads(),
                'voucher_id'     => uniqid(),
                'branch'         => $branch->getBranchList(),
                'generic_list'   => $generic_type->getAllGenericList(),
                'filter_subhead_list'   => $account->getAllSubheadByType($voucher_type),
                'subhead_list'          => $account->getAllSubhead(),
                'voucher_type'          => $voucher_type,
            ])->render();

        return $data;
    }
    public function viewCreditVoucher($voucher_type){
        $user = new User;

        $booking= new Booking();

        $head= new Head();
        $branch = new Branch;
        $generic_type = new GenericType;
        $account = new Account;

        $data['account_section'] = '<div class="card-header"><strong>Debit Account </strong></div>
                                    <div class="card-body form-fieldset">'.view('components.voucher.account_section',[
                                        'subhead_list'          => $account->getAllSubhead(),
                                        'filter_subhead_list'   => $account->getAllSubheadByType($voucher_type),
                                        'voucher_type'          => $voucher_type,
                                        'convention'            => 'debit',
                                        'unique_id'             => uniqid(),
                                    ])->render().'</div></div>';




        $data['view'] = View('voucher.modals.multiple_credit_voucher',
            [
                'user_type_list' => EF::getUserTypeWithRole(),
                // 'booking_list'   => $booking->getAllBookings(['Approve']),
                'head_list'      => $head->getAllHeads(),
                'voucher_id'     => uniqid(),
                'generic_list'   => $generic_type->getAllGenericList(),

                'branch'         => $branch->getBranchList(),
                'filter_subhead_list'   => $account->getAllSubheadByType($voucher_type),
                'subhead_list'          => $account->getAllSubhead(),
                'voucher_type'          => $voucher_type,



            ])->render();

        return $data;
    }
    public function setGvVoucher($id,$voucher_type){

        $user = new User;

        try
        {
            $curr_branch = decrypt($id);

            if($curr_branch <= 0)
            {
                $curr_branch = 0;
            }
        }
        catch (DecryptException $e)
        {
            $curr_branch  = 0;
            $voucher_type = 0;
        }



        $booking= new Booking();
        $branch = new Branch;
        $generic_type = new GenericType;
        $account = new Account;


        $head= new Head();
        return View('voucher.modals.general_voucher',
            [
                'user_type_list' => $user->getUserType(),
                'booking_list'   => $booking->getBookingByBranch([$curr_branch],['Approve']),
                'head_list'      => $head->getAllHeads(),
                'voucher_id'     => uniqid(),
                'branch'         => $branch->getBranchList(),


                'generic_list'   => $generic_type->getAllGenericList(),
               'filter_subhead_list'   => $account->getAllSubheadByType($voucher_type),
                'subhead_list'          => $account->getAllSubhead(),
                'voucher_type'          => $voucher_type,



            ]);
    }

    public function setCrvVoucher($id,$voucher_type){

        try
        {
            $curr_branch = decrypt($id);

            if($curr_branch <= 0)
            {
                $curr_branch = 0;
            }
        }
        catch (DecryptException $e)
        {
            $curr_branch = 0;
            $voucher_type = 0;
        }

        $user = new User;

        $booking= new Booking();
        $branch = new Branch;

        $head= new Head();
        $generic_type = new GenericType;
        $account = new Account;





        return View('voucher.modals.multiple_credit_voucher',
            [
                'user_type_list' => $user->getUserType(),
                'booking_list'   => $booking->getBookingByBranch([$curr_branch],['Approve']),
                'head_list'      => $head->getAllHeads(),
                'voucher_id'     => uniqid(),
                'branch'         => $branch->getBranchList(),
                'generic_list'   => $generic_type->getAllGenericList(),
                'filter_subhead_list'   => $account->getAllSubheadByType($voucher_type),
                'subhead_list'          => $account->getAllSubhead(),
                'voucher_type'          => $voucher_type,




            ]);
    }

    public function setDbVoucher($id,$voucher_type){

        try
        {
            $curr_branch = decrypt($id);

            if($curr_branch <= 0)
            {
                $curr_branch = 0;
            }
        }
        catch (DecryptException $e)
        {
            $curr_branch = 0;
            $voucher_type = 0;
        }

        $user = new User;

        $booking = new Booking();
        $branch  = new Branch;
        $generic_type = new GenericType;
        $account = new Account;


        $head = new Head();

        return View('voucher.modals.multiple_debit_voucher',
            [
                'user_type_list'        => $user->getUserType(),
                'booking_list'          => $booking->getBookingByBranch([$curr_branch],['Approve']),
                'head_list'             => $head->getAllHeads(),
                'voucher_id'            => uniqid(),
                'branch'                => $branch->getBranchList(),
                'generic_list'          => $generic_type->getAllGenericList(),
                'filter_subhead_list'   => $account->getAllSubheadByType($voucher_type),
                'subhead_list'          => $account->getAllSubhead(),
                'voucher_type'          => $voucher_type,
            ]);
    }

    public function approveVoucher($id)
    {

        $id = Crypt::decrypt($id);


        $journal = new Journal;
        $payment = new Payment;


        $journal_list = $journal->getJorunalByTransactionId($id);





          $view = '<table class="table table-hover table-outline table-vcenter text-nowrap card-table">
         <thead>
         <tr>

          <th>#</th>
          <th>Account</th>
          <th>Payment Detail</th>
          <th>Description</th>
          <th>Debit</th>
          <th>Credit</th>

         </tr>
         </thead>
         <tbody>';






                $count = 0;

                foreach ($journal_list as $rows)
                {


                    $other_info = $payment->showGenericTypeDetail($rows->payment);






                $view .= '<tr>
                            <td>'.++$count.'<label id="voucher_journal_id" class="id">'. Crypt::encrypt($rows->id).'</label></td>
                            <input type="hidden" name="account[]" value="'.Crypt::encrypt($rows->account->id).'"/>
                            <td>'.$rows->account->name.'</td>
                            <td>'.$other_info['description'].'</td>';

                            if(isset($rows->payment->id))
                            {
                                $view.=  '<td>'.wordwrap($rows->payment->description,50,'<br>').'</td>';

                            }
                            else
                            {
                                $view.=  '<td>'.$rows->narration.'</td>';

                            }

                           $view.=  '<td>'.EF::numberFormat($rows->debit).'</td>';
                           $view.=  '<td>'.EF::numberFormat($rows->credit).'</td>';








                }

         $view .='</tbody></table>';


        return $view;
    }

    public function pendingPaymentVoucherAlgo(Request $request)
    {
        $payment_list = Payment::where(['generic_type_id' => 1, 'is_recycle' => '0', 'status' => 'Unapprove'])->orderBy('id','asc')->get();

        foreach($payment_list->chunk('100') as $payments)
        {
            \DB::transaction(function() use($payments){

                foreach($payments as $rows)
                {
                    $jv_data['compound_type']           = 'General';
                    $jv_data['branch'][0]               = ($rows->branch_id);
                    $jv_data['approve_transaction']     = true;
                    $jv_data['voucher_list']            = 'BRV';
                    $jv_data['date']                    = $rows->created_at;

                    $jv_data['generic_type'][0]         = 1;
                    $jv_data['booking'][0]              = $rows->installment->booking_id;
                    $jv_data['payment'][0]              = $rows->id;
                    $jv_data['amount'][0]               = $rows->amount;
                    $jv_data['user'][0]                 = $rows->user_id;
                    $jv_data['debit_subhead'][0]        = 2;
                    $jv_data['credit_subhead'][0]       = 10;
                    $jv_data['narration'][0]            = $rows->description;
                    $jv_data['payment_mode'][0]         = $rows->mode;
                    $jv_data['instrument'][0]           = $rows->instrument;
                    $jv_data['drawn'][0]                = $rows->drawn_on;
                    $jv_data['instrument_date'][0]      = $rows->instrument_date;
                    $jv_data['deposit_no'][0]           = NULL;
                    $jv_data['deposit_date'][0]         = NULL;
                    $jv_data['payment_type'][0]         = $rows->payment_type;
                    $jv_data['auto_jv'][0]              = 0;
                    
                    $transaction = $rows->createVoucher($jv_data);

                    $transaction->updateStatusByTransaction([
                        'transaction_id' => $transaction->id,
                        'status' => 'Approve',
                        'date'   => $rows->created_at,
                    ]);




                }

            });
            
        }
    }

    public function storeVoucher(VoucherRequest $request)
    {

        try
        {

            $payment = new Payment;

            $form_collect = $request->input();

            $compund_list = EF::getVoucherType();

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

            $debit_id  = $form_collect['debit_subhead'][0];
            $credit_id = $form_collect['credit_subhead'][0];

            $index = 0;

            foreach ($form_collect['amount'] as $rows)
            {
                // FOR MULTIPLE DEBIT
                if($compund_list[1] == $form_collect['compound_type'])
                {
                    $form_collect['credit_subhead'][$index] = $credit_id;
                }
                // FOR MULTIPLE CREDIT
                else if($compund_list[2] == $form_collect['compound_type'])
                {
                    $form_collect['debit_subhead'][$index] = $debit_id;
                }

                $form_collect['branch'][$index]             = $branch;

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

                if(isset($form_collect['user_type']) && $form_collect['user_type'][$index]){

                    $form_collect['role'][$index]           = decrypt($form_collect['user_type'][$index]);
                    
                }

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

                $form_collect['payment'][$index]            = decrypt($form_collect['payment'][$index]);

                 $form_collect['generic_type'][$index]      = decrypt($form_collect['generic_type'][$index]);


                if(isset($form_collect['payment_type'][$index]))
                {
                    $form_collect['payment_type'][$index]            = decrypt($form_collect['payment_type'][$index]);
                }
                else
                {
                    $form_collect['payment_type'][$index]            = NULL;
                }


                $form_collect['debit_subhead'][$index]      = decrypt($form_collect['debit_subhead'][$index]);

                $form_collect['credit_subhead'][$index]     = decrypt($form_collect['credit_subhead'][$index]);


                $index++;
            }

            if(!isset($form_collect['receipt']))
            {
                $form_collect['receipt'] = NULL;
            }



            if(!isset($form_collect['auto_jv']))
            {
                $form_collect['auto_jv'] = 0;
            }




        $transaction = $payment->createVoucher($form_collect);

        if(isset($transaction->id))
        {
            parent::setLogMessage('Voucher VR/'.sprintf('%04d', $transaction->id).' has been created');

            parent::successMessage('Voucher has been created.',parent::getLogMessage());

            if(\Request::ajax())
            {
                return 1;
            }
        }


        }
        catch (DecryptException $e)
        {
            exit;
        }
        return redirect()->back();


    }

    // public function storeVoucher(VoucherRequest $request)
    // {
    //     $form_collect = $request->input();



    //     for($i=0;$i<count($form_collect['amount']);$i++)
    //     {

    //     $form_collect['user'][$i]           = Crypt::decrypt($form_collect['user'][$i]);
    //     $form_collect['booking'][$i]        = Crypt::decrypt($form_collect['booking'][$i]);
    //     $form_collect['installment'][$i]    = Crypt::decrypt($form_collect['installment'][$i]);
    //     $form_collect['commission'][$i]     = Crypt::decrypt($form_collect['commission'][$i]);



    //     if('General'== $form_collect['type']){
    //     $form_collect['head_db'][$i]        = Crypt::decrypt($form_collect['head_db'][$i]);
    //     $form_collect['subhead_db'][$i]     = Crypt::decrypt($form_collect['subhead_db'][$i]);
    //     $form_collect['subhead_cr'][$i]     = Crypt::decrypt($form_collect['subhead_cr'][$i]);
    //     $form_collect['head_cr'][$i]        = Crypt::decrypt($form_collect['head_cr'][$i]);
    //     }
    //     if('Multiple Debit'== $form_collect['type']){

    //     $form_collect['head_db'][$i]        = Crypt::decrypt($form_collect['head_db'][$i]);
    //     $form_collect['subhead_db'][$i]     = Crypt::decrypt($form_collect['subhead_db'][$i]);


    //     }
    //     if('Multiple Credit'== $form_collect['type']){

    //     $form_collect['subhead_cr'][$i]     = Crypt::decrypt($form_collect['subhead_cr'][$i]);
    //     $form_collect['head_cr'][$i]        = Crypt::decrypt($form_collect['head_cr'][$i]);
    //     }

    //     }


    //     if('Multiple Debit'== $form_collect['type']){
    //     $form_collect['subhead_cr']         = Crypt::decrypt($form_collect['subhead_cr'][0]);
    //     $form_collect['head_cr']            = Crypt::decrypt($form_collect['head_cr'][0]);

    //     }
    //     if('Multiple Credit'== $form_collect['type']){
    //     $form_collect['head_db']            = Crypt::decrypt($form_collect['head_db'][0]);
    //     $form_collect['subhead_db']         = Crypt::decrypt($form_collect['subhead_db'][0]);
    //     }
    //     $form_collect['branch']             = Crypt::decrypt($form_collect['branch']);
    //     $payment = new Payment;


    //     if($payment->createVocuher($form_collect))
    //     {

    //         parent::successMessage('Voucher has been created.');
    //     }


    //
    // }

    public function updateVoucher(VoucherRequest $request)
    {

        $journal_list = $request->journal_list;

        $amount_size = @count($request->amount);

        $counter = 0;

        $key = 0;

        $ledget_list = array();

        $form_collect = $request->input();

        // dd($form_collect);

        $compund_list = EF::getVoucherType();

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

            foreach($journal_list as $rows)
            {
                if(trim($form_collect['compound_type']) == $compund_list[0])
                {
                    if($key == 0)
                    {
                        $account =  $form_collect['debit_subhead'][$counter];
                    }
                    else if($key == 1)
                    {
                        $account =  $form_collect['credit_subhead'][$counter];
                    }
                }
                else if(trim($form_collect['compound_type']) == $compund_list[1])
                {
                    if($key == 0)
                    {
                        $account =  $form_collect['debit_subhead'][$counter];
                    }
                    else if($key == 1)
                    {
                        $account =  $form_collect['credit_subhead'][0];
                    }
                }
                else if(trim($form_collect['compound_type']) == $compund_list[2])
                {
                    if($key == 0)
                    {
                        $account =  $form_collect['debit_subhead'][0];
                    }
                    else if($key == 1)
                    {
                        $account =  $form_collect['credit_subhead'][$counter];
                    }
                }

                $ledget_list[] = array(

                    'id'              => decrypt($rows),

                    'transaction_id'  => decrypt($form_collect['transaction']),


                    'branch_id'       => $curr_branch,

                    'booking_id'      => decrypt($form_collect['booking'][$counter]),

                    'user_id'         => decrypt($form_collect['user'][$counter]),

                    'payment_id'      => decrypt($form_collect['payment'][$counter]),

                    'generic_type'    => decrypt($form_collect['generic_type'][$counter]),

                    'account_id'      => decrypt($account),

                    'voucher'         => ($form_collect['voucher_list']),

                    'compound'        => ($form_collect['compound_type']),

                    'date'            => ($form_collect['date']),

                    'amount'          => ($form_collect['amount'][$counter]),

                    'narration'       => ($form_collect['narration'][$counter]),

                    'drawn'           => ($form_collect['drawn'][$counter]),

                    'instrument'      => ($form_collect['instrument'][$counter]),

                    'instrument_date' => ($form_collect['instrument_date'][$counter]),

                    'mode'            => ($form_collect['payment_mode'][$counter]),

                    'deposit_no'      => ($form_collect['deposit_no'][$counter]),

                    'deposit_date'    => ($form_collect['deposit_date'][$counter]),

                );

                if($key == 1)
                {
                    $counter++;
                    $key = 0;
                }
                else
                {
                    $key++;
                }





            }


            if(@count($ledget_list) > 0)
            {
                $journal = new Journal;

                $transaction = $journal->updateVoucher($ledget_list);

                parent::setLogMessage('Voucher VR/'.sprintf('%04d', $transaction->id).' has been updated');

                parent::successMessage('Voucher has been updated.',parent::getLogMessage());

            }
        }
        catch (DecryptException $e)
        {
            parent::errorMessage('Something is wrong!.');
        }

        return redirect()->back();

    }

    public function getDebitCredit($compound_type,$data)
    {

    }

    public function updateVoucherStatus(VoucherRequest $request)
    {


        try
        {
            $form_collect = $request->input();
            $form_collect['journal_id'] = Crypt::decrypt($form_collect['journal_id']);

            $form_collect['transaction_id'] = Crypt::decrypt($form_collect['transaction_id']);

             $transaction = new Transaction;

             $curr_transaction = $transaction->updateStatusByTransaction($form_collect);

             if(isset($curr_transaction->id))
             {
                if($form_collect['status']== "Approve")
                {
                    parent::setLogMessage('Voucher VR/'.sprintf('%04d', $curr_transaction->id).' has been approved and new number has issued '.$curr_transaction->voucher_type.'-'.$curr_transaction->voucher_number);

                      parent::successMessage('Voucher has been approved.',parent::getLogMessage());
                }

                else if($form_collect['status'] == "Reject")
                {
                      parent::setLogMessage('Voucher VR/'.sprintf('%04d', $curr_transaction->id).' has been rejected');

                      parent::successMessage('Voucher has been rejected.',parent::getLogMessage());
                }
                else if($form_collect['status'] == "Reverse")
                {
                    parent::setLogMessage('Voucher VR/'.sprintf('%04d', $curr_transaction->id).' has been reserved');

                      parent::successMessage('Voucher has been reserved.',parent::getLogMessage());

                }


             }
             else
             {
                 parent::errorMessage('Voucher status not updated.');
             }





        }
        catch (DecryptException $e)
        {

        }

        return redirect()->back();
    }

    public function reversalVoucher($id)
    {

        try
        {


            $id=Crypt::decrypt($id);
            $journal = new Journal;
            $journal = $journal->getJournalById($id);

            $transaction_data = $journal->transaction_id;
            $payment_data = $journal->payment_id;

            $payment = new Payment;

                if($payment->reversalVocuher($payment_data,$transaction_data,$id)){
                     parent::successMessage('Voucher has been updated.');
                }




        }
        catch (DecryptException $e)
        {

        }

        return redirect()->back();
    }

    // public function updateVoucher(HeadRequest $request)
    // {

    //     try
    //     {
    //         $form_collect = $request->input();
    //         $form_collect['head_id'] = decrypt($form_collect['head_id']);
    //         $form_collect['branch'] = decrypt($form_collect['branch']);


    //         $head = new Head;
    //         if($head->updateHead($form_collect))
    //         {
    //             parent::successMessage('Head has been updated.');
    //         }
    //     }
    //     catch (DecryptException $e)
    //     {

    //     }

    //     return redirect('head');
    // }

    // public function removeVoucher($id)
    // {

    //     parent::errorMessage('Head not found.');

    //     try
    //     {
    //         $id = decrypt($id);
    //         $head = new Head;

    //         if($head->removeHead($id))
    //         {
    //             parent::successMessage('Head has been removed.');
    //         }
    //     }
    //     catch (DecryptException $e)
    //     {

    //     }

    //     return redirect()->back();
    // }


     // AM'

    public function showVoucher($id)
    {


        $view = '';

        try
        {
            // GLOABLE VARIBALE DECLARATION PART
            $user           = new User;
            $booking        = new booking;
            $transaction    = new Transaction;
            $journal        = new Journal;
            $head           = new Head;
            $branch         = new Branch;
            $generic_type   = new GenericType;


            $voucher_title  = "";
            $voucher_header = "";
            $voucher_body   = "";
            // END

            // DECRPT TRANCACTION ID
            $id = decrypt($id);
            // END

            // GET ALL COMPOUND TYPE
            // [0] INDEX => GENERAL
            // [1] INDEX => MULTIPLE DEBIT
            // [2] INDEX => MULTIPLE CREDIT
            $compund_list = EF::getVoucherType();
            // END
            $payment_list = EF::getPaymentType();


            // GET TRANSACTION BY ID FROM TRANSACTION TABLE
            $curr_transaction = $transaction->getTransactionById($id);

            // VERIFY TRANSACTION IS FOUND OR NOT
            if(isset($curr_transaction->id))
            {
                // GET JOURNAL / LEDGER FROM JOURNAL TABLE
                $journal_list = $journal->getJorunalByTransactionId($curr_transaction->id);


                $view.= '<input type="hidden" name="transaction" value="'.Crypt::encrypt($curr_transaction->id).'" >';


                // COMMON SECTION DECLARE
                $data = [

                    // GLOBAL DECLARATION FOR ALL FUNCTION
                    'user_type_list'   => $user->getUserType(),

                    'head_list'        =>  $head->getAllHeads(),

                    'branch'           => $branch->getBranchList(),

                    'generic_list'     => $generic_type->getAllGenericList(),

                    'transaction'      => $curr_transaction,

                    // END

                    // SET DATA IN FUNCTION
                    'compound' => $curr_transaction->compound_type,
                    'type'     => $curr_transaction->voucher_type,
                    'date'     => date('Y-m-d',strtotime($curr_transaction->created_at)),
                    'current_branch' => $journal_list[0]->branch_id,


                    // END
                ];

                $counter = 0;
                $voucher_header = $this->getVoucherHeader($data);
                // CHECK GENERAL VOUCHER
                if($curr_transaction->compound_type == $compund_list[0])
                {
                    foreach ($journal_list as $rows)
                    {
                        $data['booking_list'] = $booking->getBookingByBranch([$rows->branch_id],['Approve']);

                        // $data['current_branch'] = $rows->branch_id;

                        $view.='<input type="hidden" value="'.Crypt::encrypt($rows->id).'" name="journal_list[]">';

                        if($rows->debit > 0)
                        {
                            //BbOOKING SECTION VIEW

                            $data['booking'] = $rows->booking;

                            $data['payment'] = $rows->payment;

                            $data['amount']  = $rows->debit;

                            $data['loan_id'] = $rows->loan_id;



                            $voucher_body.= $this->getBookingSection($data);
                            // END BOOKING SECTION VIEW

                            // USER SECTION VIEW
                            $data['user'] = $rows->user;

                            $voucher_body.= $this->getUserSection($data);
                            // END USER SECTION VIEW

                            // DEBIT ACCOUNT SECTION VIEW
                            $data['convention'] = 'debit';

                            $voucher_body.='<label class="label-color">Debit Account:</label>';

                            $data['account'] = $rows->account;

                            $voucher_body.= $this->getAccountSection($data);
                            // END  DEBIT ACCOUNT SECTION VIEW


                        }
                        elseif($rows->credit > 0)
                        {
                            // CREDIT ACCOUNT SECTION VIEW
                            $data['convention'] = 'credit';

                            $voucher_body.='<label class="label-color">Credit Accout:</label>';

                            $data['account'] = $rows->account;

                            $voucher_body.= $this->getAccountSection($data);
                            // END  DEBIT ACCOUNT SECTION VIEW

                            // NARRATION SECTION
                            $data['narration'] = $rows->narration;

                            $voucher_body.= $this->getNarrationSection($data);
                            // END NARRATION SECTION

                            // PAYMENT SECTION
                            $data['mode']            = $rows->mode;
                            $data['instrument']      = $rows->instrument;
                            $data['instrument_date'] = date('Y-m-d',strtotime($rows->instrument_date));
                            $data['deposit_no']      = $rows->deposit_no;
                            $data['deposit_date'] = date('Y-m-d',strtotime($rows->deposit_date));
                            $data['drawn_on']        = $rows->drawn_on;
                            $data['post_dated']      = $rows->post_dated;


                            $voucher_body.= $this->getPaymentSection($data);
                            // END PAYMENT SECTION


                        }

                        $data['voucher_title']  = 'General Voucher';
                        $data['voucher_header'] =  $voucher_header;
                        $data['voucher_body']   =  $voucher_body;

                        if($counter == 1)
                        {
                            $counter        = 0;
                            $voucher_header =  '';
                            $voucher_body   =  '';

                            $view.= $this->bindVoucher($data);

                        }
                        else
                        {
                            $counter++;
                        }




                    }

                }
                // CHECK MULTIPLE DEBIT VOUCHER
                else if($curr_transaction->compound_type == $compund_list[1])
                {
                    $count = 0;

                    foreach ($journal_list as $rows)
                    {
                        $view.='<input type="hidden" value="'.Crypt::encrypt($rows->id).'" name="journal_list[]">
 ';

                        if($rows->debit > 0)
                        {
                            $data['booking_list'] = $booking->getBookingByBranch([$rows->branch_id],['Approve']);

                            // $data['current_branch'] = $rows->branch_id;

                            //BbOOKING SECTION VIEW
                            $data['booking'] = $rows->booking;

                            $data['payment'] = $rows->payment;

                            $data['amount']  = $rows->debit;

                            $voucher_body.= $this->getBookingSection($data);
                            // END BOOKING SECTION VIEW

                            // USER SECTION VIEW
                            $data['user'] = $rows->user;
                            $data['loan_id'] = $rows->loan_id;

                            $voucher_body.= $this->getUserSection($data);
                            // END USER SECTION VIEW

                             // CREDIT ACCOUNT SECTION VIEW
                            $data['convention'] = 'debit';

                            $voucher_body.='<label class="label-color">Debit Account:</label>';

                            $data['account'] = $rows->account;

                            $voucher_body.= $this->getAccountSection($data);
                            // END  DEBIT ACCOUNT SECTION VIEW

                            // NARRATION SECTION
                            $data['narration'] = $rows->narration;

                            $voucher_body.= $this->getNarrationSection($data);
                            // END NARRATION SECTION

                            // PAYMENT SECTION
                            $data['mode']            = $rows->mode;
                            $data['instrument']      = $rows->instrument;
                            $data['instrument_date'] = date('Y-m-d',strtotime($rows->instrument_date));
                              $data['deposit_no']      = $rows->deposit_no;
                            $data['deposit_date'] = date('Y-m-d',strtotime($rows->deposit_date));
                            $data['drawn_on']        = $rows->drawn_on;
                            $data['post_dated']      = $rows->post_dated;



                            $voucher_body.= $this->getPaymentSection($data);
                            // END PAYMENT SECTION

                        }
                        else if($rows->credit > 0)
                        {

                            if($count == 0)
                            {

                                // DEBIT ACCOUNT SECTION VIEW
                                $data['convention'] = 'credit';
     $voucher_header.='<div class="col-sm-12"><div class="card"><div class="card-header"><strong>Credit Account</strong></div><div class="card-body form-fieldset">';

                                $data['account'] = $rows->account;

                                $voucher_header.= $this->getAccountSection($data);
                                // END  DEBIT ACCOUNT SECTION VIEW
                                $voucher_header.='</div></div> </div>';


                                $count++;
                            }

                        }

                        $data['voucher_title']  = 'Multiple Debit Voucher';
                        $data['voucher_header'] =  $voucher_header;
                        $data['voucher_body']   =  $voucher_body;

                        if($counter == 1)
                        {
                            $counter        = 0;
                            $voucher_header =  '';
                            $voucher_body   =  '';

                            $view.= $this->bindVoucher($data);

                        }
                        else
                        {
                            $counter++;
                        }
                    }
                }
                // CHECK MULTIPLE CREDIT VOUCHER
                else if($curr_transaction->compound_type == $compund_list[2])
                {

                    $count = 0;

                    foreach ($journal_list as $rows)
                    {
                        $view.='<input type="hidden" value="'.Crypt::encrypt($rows->id).'" name="journal_list[]">
 ';


                        if($rows->debit > 0)
                        {
                            if($count == 0)
                            {
                                $voucher_header.='<div class="col-sm-12"><div class="card"><div class="card-header"><strong>Debit Account</strong></div><div class="card-body form-fieldset">';
                                // DEBIT ACCOUNT SECTION VIEW
                                $data['convention'] = 'debit';


                                $data['account'] = $rows->account;

                                $voucher_header.= $this->getAccountSection($data);
                                // END  DEBIT ACCOUNT SECTION VIEW
                                $voucher_header.='</div></div></div>';


                                $count++;
                            }

                        }
                        else if($rows->credit > 0)
                        {

                            $data['booking_list'] = $booking->getBookingByBranch([$rows->branch_id],['Approve']);

                            // $data['current_branch'] = $rows->branch_id;

                            //BbOOKING SECTION VIEW


                            $data['booking'] = $rows->booking;

                            $data['payment'] = $rows->payment;

                            $data['amount']  = $rows->credit;

                            $voucher_body.= $this->getBookingSection($data);
                            // END BOOKING SECTION VIEW

                             // USER SECTION VIEW
                            $data['user'] = $rows->user;
                            $data['loan_id'] = $rows->loan_id;

                            $voucher_body.= $this->getUserSection($data);
                            // END USER SECTION VIEW

                             // CREDIT ACCOUNT SECTION VIEW
                            $data['convention'] = 'credit';

                            $voucher_body.='<label class="label-color">Credit Account:</label>';

                            $data['account'] = $rows->account;

                            $voucher_body.= $this->getAccountSection($data);
                            // END  DEBIT ACCOUNT SECTION VIEW

                            // NARRATION SECTION
                            $data['narration'] = $rows->narration;

                            $voucher_body.= $this->getNarrationSection($data);
                            // END NARRATION SECTION

                            // PAYMENT SECTION
                            $data['mode']            = $rows->mode;
                            $data['instrument']      = $rows->instrument;
                            $data['instrument_date'] = date('Y-m-d',strtotime($rows->instrument_date));
                              $data['deposit_no']      = $rows->deposit_no;
                            $data['deposit_date'] = date('Y-m-d',strtotime($rows->deposit_date));
                            $data['drawn_on']        = $rows->drawn_on;
                            $data['post_dated']      = $rows->post_dated;



                            $voucher_body.= $this->getPaymentSection($data);
                            // END PAYMENT SECTION

                        }

                        $data['voucher_title']  = 'Multiple Credit Voucher';
                        $data['voucher_header'] =  $voucher_header;
                        $data['voucher_body']   =  $voucher_body;

                        if($counter == 1)
                        {
                            $counter        = 0;
                            $voucher_header =  '';
                            $voucher_body   =  '';

                            $view.= $this->bindVoucher($data);

                        }
                        else
                        {
                            $counter++;
                        }
                    }
                }
            }


        }
        catch (DecryptException $e)
        {

        }

        return $view;
    }

    public function getVoucherHeader($data)
    {
        $data['unique_id'] = uniqid();

        return view('components.voucher.voucher_header',$data);
    }

    public function getBookingSection($data)
    {

        $data['unique_id'] = uniqid();
        $data['installment']   = "";
        $data['commission']    = "";
        $data['generic_type']  = 0;


        $data['installment_list'] = array();
        $data['commission_list']  = array();


        if(isset($data['payment']['id']))
        {
            $payment_list = EF::getPaymentType();

            $payment = new Payment;

            $data['generic_type']  = $data['payment']->genericType;

            if($data['payment']->generic_type_id === $this->generic_index['Installment'])
            {
                $booking_id = $data['payment']->installment->booking_id;

                $data['payment_list'] = $payment->getInstallmentPaymentList($booking_id,$data['payment']->generic_type_id,['Unapprove']);
            }
            else if($data['payment']->generic_type_id === $this->generic_index['Commission'])
            {
                $booking_id = $data['payment']->commission->booking_id;

                $data['payment_list'] = $payment->getCommissionPaymentList($booking_id,$data['payment']->generic_type_id,['Unapprove']);
            }
            else if($data['payment']->generic_type_id === $this->generic_index['Booking'])
            {
                $booking_id = $data['payment']->generic_id;

                $data['payment_list'] = $payment->getPaymentByGenericIdWithType($booking_id,$data['payment']->generic_type_id,['Unapprove']);
            }
            else
            {
                $data['payment_list'] = $payment->getOtherPaymentList($data['payment']->generic_type_id,['Unapprove']);
            }



        }

        return view('components.voucher.booking_section',$data);
    }

    public function getUserSection($data)
    {
        $data['unique_id'] = uniqid();

        $data['user_list'] = array();

        if(isset($data['user']['id']))
        {

            $user = new User;

            $data['user_list'] = $user->getUserListByType([$data['user']['type']]);

        }


        return view('components.voucher.user_section',$data);
    }

    public function getAccountSection($data)
    {
        $data['unique_id'] = uniqid();

        $data['subhead_list'] = array();

        if(isset($data['account']['id']))
        {
            $head_id = $data['account']['head_id'];

            $account = new Account;

            $data['filter_subhead_list'] = $account->getAllSubHeadByType($data['transaction']->voucher_type);
            $data['subhead_list']        = $account->getAllSubHead();
            $data['voucher_type']        = $data['transaction']->voucher_type;



        }

        return view('components.voucher.account_section',$data);
    }

    public function payPayment(VoucherRequest $request)
    {
        try
        {
           

            if($this->storeVoucher($request))
            {

                 parent::successMessage('Payment has been updated.');
            }


        }
        catch (DecryptException $e)
        {

        }
        return redirect()->back();
    }
    public function payInstallment(VoucherRequest $request)
    {
        try
        {


        if($this->storeVoucher($request))
        {

             parent::successMessage('Installment has been paid.');
        }


        }
        catch (DecryptException $e)
        {

        }
        return redirect()->back();


    }
       public function payCommission(VoucherRequest $request)
    {
        try
        {

        if($this->storeVoucher($request))
        {

             parent::successMessage('Commission has been paid.');
        }


        }
        catch (DecryptException $e)
        {

        }
        return redirect()->back();


    }

    public function getNarrationSection($data)
    {
        $data['unique_id'] = uniqid();

        return view('components.voucher.narration_section',$data);
    }

    public function getPaymentSection($data)
    {
        $data['unique_id'] = uniqid();

        return view('components.voucher.payment_section',$data);
    }

    public function bindVoucher($data)
    {
        $data['unique_id'] = uniqid();

        return view('components.voucher.bind_voucher',$data);
    }

    public function approveMultipleVouchers(Request $request)
    {
        $transaction = new Transaction;

        $transaction_list = $request->input('transaction');

        $date_list  =   $request->input('date');

        $status_list  =   $request->input('status');

        $index = 0;

        foreach($transaction_list as $transaction_row){

            $form_collect['transaction_id'] = decrypt($transaction_row);
            $form_collect['status'] = $status_list[$index];
            $form_collect['date']   = $date_list[$index];

            $curr_transaction = $transaction->updateStatusByTransaction($form_collect);

            if(isset($curr_transaction->id)){
                parent::setLogMessage('Voucher VR/'.sprintf('%04d', $curr_transaction->id).' has been updated');

                parent::successMessage('Voucher has been updated.',parent::getLogMessage());
            }
            else{
                parent::errorMessage('Voucher not has been updated.',parent::getLogMessage());
            }

            $index++;
        }

        return back();

    }

    function voucherFilter(Request $request)
    {
        
        $default_view = '<tr><td colspan=13>No Record Found<td></tr>';

        $view = $default_view;

        if($request->ajax())
        {
            $transaction = new Transaction;

            $from = $request->from;
            $to   = $request->to;


            $branch = decrypt($request->project);

            $view = view('components.voucher.table_voucher',[

                'trasnaction'   => $transaction->getUnpaidFilterTransaction($from,$to,$branch),

            ])->render();

            if(trim(strlen($view)) <= 0)
            {
                $view = $default_view;
            }
        }

        return $view;
    }
}
