<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\ContractDetail;
use App\PayrollDetail;

class MinuteSheet 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 getMinuteSheetList()
    {
        return MinuteSheet::where($this->getCondition())->orderBy('id','desc')->get();
    }

        //RETRIEVING MINUTE SHEET BY ID
    public function getMinuteSheetById($id)
    {
      
       $condition = $this->getCondition();
       $condition += ['id' => $id];
        return MinuteSheet::where($condition)->first();

    }

    public function getPreviousSheet($month,$year)
    {
         $condition = $this->getCondition();

         return MinuteSheet::where($condition)->whereMonth('date','=',$month)->whereYear('date','=',$year)->count();

    }

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

            
          $minute_sheet                    = new MinuteSheet;
          $minute_sheet->title             = $object['title'];
          $minute_sheet->date              = $object['date'];
          $minute_sheet->save();

          $this->createMinutePayroll($minute_sheet->id,$minute_sheet->date,$flag = 'false');



            return with($minute_sheet);
          

        });
    }

          public function refreshMinuteSheet($minute_sheet_id)
          {

             return \DB::transaction(function () use ($minute_sheet_id) {

            $minute_sheet = MinuteSheet::find($minute_sheet_id);

           

            if(isset($minute_sheet->id))
            {
          
             $this->createMinutePayroll($minute_sheet->id,$minute_sheet->date,$flag = 'true');

         
                $minute_sheet->refresh_date = now();

                $minute_sheet->update(); 

                return 1;
   
            }

            
            
            return 0;
        });

          }

   
    public function createMinutePayroll($minute_sheet_id,$minute_sheet_date,$flag)
    {

        $month = date('m',strtotime($minute_sheet_date));

        $year  = date('Y',strtotime($minute_sheet_date));

          $contract_detail                 = new ContractDetail;
          $contract                        = new Contract;
          $payroll_detail                  = new PayRollDetail;
          $deduction                       = new Deduction;

          $contract_id_list  = [];

         


          if($flag == 'false')
          {
             $active_contracts                 = $contract->getContractList(['Active']);

             $active_deductions                = $deduction->getDeductionListByDate($month,$year,'=');



          foreach($active_contracts as $rows)
          {

            array_push($contract_id_list,$rows->id);

          }

          $active_contract_details          = $contract_detail->getContractDetailList($contract_id_list);
             
        



          }


          elseif($flag = 'true')
          {
              
              
               $minute_contracts      = $payroll_detail->getDistinctContract($minute_sheet_id,'contract_id',['contract_id']);
               $minute_contracts         = array_map('current', $minute_contracts->toArray());



               $minute_contract_details      = $payroll_detail->getDistinctContract($minute_sheet_id,'contract_detail_id',['contract_detail_id']);
               $minute_contract_details      = array_map('current', $minute_contract_details->toArray());



                $minute_deductions     = $payroll_detail->getDistinctContract($minute_sheet_id,'deduction_id',['deduction_id']);



                $minute_deductions         = array_map('current', $minute_deductions->toArray());



                $active_contracts           =  $contract->getNewContractList(['Active'],$minute_contracts);

                $active_deductions         = $deduction->getNewDeductionList($month,$year,'=',$minute_deductions);


                $new_contract_details       = $contract_detail->getNewContractDetailList($minute_contract_details,$minute_contracts);

           


                

          foreach($active_contracts as $rows)
          {

            array_push($contract_id_list,$rows->id);


          }

          $active_contract_details          = $contract_detail->getContractDetailList($contract_id_list);
             
          $active_contract_details          = $active_contract_details->merge($new_contract_details);

      
          }
          

          
        

        

           $data = array();

           $contract_data = array();


     foreach($active_contracts as $rows)
     {
        
          $contract_data[] =
          [
            'contract_detail_id'  => 0,
            'user_id'             => $rows->user_id,
            'amount'              => $rows->basic_salary,
            'minute_sheet_id'     => $minute_sheet_id,
            'deduction_id'        => '0',
            'contract_id'         => $rows->id,
            'created_at'          => now(),
          ];

     }

        if(@count($contract_data))
        {
            $payroll_detail = new PayrollDetail;

            $payroll_detail->massInsertPayrollDetail($contract_data);

         
        }



     foreach($active_deductions as $rows)
     {
        
          $deduction_data[] =
          [
            'contract_detail_id'  => 0,
            'user_id'             => $rows->loan->user_id,
            'amount'              => $rows->amount,
            'minute_sheet_id'     => $minute_sheet_id,
            'deduction_id'        => $rows->id,
            'contract_id'         => 0,
            'created_at'          => now(),
          ];

     }

        if(@count($deduction_data))
        {
            $payroll_detail = new PayrollDetail;

            $payroll_detail->massInsertPayrollDetail($deduction_data);

         
        }

     foreach($active_contract_details as $rows)
     {

      $contract = new Contract;
      $current_contract = $contract->getContractById($rows->contract_id);

      $basic_salary = $current_contract->basic_salary;

      if($rows->amount == 0)
      {
        $rows->amount = ($rows->percentage/100)*$basic_salary;


      }


        
          $data[] =
          [
            'contract_detail_id'  => $rows->id,
            'user_id'             => $rows->contract->user_id,
            'amount'              => $rows->amount,
            'minute_sheet_id'     => $minute_sheet_id,
            'deduction_id'        => '0',
            'contract_id'         => '0',
            'created_at'          => now(),
          ];

     }


        if(@count($data))
        {
           $payroll_detail = new PayrollDetail;

            $payroll_detail->massInsertPayrollDetail($data);

           
        }

    }



    public function updateMinuteSheet($object)
    {

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

            $minute_sheet = MinuteSheet::find($object['minute_sheet']);

            if(isset($minute_sheet->id))
            {
          
             $minute_sheet->title             = $object['title'];
             $minute_sheet->date              = $object['date'];
             $minute_sheet->update();

                return with($minute_sheet);
                
   
            }
            
            return 0;
        });
    }

    //------------- Foriegn key relashionships -------------- 


    public function getContractList()
    {
        return Contract::where($this->getCondition())->orderBy('id','desc')->get();
    }

       
    //------------- END Foriegn key relashionships ----------- 


}
