<?php

namespace App\Http\Controllers\Hr;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Request;
use App\Http\Requests\PayrollDetailRequest;
use App\Http\Requests\DeductionRequest;
use App\PayrollDetail;
use App\Deduction;
use App\MinuteSheet;
use App\User;
use Crypt;
class PayrollDetailController extends Controller
{
    public function getUserPayRollDetails(Request $request)
    {
       
          if(\Request::ajax())
            {
            	$data = '';

          try
          {

          	  $payroll_detail       = new PayrollDetail;
              $minute_sheet         = new MinuteSheet;
              $user                 = new User;

              $user_id              = decrypt($request->user_id);
              $minute_id            = decrypt($request->minute_id);

              $curr_user            =  $user->getUserById($user_id);
              $curr_minute_sheet    =  $minute_sheet->getMinuteSheetById($minute_id);

              if(isset($curr_user->id) && isset($curr_minute_sheet->id))
              {


              $user_payroll_details = $payroll_detail->getPayrollDetail($user_id,$minute_id);


              $contract_list = [];

              $contract_detail_list = [];

              $deduction_list = [];

              foreach ($user_payroll_details as $rows) 
              {
                if($rows->contract_id > 0 && $rows->contract_detail_id == 0 && $rows->deduction_id == 0)
                {
                    array_push($contract_list,$rows);
                }
                else if($rows->contract_detail_id > 0)
                {
                    array_push($contract_detail_list,$rows);

                }
                else if($rows->deduction_id > 0 && $rows->contract_detail_id == 0)
                {
                    array_push($deduction_list,$rows);
                }
              }

              $date = strtotime($curr_minute_sheet->date);

              $curr_year = date('Y',$date);

              $curr_month = date('M',$date);


              $basic_salary = $payroll_detail->getBasicSalary($user_id,$curr_minute_sheet->id);

              $allowance_sum = $payroll_detail->getAllowanceSum($user_id,$curr_minute_sheet->id);

              $deduction_sum = $payroll_detail->getDeductionSum($user_id,$curr_minute_sheet->id);

              $gross_salary = ($basic_salary + $allowance_sum)-($deduction_sum);

              $non_taxable_allowances = $payroll_detail->getNonTaxableAllowanceSum($user_id,$curr_minute_sheet->id);

              $taxable_amount = $gross_salary - $non_taxable_allowances;

              $tax = $payroll_detail->calculateTax($taxable_amount);

              
              $net_salary = $gross_salary-$tax['monthly_tax_amount'];

              $unique_id =  uniqid();

             $data = view('hr.minute_sheet.modals.update_payroll_detail',['contract_list' => $contract_list,'contract_detail_list' => $contract_detail_list,'curr_year' => $curr_year , 'curr_month' => $curr_month,'deduction_list' => $deduction_list,'minute_id'=> $curr_minute_sheet->id,'user_id' =>  $user_id,'gross_salary' => $gross_salary,'taxable_amount' => $taxable_amount,'net_salary' => $net_salary,'unique_id' => $unique_id,'deduction_sum'=> $deduction_sum,'allowance_sum'=>$allowance_sum]);

              }

          }
          catch (DecryptException $e) 
          {
            
          }
          return $data;


            }

      return redirect()->back();
          
    }



