<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;
use DB;
use Crypt;
use App\Journal;
use App\Deduction;
use App\User;
use App\Payment;
use App\Transaction;
class Loan 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 storeLoan($object)
    {
          
        return DB::transaction(function () use ($object){
        
            $loan                  = new Loan;
            $payment               = new Payment;

            $loan->user_id         = $object['employee'];
            $loan->interest_rate   = $object['interest_rate'];
            $loan->no_of_months    = $object['no_of_months'];
            $loan->amount          = $object['amount'];
            $loan->net_amount      = $object['net_amount'];
            $loan->installment     = $object['installment'];
            $loan->loan_form       = $object['loan_form'];
            $loan->save();

           
        
          
           return with($loan);

        });

    } 

    public function GetReturnedAmountSum($loan_id)
    {
       return DB::transaction(function () use ($loan_id)
       {

          $deduction = new Deduction();

          return $deduction->GetReturnedAmountSum($loan_id);

       });

    }


    // Updating loan modal data

    public function updateLoan($object)
    {
          
        return DB::transaction(function () use ($object){
        
            $loan = Loan::find($object['loan']);

            $journal     = new Journal;
            $transaction = new Transaction;
             
            if(isset($loan->id))
            {

                $curr_amount           = $loan->amount;

                //$loan->user_id         = $object['employee_name'];
                
                $loan->interest_rate   = $object['interest_rate'];

                $loan->no_of_months    = $object['no_of_months'];

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

                $loan->net_amount      = $object['net_amount'];

                $loan->installment     = $object['installment'];
                
                $loan->loan_form       = $object['loan_form'];

                $loan->update();

                $loan_journal_list = $journal->getJournalByLoanId($loan->id);
                if($curr_amount != $loan->amount)
                {
                    foreach( $loan_journal_list as $rows)
                    {
                        if($rows->debit > 0)
                        {
                            $rows->debit = $loan->amount;
                        }
                        if($rows->credit > 0)
                        {
                            $rows->credit = $loan->amount;
                        }

                        $rows->update();

                    }
                }

            if(isset($loan_journal_list[0]->id))
            {
              $transaction_id   = $loan_journal_list[0]->transaction_id;

              $loan_transaction = $transaction->getTransactionById($transaction_id);

              $loan_transaction->total_amount = $loan->amount;

              $loan_transaction->update();

            }

            }

            return with($loan);

        });

    } 


    public function initializeLoanById($id)
    {
          
        return DB::transaction(function () use ($id){
        
            $loan = Loan::find($id);
             
            if(isset($loan->id) && $loan->is_initialize == "0")
            {

               
                for($i= 1; $i<= $loan->no_of_months; $i++)
                {

                    $deduction            = new Deduction;
                    $deduction->user_id   = $loan->user_id;
                    $deduction->loan_id   = $loan->id;
                    $deduction->amount    = $loan->installment;
                    $deduction->title     = "Installment ".$i;
                    $deduction->created_at  = null;
                    $deduction->save();
              
                }

                $loan->is_initialize   = "1";

                $loan->update();
            }

            return with($loan);

        });

    } 

    public function uninitializeLoanById($id)
    {
          
        return DB::transaction(function () use ($id){
        
            $loan      = Loan::find($id);

            $deduction = new Deduction;
             
            if(isset($loan->id))
            {
        
                $loan->is_initialize   = "0";

                $loan->update();

             $installments =  $deduction->getDeductionsByLoan($loan->id);

             foreach($installments as $rows)
             {
                $rows->is_recycle = "1";
                $rows->update();
             }



            }

            return with($loan);

        });

    } 

    public function removeLoanById($id)
    {
          
        return DB::transaction(function () use ($id){
        
            $loan = Loan::find($id);
             
            if(isset($loan->id))
            {       
                $loan->is_recycle   = "1";

                $loan->update();
         
            }

            return with($loan);

        });

    } 


    
     //RETRIEVING loan BY ID
    public function getLoanById($id)
    {
      
       $condition = $this->getCondition();
       $condition += ['id' => $id];
        return Loan::where($condition)->first();

    }

     public function getLoanByUser($user_id)
    {
      
       $condition = $this->getCondition();
       $condition += ['user_id' => $user_id];
        return Loan::where($condition)->first();

    }
    public function getLoanList()
    {
        return Loan::where($this->getCondition())->orderBy('id','desc')->with(['user'])->get();
    }

     // ALL FORIGN KEY RELATIONSHIP FUNCTION
   

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

    


    // END ALL FORIGN KEY RELATIONSHIP FUNCTION
}
