<?php

namespace App\Http\Controllers\Hr;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Http\Requests\LoanRequest;
use App\User;
use App\Loan;
use App\Deduction;
use App\Payment;
use App\Journal;
use App\Transaction;
use App\Contract;
use App\Account;
use EF;
use HR;

class LoanController extends Controller
{
    private $hr_head_list;

    private $hr_account_list;


    public function __construct()
    {


       $this->hr_head_list    = HR::getHrHeadList();

       $this->hr_account_list = HR::getHrAccountList();

    }

    public function index()
    {
        $loan        = new Loan;
        $employee    = new User;
        $journal     = new Journal;
        $contract    = new Contract;
        $account     = new Account;
        $payment     = new Payment;

        $contract_list = $contract->getContractList(['Active']);
        $curr_accounts = $account->getSubheadByType('Bank');


        return view('hr.loan.manage_loan',
            [
                'loan_list'        => $loan->getLoanList(),
                'employee_list'    => $contract_list,
                'payment'          => $payment,
                'curr_accounts'    => $curr_accounts

               
            ]
        );
    }

public function uploadfile($file,$loaded_image = '/graphics/logo/user.png')
  {
      if((isset($file) && trim(strlen($file)) > 0))
      {
          $file =  \EF::uploadFile($file);

      }
      else
      {
          if(strlen(trim($loaded_image)) > 0)
          {
              $file =  $loaded_image;
          }
          else
          {
             $file = '/graphics/logo/user.png';
          }
      }


      return $file;
  }


    public function storeLoan(LoanRequest $request)
    {
        try
        {
           

         $user = new User;
         $loan = new Loan;


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

        $form_collect['loan_form']   = $this->uploadfile($request->loan_form);

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



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

        $previous_loan = $loan->getLoanByUser($curr_user->id);

       if(@count($previous_loan) > 0)
       {

        parent::errorMessage('Loan against '.$curr_user->name.' already exists'); 

        return redirect()->back();

       }

        $curr_loan = $loan->storeLoan($form_collect);

        if (isset($curr_loan->id)) 
        {
           parent::successMessage('loan has been added');   
        }


        }

        }
        catch(DecryptException $e)
        {

        }

