<?php

namespace App;

use Spatie\Permission\Models\Role;

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

class Commission extends Model
{
  private $generic_condition;
  private $generic_index;



    public function __construct()
    {

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

       $this->generic_index = EF::getGenericTableIndex();
    }

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

        return Commission::where($condition)->update(['is_recycle' => 1]);
    }

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

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

    public function getCommissionsByStatus($booking_id,$status = ['Unpaid'])
    {
        $condition = $this->getCondition();
        $condition  += ['booking_id'=>$booking_id];

       $commissions_list = Commission::where($condition)->whereIn('status',$status)->get();

       return $commissions_list;
    }

    public function salesPersonChart()
    {
      $type = ['Employee'];

      $condition = $this->getCondition();

      $condition += ['commissions.payment_type' => 'Commission'];


        //   return  $users = Commission::join('users', 'users.id', '=', 'commissions.user_id')
        //     ->whereIn('users.type',$type)
        //     ->where($condition)
        //     ->groupBy('commissions.user_id','users.name')


        //     ->selectRaw('commissions.user_id, count(commissions.booking_id) as sales, users.name')->get();

        return  $users = Commission::join('users', 'users.id', '=', 'commissions.user_id')
            // ->join('role_user', 'role_user.user_id', '=', 'commissions.user_id')
            ->join('roles', 'roles.id', '=', 'commissions.role_id')
            ->whereIn('roles.name', $type)
            ->where($condition)
            ->groupBy('commissions.user_id', 'users.name')
            ->selectRaw('commissions.user_id, count(commissions.booking_id) as sales, users.name')->get();
    }

    public function getBookingSalesPerson($booking_id)
    {

         $condition = $this->getCondition();

        $condition += ['booking_id'=>$booking_id ,'payment_type' => 'Commission', 'role_id' => EF::getRoleIdByName('Employee')];

        $booking_salesperson = Commission::where($condition)->get();

       return $booking_salesperson;
    }

     public function storeCommission($object)
    {


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


            $com = new Commission;

            $com->user_id           = $object['user_id'];

            $com->booking_id        = $object['booking_id'];

            // $com->commission_type   = $object['user_type'];

            if (isset($object['role_id'])) {
                $com->role_id           = $object['role_id'];
            }

            $com->payment_type      = $object['payment_type'];

            $com->percentage        = $object['percentage'];

            $com->amount            = $object['amount'];

            $com->received_amount   = NULL;

            $com->description       = $object['description'];

            $com->save();

          //  // CREATE AUTO JV FUNCTION

          //   if($com->payment_type == "Commission")
          //   {
          //       $account_info = EF::getCommissionAccount();

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

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


          //   }
          //   else
          //   {
          //       $account_info = EF::getReceivableAccount();

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

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


          //   }

          //  $jv_data['compound_type']            =  "General";
          //  $jv_data['voucher_list']             =  'JV';
          //  $jv_data['date']                     =  $com->created_at;
          //  $jv_data['auto_jv']                  =  1;
          //  $jv_data['role'][0]                  =  $com->role_id;
          //  $jv_data['receipt']                  =  NULL;
          //  $jv_data['branch'][0]                =  $com->booking->branch->id;
          //  $jv_data['user'][0]                  =  $com->user->id;
          //  $jv_data['booking'][0]               =  $com->booking->id;
          //  $jv_data['amount'][0]                =  $com->amount;
          //  $jv_data['narration'][0]             =  'Auto Jv Against '.$com->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()['Commission'];
          //  $jv_data['payment_type'][0]          =   $com->payment_type.' AutoJV';
          //  $jv_data['payment'][0]               =   0;
          //  $jv_data['generic'][0]               =   $com->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']             = $com->created_at;

          // $transaction = new Transaction;

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


          return with($com);

           // END





        });

    }

    public function removeCommission($id)
    {
        return DB::transaction(function () use ($id) {

            $commission = Commission::find($id);

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

                $commission->update();


               // $payment = new Payment;

               // $payment->removeAutoJvSidePayment($commission->id,$this->generic_index['Commission']);

              return with($commission);
            }

            return 0;
        });
    }



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

            Commission::insert($object);
        });
    }

      public function updateCommission($object,$id)
    {

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

           $commission = Commission::find($id);

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

            $commission->percentage        = $object['percentage'];

            $commission->amount            = $object['updateamount'];

            $commission->description       = $object['description'];

             $commission->update();

             // $payment = new Payment;

             // $payment->updateAutoJvSidePayment($commission->id,$this->generic_index['Commission'],$commission->amount);

             return with($commission);
           }
           else
           {

            return 0;
           }




        });

    }
     public function getCommissionUser($user_id , $booking_id, $role_id =0)
    {

        $condition = $this->getCondition();

        $condition += ['user_id'=>$user_id , 'booking_id'=>$booking_id, 'role_id'   =>  $role_id];

       $user = Commission::where($condition)->first();

       return $user;
    }

    public function getBookingCommissions($booking_id,$status = ['Paid','Unpaid'])
    {
      $condition = $this->getCondition();

      $condition += ['booking_id'=>$booking_id];

      $commissions_list = Commission::where($condition)->whereIn('status',$status)->orderBy('id','desc')->get();

      return $commissions_list;
    }

    public function getCommissionById($id,$column = "*")
    {

      $condition = $this->getCondition();
      $condition += ['id' => $id];

      return Commission::where($condition)->with(['booking'])->select($column)->first();

    }
    public function getBookingDocumentCharges($booking_id)
    {
          $condition = $this->getCondition();
          $condition += ['payment_type' => 'Document Charges', 'booking_id' => $booking_id];
          return Commission::where($condition)->count();
    }

    public function updateCommissionByPayment($id,$new_amount,$old_amount)
    {

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

        $commission = Commission::find($id);

        if(isset($commission->id))
        {
            // FOR REBACK INSTALLMENT
            if($old_amount > 0)
            {
               $commission->received_amount -= $old_amount;
            }
            // FOR NEWER INSTALLMENT
            if($new_amount > 0)
            {
               $commission->received_amount += $new_amount;
            }

            // THIS IF FIND INSALLMENT IS COMPLETED PAID OR NOT
            if($commission->received_amount >= $commission->amount)
            {
                $commission->status = 'Paid';
            }
            else
            {
                $commission->status = 'Unpaid';
            }


            $commission->update();

            return with($commission);
        }

      });
    }



    public function rejectVoucherCommission($payment)
    {
      if(isset($payment)){
          $commission = Commission::find($payment->commission_id);
          if(isset($commission)){
          $commission->received_amount-=$payment->amount;
          if($commission->received_amount < $commission->amount){
            $commission->status = "Unpaid";
          }
          $commission->update();
        }
          return 1;
      }
    }

    public function storeVoucherCommission($payment)
    {
      if(isset($payment)){
          $commission = Commission::find($payment->commission_id);
          if(isset($commission)){
            $commission->received_amount+=$payment->amount;

          if($commission->received_amount < $commission->amount){
            $commission->status = "Unpaid";
          }
          $commission->update();
        }
          return 1;
      }
    }

    public function salesPersonChartBranchwise($branch_ids = [])
    {
      $type = ['Employee'];

      $condition = $this->getCondition();

      $condition += ['commissions.payment_type' => 'Commission'];

        //   return  $users = Commission::join('users', 'users.id', '=', 'commissions.user_id')
        //     ->whereIn('users.type',$type)
        //     ->where($condition)
        //     ->groupBy('commissions.user_id','users.name')


        //     ->selectRaw('commissions.user_id, count(commissions.booking_id) as sales, users.name')->get();

        return  $users = Commission::branchwise($branch_ids)
            ->join('users', 'users.id', '=', 'commissions.user_id')
            // ->join('role_user', 'role_user.user_id', '=', 'commissions.user_id')
            ->join('roles', 'roles.id', '=', 'commissions.role_id')
            ->whereIn('roles.name', $type)
            ->where($condition)
            ->groupBy('commissions.user_id', 'users.name')
            ->selectRaw('commissions.user_id, count(commissions.booking_id) as sales, users.name')->get();
    }

    public function scopeBranchwise($query,$branch_ids)
    {
        if(in_array(0,$branch_ids))
        {
            $branch_ids = Branch::pluck('id')->toArray();
        }




        return $query->whereHas('booking',function($q) use ($branch_ids){

            return $q->whereIn('branch_id',$branch_ids);
        });
    }

       // FORIGN KEY TYPE FUNCTION LIST
    public function user()
    {
        return $this->belongsTo(User::class,'user_id')->withDefault();
    }

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


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


    public function role()
    {
        return $this->belongsTo(Role::class)->withDefault();
    }
    // END FORIGN KEY TYPE FUNCTION LIST
}
