<?php

namespace App\Service;
use DB;
use App\Models\User;
use App\Models\GRNCharge;
use App\Models\Expense;

class GRNChargesService
{

    public function savecharges($request,$transaction){
        
        foreach ($request['charges_type'] as $key => $item) {
            $data=[
                'account_id',
                'vendor_id',
                'amount',
                'remarks',
                'upload_image'
            ];
            
            foreach ($data as $key => $value) {
                if(isset($item[$value]) && $item[$value]!=null && $item[$value]!=''){
                    $obj[$value]=$item[$value];
                    $obj['grn_id']=$transaction['id'];
                }
            }

            $saleItem=GRNCharge::create($obj);
     
        }
        
        return true;
        
    }

    public function chargesApprove($transaction){

        $charge=GRNCharge::where('grn_id',$transaction['id'])
            ->where('rolledback',0)
            ->get();
        
        if(!count($charge) === 0){

            $expense=Expense::where('expense_name','Other Expenses')->first();
            if($expense==null){
                $expense=Expense::create(['expense_name'=>'Other Expenses']);
            }

            // entry charges in Expenses
            foreach ($charge as $key => $item) {

                $obj['expense_head_id']=$expense['id'];
                $obj['description']='The amount of expense and charges incured during GRN';
                $obj['vendor_id']=$item['vendor_id']??0;
                $obj['amount']=$item['amount'];
                $obj['transaction_date']=$transaction['transaction_date'];
                $obj['paid_by']=0;
                $obj['acc_id']=$item['account_id'];
                // $obj['notes']=$request['notes'];
                // $obj['customer_name']=$request['customer_name'];
                // $obj['document']=$request['document'];

                $expense=Expense::create($obj);
            }
        }
    }
}