<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Gisplus\Package\EstatechVendor\Models\Invoice;

use App\Commission;
use DB;
use EF;

class Journal extends Model
{
    private $generic_condition;


    public function __construct()
    {

       $this->setCondition(['is_recycle' => '0']);
    }

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

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

    public function isJournalFound($column,$value)
    {
        return Journal::where([$column => $value])->count();
    }

    public function updateJournalWithAmount($id,$amount)
    {
        return \DB::transaction(function () use ($id,$amount)
        {
               $first_journal = Journal::find($id);

               if(isset($first_journal->id))
               {
                  $first_journal->debit = $amount;

                  $first_journal->update();

                  $second_journal = Journal::where('id','>',$id)->where('credit','>',0)->orderBy('id','asc')->first();

                  if(isset($second_journal->id))
                  {
                     $second_journal->credit = $amount;

                     $second_journal->update();
                  }

                  return with(true);
               }

               return with(false);
         });
    }

    // public function isFoundBankOpeningBalance($account_id = [],$narration)
    // {
    //     return  Journal::whereIn('account_id',$account_id)->where($this->getCondition() + ['narration' => $narration])->count();
    // }

    // public function removeBankOpeningBalance($account_id = [],$narration)
    // {
    //     return \DB::transaction(function () use ($account_id,$narration)
    //     {
    //          $journal_list = Journal::whereIn('account_id',$account_id)->where($this->getCondition() + ['narration' => $narration])->get();

    //          foreach ($journal_list as $rows)
    //          {
    //             $rows->is_recycle = "1";

    //             $rows->update();

    //             $transaction = $rows->transaction;

    //             $transaction->status = "Reject";

    //             $transaction->update();
    //          }

    //     });
    // }

    // public function updateBankOpeningBalance($account_id = [],$narration,$openining_balance)
    // {
    //     return \DB::transaction(function () use ($account_id,$narration,$openining_balance)
    //     {
    //          $journal_list = Journal::whereIn('account_id',$account_id)->where($this->getCondition() + ['narration' => $narration])->get();

    //          foreach ($journal_list as $rows)
    //          {
    //             if($rows->debit > 0)
    //             {
    //                 $rows->debit  = $openining_balance;
    //                 $rows->credit = 0;
    //             }
    //             else if($rows->credit > 0)
    //             {
    //                 $rows->debit  = 0;
    //                 $rows->credit = $openining_balance;
    //             }

    //             $rows->update();

    //             $transaction = $rows->transaction;

    //             $transaction->total_amount = $openining_balance;

    //             $transaction->update();
    //          }

    //     });
    // }

    public function isFoundBankOpeningBalance($account_id = [],$narration)
    {
        return  Journal::whereIn('account_id',$account_id)->where($this->getCondition() + ['narration' => $narration])->count();
    }

    public function getJournalAccountBranchWise($id,$branch)
    {
       $condition = $this->getCondition();
       $condition += ['account_id' => $id];
        return Journal::where($condition)->whereIn('branch_id',$branch)->with('transaction')->orderBy('id','asc')->get();
    }

    public function rejectOpeningBalanceVoucher($account_id = [],$narration)
    {
        return \DB::transaction(function () use ($account_id,$narration)
        {

             $journal_list = Journal::whereIn('account_id',$account_id)->where($this->getCondition() + ['narration' => $narration])->get();

             foreach ($journal_list as $rows) {

                 $rows->is_recycle = 1;
                 $rows->update();

                 $transaction = $rows->transaction;

                 $transaction->status = 'Reject';
                 $transaction->is_recycle = 1;


                 $transaction->update();
             }


         });
    }

    
    public function updateBankOpeningBalance($account_id = [],$narration,$openining_balance,$new_account_list)
    {
        return \DB::transaction(function () use ($account_id,$narration,$openining_balance,$new_account_list)
        {

             $journal_list = Journal::whereIn('account_id',$account_id)->where($this->getCondition() + ['narration' => $narration])->get();


             foreach ($journal_list as $rows)
             {
                if($rows->debit > 0)
                {
                    $rows->debit  = $openining_balance;
                    $rows->credit = 0;
                    $rows->account_id = $new_account_list[0];
                }
                else if($rows->credit > 0)
                {
                    $rows->debit  = 0;
                    $rows->credit = $openining_balance;
                    $rows->account_id = $new_account_list[1];

                }

                $rows->update();

                $transaction = $rows->transaction;

                $transaction->total_amount = $openining_balance;

                $transaction->update();
             }

        });
    }

