<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;
use EF;

class VendorPayment extends Model
{
    private $generic_condition;

    private $generic_index;

    public function __construct()
    {
       $this->setCondition(['is_recycle' => '0']);
      
       $this->generic_index = EF::getGenericTableIndex();

    }

    public function setCondition($condition = [])
    {
        $this->generic_condition = $condition;
    }

    public function getCondition()
    {
        return $this->generic_condition;
    }

    public function getVendorPaymentByVendor($vendor)
    {

    	return VendorPayment::where($this->getCondition() + ['vendor_id' => $vendor])->with(['vendor'])->orderBy('id','asc')->get();
    }

    public function getVendorPaymentById($id)
    {
    	return VendorPayment::find($id);
    }

    public function storeVendorPayment($object)
    {
    	DB::transaction(function () use ($object) {

    		$vendor_payment = new VendorPayment;

    		// $vendor_payment->user_id 	  = $object['user'];
        $vendor_payment->invoice_no       = $object['invoice_no'];
    		$vendor_payment->vendor_id        = $object['vendor'];
    		$vendor_payment->payment_option   = $object['payment_option'];
    		$vendor_payment->description      = $object['description'];
    		$vendor_payment->amount           = $object['amount'];

        if(isset($object['debit_account']))
        {
            $vendor_payment->debit_account_id = $object['debit_account'];
        }
        
        if(isset($object['credit_account']))
        {
            $vendor_payment->credit_account_id = $object['credit_account'];

        }

    		$vendor_payment->save();

        $jv_data['voucher_list']  =  'JV';

        $jv_data['auto_jv']       =  1;

        if($vendor_payment->payment_option === "Pay Now")
        {
            $jv_data['auto_jv']   =  0;

            $account = new Account;

            $account = $account->getAccountById($vendor_payment->credit_account_id);

            if(isset($account->id))
            {
                if($account->type === "Cash")
                {
                    $jv_data['voucher_list']  =  'CPV';
                }
                else if($account->type === "Bank")
                {
                    $jv_data['voucher_list']  =  'BPV';
                }
            }      
        }
      
       $jv_data['compound_type']            =  "General";
       $jv_data['date']                     =  $vendor_payment->created_at;
       $jv_data['receipt']                  =  NULL;
       $jv_data['branch'][0]                =  $vendor_payment->vendor->branch->id;
       $jv_data['user'][0]                  =  NULL;
       $jv_data['booking'][0]               =  NULL;
       $jv_data['amount'][0]                =  $vendor_payment->amount;
       $jv_data['narration'][0]             =  $vendor_payment->description;
       $jv_data['payment_mode'][0]          =   NULL;
       $jv_data['instrument'][0]            =   NULL;
       $jv_data['instrument_date'][0]       =   NULL;
       $jv_data['drawn'][0]                 =   NULL;
       $jv_data['generic_type'][0]          =   EF::getGenericTableIndex()['Vendor Payment'];
       $jv_data['payment_type'][0]          =   'Vendor Payment';
       $jv_data['payment'][0]               =   0;
       $jv_data['generic'][0]               =   $vendor_payment->id;
       $jv_data['deposit_no'][0]            =   null;
       $jv_data['deposit_date'][0]          =   null; 
       $jv_data['debit_subhead'][0]         =   $vendor_payment->debit_account_id; 
       $jv_data['credit_subhead'][0]        =   $vendor_payment->credit_account_id; 

       $payment = new Payment;

      $curr_voucher                     = $payment->createVoucher($jv_data);
          
      if($vendor_payment->payment_option != "Pay Now")
      {
           $voucher_data['status']           = 'Approve';

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

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


          $transaction = new Transaction;

          $approved_voucher = $transaction->updateStatusByTransaction($voucher_data);
      }
      

    		return with($vendor_payment);

		});
    }

    public function updateVendorPayment($object)
    {
        DB::transaction(function () use ($object) 
        {
            $vendor_payment =  VendorPayment::find($object['vendor_payment']);

            if(isset($vendor_payment->id))
            {
                $vendor_payment->invoice_no       = $object['invoice_no'];
                // $vendor_payment->payment_option    = $object['payment_option'];
                $vendor_payment->description      = $object['description'];
                $vendor_payment->amount           = $object['amount'];

                if(isset($object['debit_account']))
                {
                    $vendor_payment->debit_account_id = $object['debit_account'];
                }
                
                if(isset($object['credit_account']))
                {
                    $vendor_payment->credit_account_id = $object['credit_account'];

                }

	    		$vendor_payment->update();

                
                $payment = new Payment;

                $payment_info = [

                    'generic'        => $vendor_payment->id,
                    'generic_type'   => $this->generic_index['Vendor Payment'],
                    'amount'         => $vendor_payment->amount, 
                    'debit_account'  => $vendor_payment->debit_account_id,
                    'credit_account' => $vendor_payment->credit_account_id,

                ];

                $payment->updateAutoJvSidePayment($payment_info);

            }

            

            return with($vendor_payment);

        });
    }

    public function removeVendorPayment($id)
    {
        DB::transaction(function () use ($id) 
        {
            $vendor_payment =  VendorPayment::find($id);

            if(isset($vendor_payment->id))
            {
                $vendor_payment->is_recycle = '1';

                $vendor_payment->update();


               $payment = new Payment;

               $payment->removeAutoJvSidePayment($vendor_payment->id,$this->generic_index['Vendor Payment']);

            }

            return with($vendor_payment);

        });
    }

    public function updateVenderPaymentById($id,$new_amount,$old_amount)
    {
     
        return \DB::transaction(function () use ($id,$new_amount,$old_amount)  {

        $vender_payment = VendorPayment::find($id);

        if(isset($vender_payment->id))
        {
            // FOR REBACK INSTALLMENT
            if($old_amount > 0)
            {
               $vender_payment->received_amount -= $old_amount;
            }
            // FOR NEWER INSTALLMENT
            if($new_amount > 0)
            {
               $vender_payment->received_amount += $new_amount;
            }
          
            // THIS IF FIND INSALLMENT IS COMPLETED PAID OR NOT
            if($vender_payment->received_amount >= $vender_payment->amount)
            {
                $vender_payment->status = 'Paid';
            }
            else
            {
                $vender_payment->status = 'Unpaid';
            }

            
            $vender_payment->update();

            return with($vender_payment);
        }

      });
    }

 

    public function vendor()
    {
        return $this->belongsTo(Vendor::class,'vendor_id')->where($this->getCondition())->withDefault();
        
    }

    public function debitAccount()
    {
        return $this->belongsTo(Account::class,'debit_account_id')->with('head')->withDefault();
    }

     public function creditAccount()
    {
        return $this->belongsTo(Account::class,'credit_account_id')->with('head')->withDefault();
    }
}
