<?php
/**
 * Created by PhpStorm.
 * User => sunilkhorwal
 * Date => 2019-05-30
 * Time => 15 =>57
 */

namespace App\Avanse\DataModels;

use App\AvanseCreateCustomer;
use App\AvanseCreateFinance;
use App\AvanseMandate;
use App\ConsumerApplication;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Slack;

class AvanseApproveMandate
{

    private $request;
    public $error = [];

    public function __construct(Request $request)
    {

        $this->request = $request;
    }

    public function getPayload()
    {

        if (!$this->dataInitialize()){
            return false;
        }

        $bankDetails = $this->request->get('bankDetails');

        return [
            "cif" => $this->request->get('cif'),
            "mandateRef" => $this->request->get('mandateRef'),
            "entityCode" => "AFSL",
            "barCodeNumber" => "",
            "finReference" => $this->request->get('finReference'),
            "mandateType" => "NACH",
            "bankCode" => "",
            "branchCode" => "",
            "ifsc" => $bankDetails->ifsc_code,
            "micr" => "",
            "accType" => "11",
            "accNumber" => $bankDetails->account_number,
            "partnerBankId" => "46",
            "accHolderName" => $bankDetails->name,
            "jointAccHolderName" => "",
            "openMandate" => true,
            "startDate" => $this->request->get('startDate'),
            "expiryDate" => $this->request->get('expiryDate'),
            "maxLimit" => $this->request->get('maxLimit'),
            "periodicity" => "M0028",
            "swap" => "true",
            "phoneCountryCode" => 91,
            "phoneAreaCode" => null,
            "phoneNumber" => $this->request->get('phone')
        ];
    }

    public function dataInitialize(){
        $application = ConsumerApplication::with('emi','checkmandate','bank_details')->where('id', $this->request->get('id'))->first();

        if(!$application->avanse && !$application->avanseByApplicant){
            $this->error[] = 'Please create customer for avanse before creating loan';
            return false;
        }

        $avanseFinance = AvanseCreateFinance::where('application_id', $this->request->get('id'))->first(['id', 'finReference']);

        if (!isset($avanseFinance->id)){
            $this->error[] = 'Please create loan for avanse before creating disbursement instruction';
            return false;
        }

        if (!$application->bank_details){
            $this->error[] = 'Please add bank details';
            return false;
        }

        if (!$application->checkmandate){
            $this->error[] = 'Please add mandate details';
            return false;
        }

        $avanseCustomer = AvanseCreateCustomer::where('applicant_id', $application->applicant_id)->first();

        return $this->request->merge([
            'cif' => isset($avanseCustomer->cif) ? $avanseCustomer->cif : '',//$application->avanse ? $application->avanse->cif : ($application->avanseByApplicant ? $application->avanseByApplicant->cif : ''),
            'finReference' => $avanseFinance->finReference,
            'bankDetails' => $application->bank_details,
            'phone' => $application->mobile_number,
            'startDate' => date('c', strtotime($application->checkmandate->date_first_collection)),
            'expiryDate' => $application->checkmandate->expiry_date ? date('c', strtotime($application->checkmandate->expiry_date)) : (date('c', Carbon::parse($application->emi->emi_date)->addMonth($application->emi->remaining_emi)->addYear(1)->timestamp)),
            'maxLimit' => $application->checkmandate->mandate_amount * 100,
            'mandateRef' => $application->checkmandate->umrn,
        ]);
    }

    public function saveResponse(AvanseApproveMandate $avanseApproveMandate, $response){

        if ($response){
            try {

                if (!isset($response->returnStatus->returnCode) || $response->returnStatus->returnCode != '0000'){
                    $avanseApproveMandate->error = isset($response->returnStatus->returnText) ? $response->returnStatus->returnText : 'Avanse: Incomplete data found!';
                    return false;
                }

                $avanse_mandate_id = AvanseMandate::insertGetId([
                    "application_id" => $this->request->get('id'),
                    "applicant_id" => $this->request->get('applicant_id'),
                    "useExisting" => $response->useExisting,
                    "mandateID" => $response->mandateID,
                    "mandateRef" => $response->mandateRef,
                    "openMandate" => $response->openMandate,
                    "status" => $response->status,
                    "partnerBankId" => $response->partnerBankId,
                    "swap" => $response->swap,
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);

                if ($avanse_mandate_id) {
                    $this->request->merge(['avanse_mandate_id' => $avanse_mandate_id]);
                }
                return $avanse_mandate_id;
            }catch (\Exception $exception){
                (new Slack(new Request(['title' => 'Request Error', 'fields' => ['response' => $response, 'request' => json_encode($this->request->all())]])))->send();
                return false;
            }
        }

        return $response;
    }

}