    public function updateJournalAmountByPayment($payment_id,$amount)
    {
         return \DB::transaction(function () use ($payment_id,$amount)
         {
             $journal_list = Journal::where($this->getCondition() + ['payment_id' => $payment_id])->get();

             foreach ($journal_list as $rows)
             {

                if($rows->debit > 0)
                {
                    $rows->debit = $amount;
                    $rows->credit = 0;

                    $invoice = new Invoice;

                    $invoice->updatePaidVendorInvoice($rows->id,$rows->debit);

                }
                else if($rows->credit > 0)
                {
                   $rows->debit = 0;
                    $rows->credit = $amount;
                }

                $rows->update();

                $transaction = $rows->transaction;

                $transaction->total_amount = $amount;

                $transaction->update();
             }


             // $payable_account    = EF::getCommissionAccount();

             // $receivable_account = EF::getReceivableAccount();



             // foreach ($journal_list as $rows)
             // {

             //    if($rows->payment->payment_type === "Commission AutoJV")
             //    {
             //        $account_info = $payable_account;

             //        $debit_account  = $account_info['commission_debit'];

             //        $credit_account = $account_info['commission_credit'];

             //        if($debit_account === $rows->account_id)
             //        {
             //            $rows->debit  = $amount;
             //            $rows->credit = 0;

             //        }
             //        elseif($credit_account === $rows->account_id)
             //        {
             //            $rows->credit  = $amount;
             //            $rows->debit = 0;
             //        }

             //    }
             //    else
             //    {
             //        $account_info = $receivable_account;

             //        $debit_account  = $account_info['receivable_debit'];

             //        $credit_account = $account_info['receivable_credit'];

             //        if($debit_account === $rows->account_id)
             //        {
             //            $rows->debit  = $amount;
             //            $rows->credit = 0;

             //        }
             //        elseif($credit_account === $rows->account_id)
             //        {
             //            $rows->credit  = $amount;
             //            $rows->debit = 0;
             //        }


             //    }


             //    $rows->update();

             //    $transaction = $rows->transaction;

             //    $transaction->total_amount = $amount;

             //    $transaction->update();
             // }
         });
    }

    public function removeJournalAmountByPayment($payment_id)
    {
         return \DB::transaction(function () use ($payment_id)
         {
             $journal_list = Journal::where($this->getCondition() + ['payment_id' => $payment_id])->get();


             foreach ($journal_list as $rows)
             {

                if($rows->debit > 0)
                {
                     $invoice = new Invoice;

                    $invoice->updatePaidVendorInvoice($rows->id,$rows->debit);
                }

                $rows->is_recycle = '1';

                $rows->update();

                $transaction = $rows->transaction;

                $transaction->is_recycle = '1';

                $transaction->status = 'Reject';

                $transaction->update();
             }
         });
    }

    public function getLedgerByUser($condition = [],$from = '',$to = '')
    {
        $condition += $this->getCondition() + ['account_id' => EF::getAccountInfo()['control account']];

        $ledger = Journal::where($condition);

        if(strlen(trim($from)) > 0 && strlen(trim($to)) > 0)
        {
            $ledger = $ledger->whereDate('created_at','>=',$from)->whereDate('created_at','<=',$to);

        }

        $ledger = $ledger->selectRaw('user_id,branch_id,narration,transaction_id, ((journals.debit) - (journals.credit))  as balance, debit,credit,created_at,instrument,mode,instrument_date');

        return $ledger->get();
    }

    public function removeBulkJournal($booking)
    {
        $journal_list =  Journal::where(['booking_id' => $booking])->get();

        foreach ($journal_list as $rows) 
        {
            $payment = $rows->payment;

            $transaction = $rows->transaction;
            
            $payment->status = 'Reject';

            $transaction->status = "Reject";

            if($rows->is_recycle == "0")
            {
                $payment->is_recycle = 1;

                $rows->is_recycle = 1;

                $transaction->is_recycle = 1;

            }


            $payment->update();

            $rows->update();

            $transaction->update();




        }
    }

    public function getGroupUserLedger($condition = [],$from = '',$to = '',$flag = false,$all_vendor_flag = false)
    {
        $groupBy = ['user_id','branch_id','mode','instrument','instrument_date'];

        if($all_vendor_flag == true)
        {
            $groupBy = ['user_id'];
        }

        $account_info = EF::getAccountInfo();

        $condition += ['account_id' => $account_info['control account']];

        $condition += $this->getCondition();
        
        // $ledger = Journal::where($condition);
        $ledger = Journal::where($condition)
            ->groupBy($groupBy)
            ->selectRaw(implode(',',$groupBy).',(sum(journals.debit) - sum(journals.credit))  as balance');

        if(strlen(trim($from)) > 0 && strlen(trim($to)) > 0)
        {
            $ledger = $ledger->whereDate('created_at','>=',$from)->whereDate('created_at','<=',$to);
        }

        return $ledger->get();
    }


