<?php
namespace App\Http\Controllers\Hr;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\PayrollRequest;
use Crypt;
use App\Payroll;
use App\PayrollDetail;
use App\MinuteSheet;
use App\Payment;
use App\User;
use App\Account;
use App\Deduction;
use EF;


class PayrollController extends Controller
{
    public function postPayroll(PayrollRequest $request)
    {
        try
        {

            $minute_sheet    = new MinuteSheet;
            $payroll_detail  = new PayrollDetail;
            $payment         = new Payment;
            $user            = new User;
            $payroll         = new Payroll;
            $subhead         = new Account;
            $deduction       = new Deduction;
            $user_payroll    = [];
            
            $form_collect    = $request->input();

       




       //DECRYPTING ID'S

        $form_collect['bank']            = decrypt($form_collect['bank']);
        $form_collect['minute_sheet_id'] = decrypt($form_collect['minute_sheet_id']);
        $form_collect['salary_mode']     = decrypt($form_collect['salary_mode']);



      



        if($form_collect['salary_mode'] == "0")
        {
            parent::errorMessage('Please Select a valid salary mode');

             return redirect()->back();
        }
        else
        {
             
        }



      //RETRIEVING SELECTED BANK ACCOUNT(SUBHEAD)

         $subhead                         = $subhead->getSubHeadById($form_collect['bank']);

      //GETTING MINUTE SHEET BY ID

         $curr_minute_sheet = $minute_sheet->getMinuteSheetById($form_collect['minute_sheet_id']);

     //RELATED CHECKS FOR POSTING PAYROLL

     //CHECKS WHETHER USER HAS SELECTED AN EMPLOYEE TO POST SALARY
        if(@count($form_collect['user_id']) == 0)
         {
             parent::errorMessage('Select a payroll to post');  
             return redirect()->back();
         }

     //CHECKS WHETHER USER HAS SELECTED A VALID BANK
        if(in_array('Cheque',$form_collect['payment_mode']) ||(in_array('Online',$form_collect['payment_mode'])))
        {

            if(!isset($subhead->id))
            {
                       parent::errorMessage('Select valid bank');  
                       return redirect()->back(); 
            }
    
        }

     //CHECKS WHETHER USER HAS ENTERED INSTRUMENT NUMBER IF PAYMENT MODE IS ONLINE

         if(($form_collect['salary_mode'] == 'Online') && isset($subhead->id))
        {

            if($form_collect['instrument_no'] == null)
            {
                 parent::errorMessage('Enter Valid Instrument No.');  
                 return redirect()->back(); 
            }
            else
            {
                $payroll_data['instrument']             = $form_collect['instrument_no'];
                $payroll_data['payment_mode']           = 'Online';
                $payroll_data['drawn']                  = $subhead->bank->bank_name;
                $payroll_data['instrument_date']        = now();
                $payroll_data['deposit_no']             = null;
                $payroll_data['deposit_date']           = null;

               
            }
         }



        if(isset($curr_minute_sheet->id) && @count($form_collect['user_id'] > 0))
        {
            
           //DECRYPTING USER ID'S
        foreach($form_collect['user_id'] as $rows)
        {
          $form_collect['user'][] = decrypt($rows);
        }

         //RETRIEVING USER PAYROLLS ALONG WITH LOAN INSTALLMENTS OF CURRENT PAYROLL

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

            $curr_user = $user->getUserById(($form_collect['user'][$i]));

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

                $user_payroll[$i]    = $payroll_detail->calculateNetSalary($form_collect['user'][$i],$form_collect['minute_sheet_id']);

                $loan_payroll_detail[$i] = $payroll_detail->getUserLoanIdByPayrollDetail($form_collect['user'][$i],$form_collect['minute_sheet_id']);




            if(isset($loan_payroll_detail[$i]->id))
            {

             $deduction_id = $loan_payroll_detail[$i]->deduction_id;

             $curr_deduction = $deduction->getDeductionById($deduction_id);

             if(isset($curr_deduction->id))
             {
                $updated_deduction = $deduction->updateDeductionStatus($curr_deduction->id);
             }


                $payroll_data['loan_id'] = $loan_payroll_detail[$i]->loan_id;
                $payroll_data['count']   = 2;
                $payroll_data['installment_amount'] = $loan_payroll_detail[$i]->installment;
                $payroll_data['loan_amount']   =    $payroll_data['installment_amount'];

            }
            else
            {
                $payroll_data['loan_id']  = 0;
                $payroll_data['count']    = 1;
            }

            if($form_collect['payment_mode'][$i] == 'Cash' && $form_collect['salary_mode'] != 'Online')
            {
                 $payroll_data['payment_mode']           = 'Cash';
                 $payroll_data['drawn']                  = null;
                 $payroll_data['instrument_date']        = null;
                 $payroll_data['instrument']             = null;
                 $payroll_data['deposit_no']             = null;
                 $payroll_data['deposit_date']           = null;
                     
            }
            elseif($form_collect['payment_mode'][$i] == 'Cheque'  &&  $form_collect['salary_mode'] != 'Online')
            {
                 $payroll_data['payment_mode']           = 'Bank';
                 $payroll_data['instrument']             = $form_collect['user_instrument_no'][$i];
                 $payroll_data['drawn']                  = $subhead->bank->bank_name;
                 $payroll_data['instrument_date']        = now();
                 $payroll_data['deposit_no']             = null;
                 $payroll_data['deposit_date']           = null;
        
            }


            if(isset($subhead->id))
            {
                 $payroll_data['head_id']    = $subhead->head_id;
                 $payroll_data['subhead_id'] = $subhead->id;
            }

            
            $payroll_data['net_salary']             = $user_payroll[$i]['net_salary'];
            $payroll_data['tax_id']                 = $user_payroll[$i]['tax_id'];
            $payroll_data['status']                 = 'Pending';
            $payroll_data['minute_id']              = $form_collect['minute_sheet_id'];
            $payroll_data['user_id']                = $form_collect['user'][$i];

          
            $curr_payroll = $payroll->storePayroll($payroll_data);

            }
        }

         parent::successMessage('Payroll has been posted');  

        }
        else
        {
              parent::errorMessage('Something Went Wrong');  
        }

        }
        catch (DecryptException $e) 
        {
            //
        }
        
        return redirect()->back();
    }
}