        return redirect()->back();

    }

    public function updateLoan(LoanRequest $request)
    {
        try
        {
            $form_collect         = $request->input();
            
            $form_collect['loan'] = decrypt($form_collect['loan']);


            $form_collect['loan_form']   = $this->uploadfile($request->loan_form);
   
            $loan      = new Loan;

            $curr_loan = $loan->updateLoan($form_collect);

            if (isset($curr_loan->id)) 
            {
             parent::successMessage('loan has been updated');   
            }

        }
        catch(DecryptException $e)
        {

        }

        return redirect()->back();
    }

    public function initializeLoan($id)
    {
      if(\Request::ajax())
     {
                $data = '';

        try
        {

           
            $loan_id              = decrypt($id);
            $loan                 = new Loan;
            $deduction            = new Deduction;

            $curr_loan            = $loan->getLoanById($loan_id);

            if(isset($curr_loan->id)) 
            {
              $loan_installments   =  $deduction->getInstallmentsByLoanId($curr_loan->id);

              $data = view('hr.loan.modals.initialize_loan',['loan_installments' => $loan_installments,'loan_id' => $curr_loan->id]);

            }

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


            }

        return redirect()->back();

    }
    public function createLoanVoucher(LoanRequest $request)
    {
        try
        {
            $loan         = new Loan;
            $payment      = new Payment;
            $transaction  = new Transaction;
            $account      = new Account;
            $journal      = new Journal;

            $data = $request->input();



            $loan_id    = decrypt($data['loan']);
            $subhead_id = decrypt($data['drawn_on']);


            $curr_loan    = Loan::find($loan_id);

            $curr_subhead = Account::find($subhead_id);

            $generic_indexes = EF::getGenericTableIndex();

        

            if($data['payment_mode'] == 'Cash')
            {

                $form_collect['drawn'][1]              = null;
                $form_collect['instrument'][1]         = null;
                $form_collect['instrument_date'][1]    = null;

                $form_collect['drawn'][0]              = null;
                $form_collect['instrument'][0]         = null;
                $form_collect['instrument_date'][0]    = null;
                $form_collect['deposit_no']            = null;
                $form_collect['deposit_date']          = null;

                $form_collect['voucher_list']          = "CPV";
                $form_collect['payment_mode'][0]       = "Cash";
                $form_collect['payment_mode'][1]       = "Cash";
                // $form_collect['credit_subhead'][0]     = 4;
                $form_collect['credit_subhead'][0]     = $this->hr_account_list['CIH']; // CASH IN HAND

                

            }
            elseif(isset($curr_subhead->id) && $data['payment_mode'] != 'Cash')
            {
                $form_collect['drawn'][1]              = $curr_subhead->name;
                $form_collect['instrument'][1]         = $data['instrument'];
                $form_collect['instrument_date'][1]    = $data['instrument_date'];

                $form_collect['drawn'][0]              = $curr_subhead->name;
                $form_collect['instrument'][0]         = $data['instrument'];;
                $form_collect['instrument_date'][0]    = $data['instrument_date'];;

                $form_collect['voucher_list']          = "BPV";
                $form_collect['payment_mode'][0]       = $data['payment_mode'];
                $form_collect['payment_mode'][1]       = $data['payment_mode'];
                $form_collect['credit_head'][0]        = $curr_subhead->head_id;
                $form_collect['credit_subhead'][0]     = $curr_subhead->id;
                $form_collect['deposit_no']            = null;
                $form_collect['deposit_date']          = null;

            }

            $form_collect['auto_jv'] = 1;

            $form_collect['receipt'] = NULL;
          



            if(isset($curr_loan->id))
            {
                $user_id = $curr_loan->user->id;

                $branch_id = $curr_loan->user->branch->id;

                $interest_amount = $curr_loan->net_amount-$curr_loan->amount;


                $form_collect['compound_type']         = "General";
                $form_collect['date']                  = now();
                $form_collect['payment_type']          = null;
                $form_collect['booking'][0]            = null;       
                $form_collect['user'][0]               = $user_id;
                $form_collect['branch'][0]             = $branch_id;
                // $form_collect['debit_subhead'][0]      = 8;
                $form_collect['debit_subhead'][0]      = $this->hr_account_list['LR']; // LOAN RECEIVABLE;


                $form_collect['generic_type'][0]      = $generic_indexes['Loan'];

                $form_collect['payment_type'][0]      = 'Loan AutoJV';
                $form_collect['payment'][0]           = 0;

              
         
                $form_collect['narration'][0]          = "Loan amount ".$curr_loan->amount." is approved against employee ". $curr_loan->user->name;
                
                $form_collect['loan_id'][0]            = $curr_loan->id;
                $form_collect['amount'][0]             = $curr_loan->amount; 
                $form_collect['generic'][0]            = $curr_loan->id;

                if($interest_amount > 0) 
                {

                $form_collect['booking'][1]            = null;       
                $form_collect['user'][1]               = $user_id;
                $form_collect['branch'][1]             = $branch_id;
                // $form_collect['debit_subhead'][1]      = 8;
                $form_collect['debit_subhead'][1]      = $this->hr_account_list['LR']; // LOAN RECEIVABLE;

                // $form_collect['credit_subhead'][1]     = 7;
                $form_collect['credit_subhead'][1]     = $this->hr_account_list['IFL']; // LOAN FROM LOAN;

                $form_collect['generic_type'][1]       = $generic_indexes['Loan'];
                $form_collect['payment_type'][1]       = 'Loan AutoJV';
                $form_collect['payment'][1]            = 0;
              
                $form_collect['narration'][1]          = "Interest amount ".$interest_amount." is decided against user ". $curr_loan->user->name;
              
                $form_collect['loan_id'][1]            = $curr_loan->id;
                $form_collect['amount'][1]             = $interest_amount; 
                $form_collect['generic'][1]            = $curr_loan->id;

                }


            $curr_voucher          = $payment->createVoucher($form_collect);

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

                   $voucher_data['status']           = 'Approve';
                   $voucher_data['transaction_id']   = $curr_voucher->id;
                   $voucher_data['date']             = now();


           $approved_voucher = $transaction->updateStatusByTransaction($voucher_data);
                parent::successMessage('Loan has been successfully approved');
            }

            }

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


     public function updateLoanDate(LoanRequest $request)
    {
        try
        {
             
            $form_collect = $request->input();

            $loan      = new Loan;


            foreach($form_collect['installment_id'] as $rows)
            {
                $form_collect['id'][] = decrypt($rows);
            }


            $deduction = new Deduction;

            $loan_id   = decrypt($request->loan_id);

         

            $update_deductions  = $deduction->updateInstallmentsDate($form_collect);

            if($update_deductions == 1)
            {
                  parent::successMessage('Loan has been initialized successfully');  
            }
        }
        catch(DecryptException $e)
        {
           
        }
      

        return redirect()->back();

    }
}