    public function getDebitJournal($transaction_id)
    {
        return Journal::where($this->getCondition() + ['transaction_id' => $transaction_id])->orderBy('id','asc')->get();
    }

    public function storeJournal($object,$transaction_id)
    {

         return \DB::transaction(function () use ($object,$transaction_id)  {


            $data = array(

              'booking_id'      => $object['booking_id'],
              'account_id'      => $object['debit_account'],
              'branch_id'       => $object['branch_id'],
              'user_id'         => $object['user_id'],

              // 'loan_id'         => $object['loan_id'],
              // 'payroll_id'      => $object['payroll_id'],
              'transaction_id'  => $transaction_id,
              'debit'           => $object['amount'],
              'credit'          => 0,
              'narration'       => $object['description'],
              'mode'            => $object['mode'],
              'drawn_on'        => $object['drawn_on'],
              'instrument'      => $object['instrument'],
              'instrument_date' => $object['instrument_date'],
              'payment_id'      => $object['id'],
              'created_at'      => $object['created_at'],
              'deposit_no'      => $object['deposit_no'],
              'deposit_date'    => $object['deposit_date'],



            );

            if(isset($object['role'])){

                $data['role_id']         = $object['role'];

                


            }



            Journal::insert($data);

            $data['debit']      = 0;

            $data['credit']     = $object['amount'];

            $data['account_id'] = $object['credit_account'];

            Journal::insert($data);

            
            return with(true);

        });
     }

