<?php

namespace Gisplus\Package\EstatechVendor\Controllers;

use App\Http\Controllers\Controller;



use Illuminate\Http\Request;

use Gisplus\Package\EstatechVendor\Models\Invoice;

use Gisplus\Package\EstatechVendor\Models\PurchaseItem;

use Gisplus\Package\EstatechVendor\Requests\InvoiceRequest;

use EF;

use App\User;

use App\Branch;

use App\Vendor;

use App\Payment;

use App\Journal;

use App\Account;

use App\Transaction;


use PDF;

use Crypt;



class InvoiceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $invoice = new Invoice;

        $user = new User;
        
        $branch = new Branch;

        $vendor_list = $user->getUserListByType(['Vendor']);

        $branch_list = $branch->getBranchList();

        $invoice_list = $invoice->getInvoiceList();

        return view('estatechvendor::manage_invoice',[
            'vendor_list'  => $vendor_list,
            'branch_list'  => $branch_list,
            'invoice_list'  => $invoice_list,
        ]);

    }

    public function showStoreInvoice()
    {
        $invoice = new Invoice;

        $purchase_item = new PurchaseItem;

        $user = new User;
        
        $branch = new Branch;

        $vendor_list = $user->getUserListByType(['Vendor']);

        $branch_list = $branch->getBranchList();

        return view('estatechvendor::add_invoice',[
            'vendor_list'  => $vendor_list,
            'branch_list'  => $branch_list,
            'item_code_list' => $purchase_item->getItemCodeList()
        ]);

    }

    
    public function storeInvoice(InvoiceRequest $request)
    {
        $invoice = new Invoice;
        
        $collect_form = $request->input();
        
        $collect_form['branch']    = decrypt($collect_form['branch']);
        
        $collect_form['user']      = decrypt($collect_form['user']);
        
        $curr_invoice =  $invoice->storeInvoice($collect_form);

        if(isset($curr_invoice->id))
          {
             if($request->ajax())
             {
                return "true";
             }
              parent::setLogMessage('New Invoice "'.$curr_invoice->name.'" has been added.');
  
              parent::successMessage('New Invoice has been added.',parent::getLogMessage());
           
          }
          else
          {
            parent::errorMessage('Invoice already found.');
          }
  
          return redirect('invoices');
    }
 
    public function showUpdateInvoice($id)
    {
        $invoice_id = decrypt($id);

        $invoice = new Invoice;

        $user = new User;
        
        $branch = new Branch;

        $purchase_item = new PurchaseItem;


        $vendor_list = $user->getUserListByType(['Vendor']);

        $branch_list = $branch->getBranchList();

        $invoice = $invoice->getInvoiceById($invoice_id);
        
        return view('estatechvendor::update_invoice',[
            'vendor_list'   => $vendor_list,
            'branch_list'   => $branch_list,
            'invoice'       => $invoice,
            'item_code_list' => $purchase_item->getItemCodeList(),

        ]);

    }

    public function updateInvoice(InvoiceRequest $request)
    {
        try
         {
            $collect_form = $request->input();

            $collect_form['user']       = decrypt($collect_form['user']);

            $collect_form['branch']     = decrypt($collect_form['branch']);

            $collect_form['invoice']    = decrypt($collect_form['invoice']);

            $count = 0;

            foreach ($collect_form['purchase_item'] as $rows) {
                
                $collect_form['purchase_item'][$count] = decrypt($rows);

                $count++;
            }


            $invoice = new Invoice;

            $curr_invoice = $invoice->updateInvoice($collect_form);
            

            if(isset($curr_invoice))
            {
                 if($request->ajax())
             {
                return "true";
             }
                
                parent::setLogMessage($curr_invoice.' has been updated.');

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

     
        } catch (DecryptException $e) {
     
        }

        return redirect('invoices');

    }

    public function removeInvoice($id)
    {
        try {
            $id = decrypt($id);
            $invoice = new Invoice;

            if($invoice->removeInvoice($id))
            {
                parent::successMessage('Invoice has been removed.');
            }
        }
         catch (DecryptException $e) {
        }

        return redirect()->back();
    }

    public function showPendingInvoicePayments()
    {
        $payment = new Payment;


        return view('estatechvendor::invoice_payment',
            [
                'payment_list' => $payment->getAllInvoicePayments(),
        ]);
    }

    public function printInvoice($id)
    {
        try
        {

            $id = decrypt($id);

            $invoice = new Invoice;

            $invoice = $invoice->getInvoiceById($id);

            if(isset($invoice->id))
            {
                $pdf = PDF::loadView('estatechvendor::documents.invoice',[

                    'invoice'       => $invoice,
                ]);

                parent::setLogMessage($invoice->invoice_no.' has been viewed');
                 parent::getLogMessage();

                return $pdf->setPaper('a4', 'landscape')->stream('Invoice.pdf');
            }                 
        }
        catch (DecryptException $e) {

        }

        return redirect()->back();
    }

    public function vendorReport(Request $request)
    {
        try{

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

            $curr_user = new User;

            $collect_data = [

                'ledger_list' => $journal->getGroupUserLedger(),
                'user_list'   => $user->getUserListByType(['Vendor']),
                'branch_list' => $branch->getBranchList(),
                'flag'             => true,
                'all_vendor_flag'  => false,

            ];

            if($request->isMethod('post'))
            {
                $user   = decrypt($request->user);
                $branch = decrypt($request->project);


                $collect_data += [

                    'to'        => $request->input('to'),
                    'from'      => $request->input('from'),
                    'user_id'   => $user,
                    'project_id' => $branch,

                ];

                $condition = [];

                if($user > 0)
                {
                    $condition += ['user_id' => $user];

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

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

                }

                if(isset($request->all_vendor_flag) && !isset($request->flag))
                {
                    $collect_data['ledger_list'] = $journal->getGroupUserLedger($condition,$collect_data['from'],$collect_data['to'],false,true);
                     $collect_data['all_vendor_flag'] = true;
                     // $collect_data['flag'] = false;


                }
                else if(isset($request->all_vendor_flag) && isset($request->flag))
                {
                     $collect_data['ledger_list'] = $journal->getGroupUserLedger($condition,$collect_data['from'],$collect_data['to'],false,true);

                     $collect_data['flag'] = true;
                     $collect_data['all_vendor_flag'] = true;
                     

                }
                else if(isset($request->flag))
                {
                    $collect_data['ledger_list'] = $journal->getGroupUserLedger($condition,$collect_data['from'],$collect_data['to']);

                     $collect_data['flag'] = true;
                }
                else
                {
                     $collect_data['ledger_list'] = $journal->getLedgerByUser($condition,$collect_data['from'],$collect_data['to']);

                     $collect_data['flag'] = false;

                }

                $collect_data['curr_user'] = $curr_user;
               


                if(isset($request->pdf)){

                    $pdf = PDF::loadView('estatechvendor::reports.vendor_ledger_report',$collect_data);

                    return $pdf->setPaper('a4', 'landscape')->stream('Vendor ledger Report.pdf',array("Attachment" => true));

                }

            }

        }
        catch (DecryptException $e) {

        }
        
        return view('estatechvendor::vendor_ledger',$collect_data);
    }

    public function showPayInvoice($type,$generic_id)
    {
        try
        {
            $generic_index = EF::getGenericTableIndex();

            $data = [

                'branch_name'      => '',
                'user_type'        => '',
                'user_name'        => '',
                'booking_name'     => '',
                'payment_type'     => '',
                'description'      => '',
                'amount'           => 0,
                'generic'          => $generic_id, //ENCRYPTED
                'generic_type'     => $type,      // ENCRYPTED
                'section'          => '',
                'receipt'          => NULL,
                'account_list'     => [],

            ];

            $generic_id = decrypt($generic_id);
            $type       = decrypt($type);

            $invoice = new Invoice;

            $account = new Account;

            $invoice = $invoice->getInvoiceById($generic_id);

            if(isset($invoice->id))
            {
                $description = $invoice->purchaseItems->pluck('description')->toarray();
                
                $description = implode(',',$description);
                
                $data['user_type']      = 'Vendor';
                $data['role']           = encrypt($invoice->role_id);
                $data['branch_name']    = $invoice->branch->name;
                $data['user_name']      = $invoice->user->name;
                $data['payment_type']   = 'Pay Invoice';
                $data['description']    = $description;
                $data['section']        = 'Pay Invoice';
                $data['account_list']   = $account->getSubHeadByType('Bank');


                $data['amount']         = $invoice->amount - $invoice->received_amount;

                
            }
            
            return view('estatechvendor::payments.modals.add_vendor_payment',$data);
        }
        catch (DecryptException $e)
        {

        }
    }

    public function payVendorPayment(Request $request)
    {
        try
        {
            $account_info = EF::getAccountInfo();
            $form_collect = $request->input();

            $form_collect['generic']       = decrypt($form_collect['generic']);
            $form_collect['generic_type']  = decrypt($form_collect['generic_type']);
            $form_collect['account']       = decrypt($form_collect['account']);

            $payment = new Payment;

            $curr_payment = $payment->payGenericPayment($form_collect);

            if (isset($form_collect['role'])) {
                $form_collect['role']          = decrypt($form_collect['role']);
            }

            if($curr_payment->id)
            {
                parent::successMessage('Payment has been created.');

                $credit_account = 0;

                $debit_account = $account_info['control account'];


                if($curr_payment->mode ==  "Cash")
                {
                    $voucher_type = "CPV";

                    $credit_account = $account_info['cash'];
                }
                else
                {
                    $voucher_type = "BPV";

                    $credit_account = $form_collect['account'];
                }


                // CREATE VOUCHER
                $jv_data['compound_type']            =  "General";

               $jv_data['voucher_list']             =  $voucher_type;
               $jv_data['date']                     =  $curr_payment->created_at;
               $jv_data['role'][0]                  =  $curr_payment->role_id;
               $jv_data['receipt']                  =  NULL;
               $jv_data['branch'][0]                =  $curr_payment->branch_id;
               $jv_data['user'][0]                  =  $curr_payment->user_id;
               $jv_data['booking'][0]               =  NULL;
               $jv_data['amount'][0]                =  $curr_payment->amount;
               $jv_data['narration'][0]             =  'Payment made against invoice no. '.$curr_payment->invoice->invoice_no;
               $jv_data['payment_mode'][0]          =   $curr_payment->mode;
               $jv_data['instrument'][0]            =   $curr_payment->instrument;
               $jv_data['instrument_date'][0]       =   $curr_payment->instrument_date;
               $jv_data['drawn'][0]                 =   $curr_payment->drawn;
               $jv_data['generic_type'][0]          =   $curr_payment->generic_type_id;
               $jv_data['payment_type'][0]          =   'Pay Invoice';
               $jv_data['payment'][0]               =   $curr_payment->id;
               $jv_data['generic'][0]               =   $curr_payment->generic_id;
               $jv_data['deposit_no'][0]            =   null;
               $jv_data['deposit_date'][0]          =   null;
               $jv_data['debit_subhead'][0]         =   $debit_account;
               $jv_data['credit_subhead'][0]        =   $credit_account;

               $payment = new Payment;

              $curr_voucher                     = $payment->createVoucher($jv_data);
              $voucher_data['status']           = 'Approve';

              $voucher_data['transaction_id']   = $curr_voucher->id;

              $voucher_data['date']             = $curr_payment->created_at;

              $transaction = new Transaction;

              $approved_voucher = $transaction->updateStatusByTransaction($voucher_data);
                // END


            }

        }
        catch (DecryptException $e)
        {

        }

        return redirect()->back();
    }

    public function updatePayPayment(PaymentRequest $request)
    {
        try
        {
            $form_collect = $request->input();

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

            $payment = new Payment;


            $curr_payment = $payment->updatePayGenericPayment($form_collect);
            
            if (isset($form_collect['role'])) {
                $form_collect['role']          = decrypt($form_collect['role']);
            }


            if($curr_payment->id)
            {
                parent::successMessage('payment has been updated.');

            }

        }
        catch (DecryptException $e)
        {

        }

        return redirect()->back();
    }

    
    
}
