<?php

namespace App\Service;
use App\Models\Payment;
use Auth;
use App\Service\StaticMaster;
use App\Models\User;
use App\Models\AgainstPayment;
use App\Models\Invoice;
use App\Models\Bill;
use Carbon\Carbon;
use Log;

class PaymentEntryService
{

	public function createupdate($request,$transaction){
		
		if(isset($request['entries']) && count($request['entries'])>0){
			foreach ($request['entries'] as $key => $item) {
				$data=[
					'invoice_id',
					'invoice_no',
					'invoice_amount',
					'bill_id',
					'bill_no',
					'bill_amount',
					'balance_amount',
					'amount',
				];

				$obj=[];

				foreach ($data as $key => $value) {
					if(isset($item[$value]) && $item[$value]!=null && $item[$value]!=''){
						$obj[$value]=$item[$value];
						$obj['payment_id']=$transaction['id'];
					}
				}

				// if(isset($item['invoice_id']) && $item['invoice_id']!=0 && $item['invoice_id']!=''){
				// 	$invoice=Invoice::where('id',$item['invoice_id'])->first();
				// 	$invoice['amount_paid']=intval($invoice['amount_paid']) + $item['amount'];
				// 	$invoice->update();
				// }

				// if(isset($item['bill_id']) && $item['bill_id']!=0 && $item['bill_id']!=''){
				// 	$bill=Bill::where('id',$item['bill_id'])->first();
				// 	$bill['amount_paid']=intval($bill['amount_paid']) + $item['amount'];
				// 	$bill->update();
				// }

				$payment_entries=AgainstPayment::create($obj);
			
			}
		}
        

		return true;
	}
	
	public function completerollback($transaction){
		$transaction['rollback']=1;
		$transaction['updatestatus']=1;
		$transaction->update();
		$ledger = LedgerTransactions::where('transactionid',$transaction['id'])->where('rolledback',0)
			->where('updatestatus',0)->first();
		//dd($ledger);
		$ledgerservice = new LedgerService;
		$ledgerservice->rollbackledger1($ledger);
		
		//update against payment records
		$againstService = new AgainstPaymentService;
		$againstService->rollback($transaction['id']);

		$transaction['updatestatus']=0;
		$transaction->update();
	}


	public function createUpdateExpense($expense){
		$obj['transaction_date']=$expense['transaction_date'];
		$obj['userid']=$expense['userid'];
		$obj['customer_id']=$expense['customer_id'];
		$obj['mode']=$expense['mode'];
		$obj['warehouse_id']=$expense['warehouse_id']??0;
		$obj['amount']=$expense['amountwithtax']??0;
		$obj['inout']=2;
		$obj['trantype']=4;
		$obj['paymenttype']=StaticMaster::$EXPENSE_TYPE;
		$obj['fy']=$expense['fy'];
		$obj['reftransaction_id']=$expense['id'];
		$payment=Payment::create($obj);
		return $payment;
	}
	public function rollbackExpensePayment($expense){
		$payment = Payment::where('reftransactionid',$expense['id'])
			->where('paymenttype',StaticMaster::$EXPENSE_TYPE)->first();
		if($payment !=null){
			$payment['rollback']=1;
			$payment->update();
		}
	}
}