    public function createAutoJv($transaction_data,$debit_account,$credit_account,$payment_flag = false,$jv_flag = true)
    {

       return \DB::transaction(function () use ($transaction_data,$debit_account,$credit_account)  {


            $payment = new Payment;

            $payment = $payment->payGenericPayment($transaction_data);

            if(isset($payment->id))
            {
                $form_jv['voucher_list']           = 'JV';
                $form_jv['compound_type']          = 'General';
                $form_jv['branch'][0]              = $transaction_data['branch'];
                $form_jv['user'][0]                = $transaction_data['user'];
                $form_jv['booking'][0]             = $transaction_data['booking'];
                $form_jv['amount'][0]              = $transaction_data['amount'];
                $form_jv['narration'][0]           = $transaction_data['description'];
                $form_jv['description'][0]         = $transaction_data['description'];
                $form_jv['payment_type'][0]        = $payment->id;
                $form_jv['payment_mode'][0]        = $transaction_data['mode'] ;
                $form_jv['instrument'][0]          = $transaction_data['instrument'];
                $form_jv['instrument_date'][0]     = $transaction_data['instrument_date'] ;
                $form_jv['drawn'][0]               = $transaction_data['drawn_on'] ;
                $form_jv['debit_subhead'][0]       = $debit_account;
                $form_jv['credit_subhead'][0]      = $credit_account;
                $form_jv['date']                   = $transaction_data['date'];

                $payment = new Payment;

                $curr_transaction = $payment->createVoucher($form_jv);

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

                    $transaction_approval['transaction_id'] = $curr_transaction->id;

                    $transaction_approval['status'] = 'Approve';

                    $transaction_approval['date']   = $transaction_data['date'];

                    $transaction = new Transaction;

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

                }

            }




         });
    }

    public function getVendorPayableLedger($user_id,$branch_id)
    {

        $condition = $this->getCondition() + ['branch_id' => $branch_id,'user_id' => $user_id,'account_id' => EF::getAccountInfo()['control account']];


        $ledger = Journal::where($condition);

        

        $ledger = $ledger->selectRaw('((journals.debit) - (journals.credit))  as balance');


        return $ledger->get()->sum('balance');
    }



     public function updateVoucher($object)
     {

         return DB::transaction(function () use ($object){


            $key = 0;

            $flag = false;

            $transaction = Transaction::find($object[0]['transaction_id']);

            // $this->updateVendorPaidInvoice($transaction);
            

            $transaction->total_amount   = 0;

            $transaction->created_at     = $object[0]['date'];

            $transaction->voucher_type   = $object[0]['voucher'];

            foreach ($object as $rows)
            {
                $journal = Journal::find($rows['id']);

                $payment = new Payment;

                if($journal->debit > 0)
                {
                    $new_payment = $payment->updateVoucherPayment($rows['payment_id'],$journal->payment_id,$rows);
                }


                if(isset($new_payment->id))
                {
                    $journal->payment_id        = $new_payment->id;
                    $journal->user_id           = $new_payment->user_id;
                    $journal->branch_id         = $new_payment->branch_id;
                    $journal->mode              = $new_payment->mode;
                    $journal->drawn_on          = $new_payment->drawn_on;
                    $journal->instrument        = $new_payment->instrument;
                    $journal->instrument_date   = $new_payment->instrument_date;
                    $journal->role_id           = $new_payment->role_id;

                    if($journal->debit > 0)
                    {
                        $journal->debit  = $new_payment->amount;
                        $journal->credit = 0;
                    }
                    else
                    {
                        $journal->credit  = $new_payment->amount;
                        $journal->debit = 0;
                    }
                }
                else
                {
                    if($journal->debit > 0)
                    {
                        $journal->debit  = $rows['amount'];
                        $journal->credit = 0;
                    }
                    else
                    {
                        $journal->credit  = $rows['amount'];
                        $journal->debit = 0;
                    }

                    $journal->booking_id        = $rows['booking_id'];
                    $journal->payment_id        = 0;
                    $journal->user_id           = $rows['user_id'];
                    $journal->branch_id         = $rows['branch_id'];
                    if(isset($rows['role'])){
                        $journal->role_id           = $rows['role'];
                    }
                    $journal->mode              = $rows['mode'];
                    $journal->drawn_on          = $rows['drawn'];
                    $journal->instrument        = $rows['instrument'];
                    $journal->instrument_date   = $rows['instrument_date'];
                }


                $journal->account_id    = $rows['account_id'];
                $journal->narration     = $rows['narration'];

                $journal->deposit_no    = $rows['deposit_no'];
                $journal->deposit_date  = $rows['deposit_date'];
                $journal->created_at    = $rows['date'];

                $journal->update();

                $transaction->total_amount += $journal->debit;
            }

            $transaction->update();

            // $this->updateVendorInvoicePayments($transaction);


            return with($transaction);

         });
     }


     public function getJorunalByTransactionId($id,$column_order = 'id',$order = 'asc')
     {
        $condition = $this->getCondition();
        $condition += ['transaction_id' => $id];

       return Journal::where($condition)->orderBy($column_order,$order)->with(['account','booking','payment'])->get();
     }

      public function getRejectedJorunalByTransactionId($id,$column_order = 'id',$order = 'asc')
     {
        
        $condition = ['transaction_id' => $id];

       return Journal::where($condition)->orderBy($column_order,$order)->with(['account','booking','payment'])->get();
     }


    public function getJorunalByPaymentId($payment_id)
     {
        $condition = $this->getCondition();
        $condition += ['payment_id' => $payment_id];

       return Journal::where($condition)->first();
     }

     //  public function getJournalByLoanId($loan_id)
     // {
     //    $condition = $this->getCondition();
     //    $condition += ['loan_id' => $loan_id];

     //   return Journal::where($condition)->get();
     // }





     public function booking(){
        return $this->belongsTo(Booking::class,'booking_id')->where($this->getCondition())->withDefault();

     }
     public function account(){
        return $this->belongsTo(Account::class,'account_id')->where($this->getCondition())->withDefault(['id' => 0]);

     }
     public function payment(){
        return $this->belongsTo(Payment::class,'payment_id')->where($this->getCondition())->withDefault();

     }

     public function branch(){
        return $this->belongsTo(Branch::class,'branch_id')->withDefault();

     }
     public function getJournalById($journal_id)
     {
         $condition = $this->getCondition();
        return Journal::where($condition)->find($journal_id);
     }

     public function updateJournalByTransaction($id,$object)
     {
            // APPROVE
            $columns = ['updated_at' => date('Y-m-d',strtotime($object['date']))];

            if($object['status'] == "Reject")
            {
                $columns += ['is_recycle' => 1];

            }

            Journal::where('transaction_id',$id)->update($columns);

            $journal = Journal::where('transaction_id',$id)->where('debit','>','0')->get();


            foreach($journal as $rows)
            {
                 $payment = new Payment;
                 $payment->UpdatePaymentByJournal($rows->payment_id,$object);
            }
     }


     public function getJournalByAccountId($id)
     {
        $condition = $this->getCondition();
        $condition += ['account_id' => $id];
         return Journal::where($condition)->with('transaction')->orderBy('id','asc')->get();
     }

     public function getJournalByUserId($id)
     {
        $condition = $this->getCondition();
        $condition += ['user_id' => $id];
         return Journal::where($condition)->with('transaction')->orderBy('id','asc')->get();
     }

     public function transaction(){
        return $this->belongsTo(Transaction::class,'transaction_id')->with('reverseTransaction')->where($this->getCondition())->withDefault();

     }

     public function accounts(){
        return $this->belongsTo(Account::class,'account_id')->with('head')->where($this->getCondition())->withDefault();

     }
     public function user(){
        return $this->belongsTo(User::class,'user_id')->withDefault();

     }
     public function getJournalByAccountIdDistinct($id)
     {
         $condition = $this->getCondition();
        $condition += ['account_id' => $id];
        return Journal::where($condition)->distinct()->get(['transaction_id']);

     }
     public function getJournalByTransactionId($id)
     {
        $condition = $this->getCondition();
        $condition += ['transaction_id' => $id];
        return Journal::where($condition)->first();

     }

     public function getJournalListByTransaction($id)
     {
        $condition = $this->getCondition();
        $condition += ['transaction_id' => $id];
        return Journal::where($condition)->get();

     }

     public function getRejectedJournalListByTransaction($id)
     {
        $condition = [];
        $condition += ['transaction_id' => $id];
        return Journal::where($condition)->get();

     }

     public function getOpeningBalance($from,$account_id)
     {

            $opening_balance = Journal::where('account_id','=',$account_id)->whereDate('created_at','<',$from)->selectRaw('(SUM(debit) - SUM(credit)) AS outstanding')->get();
            return $opening_balance[0]->outstanding;

     }

     public function getClosingBalance($head_condition = [],$account_condition = [])
     {
            $closing_balance = Journal::

            whereHas('accounts',function($query) use ($head_condition,$account_condition){

                $query->whereHas('head',function($query) use ($head_condition){


                   $query->where($this->getCondition() + $head_condition);

                });

                $query->where($this->getCondition() + $account_condition);

            })->whereHas('transaction',function($query){

                $query->whereIn('status',['Approve','Reversal']);

            })->selectRaw('(SUM(debit) - SUM(credit)) AS outstanding')->get();

            if(isset($closing_balance[0]))
            {
                $closing_balance = $closing_balance[0]->outstanding;
            }
            else
            {
                $closing_balance = 0;
            }

            return $closing_balance;
     }
     public function ledgerWiseReport($from,$to,$account_id)
     {
       return Journal::where('account_id',$account_id)

              ->whereDate('created_at','>=',$from)

              ->where($this->getCondition())

              ->whereDate('created_at','<=',$to)

              ->OrderBy('id','asc')

              ->with('transaction')

              ->get();
     }

    public function getTransactionCountByJournal($transaction,$acount_conditon)
    {

        // $condition = $this->getCondition();

        $condition = ['journals.transaction_id' => $transaction];

        $condition += $acount_conditon;


        return Journal::join('accounts','accounts.id','journals.account_id')->join('heads','heads.id','accounts.head_id')->where($condition)->count();
    }

    public function reversalJournal($id,$payment_id,$transaction_id)
    {


         return \DB::transaction(function () use ($id,$payment_id,$transaction_id)  {
            $journal = Journal::find($id);
            $next_jounral_id = Journal::where('id', '>', $journal->id)->min('id');
            $jorunal_data    = Journal::find($next_jounral_id);

            $next_account_id = $jorunal_data->account_id;

            $value=0;
            if($journal->debit>0){
              $value=$journal->debit;
            }
            if($journal->credit>0){
              $value=$journal->credit;
            }

            $journal_debit                    = new Journal;
            $journal_debit->booking_id        = $journal->booking_id;
            $journal_debit->branch_id         = $journal->branch_id;
            $journal_debit->user_id           = $journal->user_id;
            $journal_debit->post_dated        = $journal->post_dated;
            $journal_debit->transaction_id    = $transaction_id;
            $journal_debit->payment_id        = $payment_id;
            $journal_debit->account_id        = $journal->account_id;
            $journal_debit->debit             = 0;
            $journal_debit->credit            = $value;
            $journal_debit->narration         = $journal->narration;
            $journal_debit->mode              = $journal->mode;
            $journal_debit->drawn_on          = $journal->drawn_on;
            $journal_debit->instrument        = $journal->instrument;
            $journal_debit->instrument_date   = $journal->instrument_date;

            $journal_debit->save();

            $journal_credit                    = new Journal;
            $journal_credit->booking_id        = $journal->booking_id;
            $journal_credit->branch_id         = $journal->branch_id;
            $journal_credit->user_id           = $journal->user_id;
            $journal_credit->post_dated        = $journal->post_dated;
            $journal_credit->transaction_id    = $transaction_id;
            $journal_credit->payment_id        = $payment_id;
            $journal_credit->account_id        = $next_account_id;
            $journal_credit->debit             = $value;
            $journal_credit->credit            = 0;
            $journal_credit->narration         = $journal->narration;
            $journal_credit->mode              = $journal->mode;
            $journal_credit->drawn_on          = $journal->drawn_on;
            $journal_credit->instrument        = $journal->instrument;
            $journal_credit->instrument_date   = $journal->instrument_date;

            $journal_credit->save();




            return 1;


        });
     }

    public function accountWiseReport($from,$to,$account_condition = [],$transaction_condition = [], $nature_list = [])
    {
        if(@count($nature_list) == 0)
        {
            $nature_list = \EF::getNatureList();
        }

      return ( Journal::

            whereHas('transaction',function($query) use ($transaction_condition){

             $query->where($transaction_condition);

        })

          ->where($account_condition)

          ->where($this->getCondition())

          ->whereDate('created_at','>=',$from)

          ->whereDate('created_at','<=',$to)

          ->whereHas('accounts',function($query) use ($nature_list){

             $query->whereHas('head',function($query) use ($nature_list){

             $query->whereIn('nature',$nature_list);

          });
             $query->where($this->getCondition());

          })

          ->orderBy('id','asc')->get());


    }

    public function accountReport($from,$to,$account_condition = [],$transaction_condition = [], $nature_list = [])
    {
        if(@count($nature_list) == 0)
        {
            $nature_list = \EF::getNatureList();
        }


      return Journal::

            whereHas('transaction',function($query) use ($transaction_condition){

             $query->where($transaction_condition);

        })

          ->where($account_condition)

          ->where($this->getCondition())

          ->whereDate('created_at','>=',$from)

          ->whereDate('created_at','<=',$to)

          ->whereHas('accounts',function($query) use ($nature_list){

             $query->whereHas('head',function($query) use ($nature_list){

             $query->whereIn('nature',$nature_list);

          });
             $query->where($this->getCondition());

          })

          ->orderBy('id','asc')
          ->get();


    }





    public function trialWiseReport($from,$to,$trial_condition = [])
    {


       return Journal::join('accounts','accounts.id','journals.account_id')

        ->join('heads','heads.id','accounts.head_id')

        ->join('transactions','transactions.id','journals.transaction_id')

        ->whereDate('journals.created_at','>=',$from)

        ->whereDate('journals.created_at','<=',$to)

        ->where($trial_condition)

        // ->where($this->getCondition())

        ->whereIn('transactions.status',['Reversal','Approve'])

        ->groupBy('journals.account_id','accounts.name','accounts.code','heads.name','heads.nature')

        ->selectRaw('journals.account_id,accounts.name,accounts.code,heads.name as head_name,heads.nature,SUM(debit) AS debit,SUM(credit) AS credit')


        ->get();
    }

    public function getNatureWiseReport($from,$to,$status_in = ['Approve','Reversal'])
    {


       return Journal::join('accounts','accounts.id','journals.account_id')

        ->join('heads','heads.id','accounts.head_id')

        ->join('transactions','transactions.id','journals.transaction_id')

        ->whereDate('journals.created_at','>=',$from)

        ->whereDate('journals.created_at','<=',$to)

        ->whereIn('transactions.status',$status_in)

        ->whereIn('transactions.status',['Reversal','Approve'])

        ->groupBy('heads.nature','heads.name')

        ->selectRaw('heads.name,heads.nature,SUM(debit) AS debit,SUM(credit) AS credit')

        ->get();
    }

    public function getVendorBranches($user_id)
    {
        return Journal::where($this->getCondition() + ['user_id' => $user_id])->distinct('branch_id')->with('branch')->get(['branch_id'])->pluck('branch.name')->toArray();
        
    }

    public function getOpeningBalanceListByVendor($user_id)
    {
        return Journal::where('debit','>',0)->where($this->getCondition() + ['user_id' => $user_id , 'role_id' => EF::getRoleIdByName('Vendor') , 'auto_jv' => 1])->orderBy('id','asc')->get();
    }







}
