<?php

namespace App\Http\Controllers\Admin;

use App\EmiPayment;
use App\Http\Controllers\Controller;
use App\Imports\PrePaymentFile;
use App\PaymentTransaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class PrePaymentController extends Controller{

    public $application_id = null;

    public function getEMIAmount($id, $emi_date, $data){
        $emi_payment = EmiPayment::where('application_id', $id)->where('is_pre_part_payment', 1)->where('emi_date', $emi_date)->first(['emi_amount']);
        return $emi_payment->emi_amount ?? $data['emi_amount'];
    }

    public function getPrePayment($id, $date = null){
        $emi_payment = PaymentTransaction::where('application_id', $id);
        if($date){
            $start_date = Carbon::parse($date)->startOfMonth();
            $end_date = Carbon::parse($date)->endOfMonth();
            $emi_payment = $emi_payment->where('payment_date', '>=', $start_date)->where('payment_date', '<=', $end_date);
        }
        $emi_payment = $emi_payment->where('payment_for', 'Pre-Part Payment')->get(['payment_date', 'amount']);
        $pre_payment = [];
        foreach ($emi_payment as $payment) {
            $payment_date = date('Y-m-d', strtotime($payment->payment_date));
            if (!isset($pre_payment[$payment_date])){
                $pre_payment[$payment_date] = 0;
            }
            $pre_payment[date('Y-m-d', strtotime($payment->payment_date))] += $payment->amount;
        }

        return $pre_payment;
    }

    public function getPrincipalOutstanding($id, $emi_date, $current_principal_outstanding){
        $pre_payment = $this->getPrePayment($id, $emi_date);
        if ($pre_payment){
            return array_sum($pre_payment) - $current_principal_outstanding;
        }
        return $current_principal_outstanding;
    }

    public function beforeFileProcessing(Request $request){
        try {
            $prePaymentFile = new PrePaymentFile(new Request());
            $prePaymentFile->application_id = $this->application_id;
            Excel::import($prePaymentFile, $request->file('receipt_ack'));

            if ($prePaymentFile->error) {
                return $prePaymentFile->error;
            }
        }catch (\Exception $e){
            return true;
        }

        return false;
    }
}