    public function updatePayrollDetail(PayrollDetailRequest $request)
    {
    try
    {
       $payroll_detail = new PayrollDetail;
       $deduction      = new Deduction;
       $user           = new User;
       $minute_sheet   = new MinuteSheet;
            


      $form_collect = $request->input();
      $form_collect['user_id']   = decrypt($form_collect['user_id']);
      $form_collect['minute_id'] = decrypt($form_collect['minute_id']);



      $curr_user            =  $user->getUserById($form_collect['user_id']);
      $curr_minute_sheet    =  $minute_sheet->getMinuteSheetById($form_collect['minute_id']);

   if(isset($curr_user->id) && isset($curr_minute_sheet->id))
   {


    if(@count($form_collect['allowances']) > 0 &&  @count($form_collect['allowances']) == @count($form_collect['allowance_amount']))
     {

        foreach($form_collect['allowances'] as $rows)
        {
          $form_collect['allowance_id'][] = decrypt($rows);
        }

        for($i=0; $i< @count($form_collect['allowance_id']); $i++)
        {
          $update_allowances = $payroll_detail->updatePayrollDetailAmount($form_collect,$form_collect['allowance_id'][$i],$form_collect['allowance_amount'][$i],'contract_detail_id');
        }
 
      }

     if(@count($form_collect['deductions']) > 0 &&  @count($form_collect['deductions']) == @count($form_collect['deduction_amount']))
     {
        foreach($form_collect['deductions'] as $rows)
        {
          $form_collect['deduction_id'][] = decrypt($rows);
        }

        for($i=0; $i< @count($form_collect['deduction_id']); $i++)
        {

          $curr_installment = $deduction->getCurrentInstallment($form_collect['deduction_id']);

          if(isset($curr_installment->id))
          {
             $loan_installments = $deduction->updateLoanInstallments($form_collect['user_id'],$form_collect['deduction_id'],$form_collect['deduction_amount'][$i]);

          if($loan_installments == 0)
          {
            parent::errorMessage('Invalid Deduction Amount');
            return redirect()->back();
          }

          }

         
           $update_deductions = $payroll_detail->updatePayrollDetailAmount($form_collect,$form_collect['deduction_id'][$i],$form_collect['deduction_amount'][$i],'deduction_id');
        }
 
      }

            parent::setLogMessage('Payroll detail has been updated');
            parent::successMessage('Payroll detail has been updated.',parent::getLogMessage());

            if(\Request::ajax())
             {
                return 1;
             }


    }
  }
   catch (DecryptException $e) 
  {
    
  }

      return redirect()->back();
            
     
    }

  public function  storePayrollDeduction(DeductionRequest $request)
  {

  if(\Request::ajax())
   {
  
  try
   {
     $deduction    = new Deduction;
     $user         = new User;
     $minute_sheet = new MinuteSheet;

     $form_collect              = $request->input();
     $form_collect['user_id']   = decrypt($form_collect['user_id']);
     $form_collect['minute_id'] = decrypt($form_collect['minute_id']);

      $curr_user                =  $user->getUserById($form_collect['user_id']);
      $curr_minute_sheet        =  $minute_sheet->getMinuteSheetById($form_collect['minute_id']);

   if(isset($curr_user->id)&&isset($curr_minute_sheet->id))
   {

     if($form_collect['deduction'] != null)
     {

        $form_collect['deduction'] = decrypt($form_collect['deduction']);
        $curr_deduction            = $deduction->getDeductionById($form_collect['deduction']);

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

          $form_collect['deduction'] = $curr_deduction->id;

        }
     }
     else
     {
        $curr_deduction            = $deduction->storeDeduction($form_collect);

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

          $form_collect['deduction'] = $curr_deduction->id;

        }
       
     }

      $payroll_detail_data[] =
          [
            'contract_detail_id'  => 0,
            'user_id'             => $form_collect['user_id'],
            'amount'              => $form_collect['amount'],
            'minute_sheet_id'     => $form_collect['minute_id'],
            'deduction_id'        => $form_collect['deduction'],
            'contract_id'         =>  0,
            'created_at'          => now(),
          ];

        if(@count($payroll_detail_data))
        {

       
            $payroll_detail = new PayrollDetail;

            $payroll_detail->massInsertPayrollDetail($payroll_detail_data);

         
        }
      
      $data  = ['user_id' => Crypt::encrypt($form_collect['user_id']),'minute_id' =>Crypt::encrypt($form_collect['minute_id'])];

     
  }
}

   catch (DecryptException $e) 
          {
            
          }
               return response()->json($data);



        }
}




}
