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

namespace App\Avanse\Services\SubService;

use App\Avanse\DataModels\AvanseFinance;
use App\Avanse\Processes\AvanseCreditPolicy;
use App\Avanse\Processes\AvanseProcesses;
use App\Avanse\Services\AvanseServices;
use Illuminate\Http\Request;
use App\Comments;
use App\ApplicationEMICalculation;
use App\CreditReport;
use App\AvanseCreateFinance;
use Illuminate\Support\Facades\Mail;
use App\ConsumerApplication;


class CreateFinance{

    private $request;

    public function __construct(Request $request){
        $this->request = $request;
    }

    public function createFinance(AvanseCreditPolicy $avanseCreditPolicy){
        $avanseFinance = new AvanseFinance($this->request);
        $response = (new AvanseServices($this->request))->createFinance($avanseFinance);
        if ($response){
            if (isset($response->returnStatus)){
                return $response->returnStatus->returnText;
            }
            if ($this->request->get('avanse_finance_id')){
                return $this->request->get('avanse_finance_id');
            }
            return $avanseCreditPolicy->response;
        }

        return $avanseFinance->error;
    }

    /*
        below function is triggered(via queue) when an application is successfully sent to avanse
    */
    public static function postCreateActions($appObj) {

        if ($appObj instanceof ConsumerApplication) {
            if ($appObj->lender_id == ConsumerApplication::AVANSE_LENDER_ID) {
                return self::sendNotificationToAvanse($appObj);
            }
            return true;
        }
        return 'Invalid loan application object';

    }

    public static function sendNotificationToAvanse($appObj) {

        $to = _env('AVANSE_NEW_CASE_EMAIL_TO');
        $cc = _env('AVANSE_NEW_CASE_EMAIL_CC');
        // send email to applicant and co-applicant
        if(!empty($to) || !empty($cc)) {
            //$emiObj = ApplicationEMICalculation::where('application_id', $appObj->id)->first();
            $application = ConsumerApplication::with('advisor','emi','proFormaInvoice','activeOffer')->whereNull('deleted_at')->where('id', $appObj->id)->first();
            $crdObj = CreditReport::where('application_id', $appObj->id)->where('applicant_type', 1)->first();
            $avId = AvanseCreateFinance::getAvanseLoanId($appObj->id);
            $to = explode(',', $to);
            $cc = explode(',', $cc);
            array_push($cc, $application->advisor->email);
            if($application->activeOffer->advance_type == 'emi' && !$application->proFormaInvoice->merchant_collected_advance_amount && $application->emi) {
                $tenure = $application->emi->tenure - $application->emi->advance_emi;
            }else{
                $tenure = $application->emi->tenure;
            }
            $avanseProcesses = new AvanseProcesses(new Request(['id' => $appObj->id]));

            $comments = Comments::with('user')->where('application_id', $appObj->id)->where('type','consumer')->orderBy('created_at','desc')->where('show_avanse', AvanseServices::$lender_id)->get();

            $remark = '';
            foreach($comments as $comment){
                $remark .= $comment->comment."<br/>";
            }

            $data = [
                'id' => $appObj->id,
                'loan_id' => !empty($avId) ? $avId : '',
                'borr_name' => $appObj->name,
                'amount' => round($avanseProcesses->getNetAmountAsPerAvanse()),//$appObj->approved_amount,
                'tenure' => $tenure,//!empty($emiObj->tenure) ? $emiObj->tenure : 0,
                'foir' => $avanseProcesses->getFoirByAvanse($appObj->id),//!empty($crdObj->foirIncludingCFEMI) ? $crdObj->foirIncludingCFEMI : 0,
                'ind_emi' => $application->emi->emi,//!empty($emiObj->emi) ? $emiObj->emi : 0,
                'fast_track' => 'Yes',
                'add_remark' => $remark
            ];
            $id = !empty($avId) ? $avId : '';
            $lid = $appObj->id;
            Mail::send('emails.reminders.basic_reminder', [
                'body' => view('emails.reminders.new_case_avanse', $data),
                //'lender_id' => $appObj->lender_id,
                'is_include_footer' => false
            ], function ($message) use ($to, $cc, $id, $lid) {
                $message->subject('New Loan Application '.$id.' - Credit Fair - '. $lid);
                if(!empty($cc)) {
                    foreach ($cc as $email) {
                        $message->cc($email);
                    }
                }
                if(!empty($to)) {
                    foreach ($to as $email) {
                        $message->to($email);
                    }
                }
            });
        }
        unset($application, $crdObj, $afObj, $appObj, $data);
        return true;
    }
}
