<?php

namespace App\Avanse\Processes;

use App\FinBitData;
use Carbon\Carbon;

class PolicyChecker
{
    protected $request;
    protected $tenorCriteria;
    protected $ageMismatch;
    public $errorBag = [
        'Profile' => false,
        'Income' => false,
        'PAN' => false,
        'EmploymentStability' => false,
        'ResidenceVerification' => false,
        'GeoLimit' => false,
        'WrittenSettled' => false,
        '30+DPD' => false,
        'WilfulDefaulter' => false,
        'Banking' => false,
        'CoApplicantNotRequired' => false,
        'FOIR' => false,
        'Score' => false,
        'Age' => false,
        'Experience' => false,
        'Tenure' => false,
        'EMI' => false,
        'ABB' => false,
        'UNVERIFIED' => false,
        'LOANAMOUNT' => false,
        'CIBIL_ERROR' => false,
    ];
    public $response;
    private $finbit = false;
    private $salarySeen = false;
    private $creditSeen = false;
    private $bounced = false;

    public function __construct(PolicyAttributes $policyAttributes){
        $this->request = $policyAttributes->getAttributes();
    }

    protected function isPANValid(){
        return $this->request->get('is_pan_valid');
    }

    protected function getAge(){
        return (date('Y', strtotime($this->request->get('created_at'))) - date('Y', strtotime($this->request->get('dob'))));
    }

    protected function getAgeAtLastEMI(){
        $last_emi_date = Carbon::now()->addMonths($this->tenorCriteria)->toDateString();
        return (date('Y', strtotime($last_emi_date)) - date('Y', strtotime($this->request->get('dob'))));
    }

    protected function salaryCredited(){
        if($this->request->get('employee_status') == 'SALARIED'){
            if ($this->salarySeen){
                return true; //Salary Credit to be seen in last 3 months Banking
            }
        }elseif(in_array($this->request->get('employee_status'), ['Self Employed - Professional', 'Self Employed - Business'])){
            if ($this->creditSeen){
                return true; // 2 credits every 3 month
            }
        }

        return false;
    }

    protected function residenceVerification(){
        return true;
    }

    private function isCoRequired(){
        if ($this->request->get('is_student')){
            $this->response['co_app_required'] = true;
            return true;
        }else if ($this->ageMismatch){
            $this->response['co_app_required'] = true;
            return true;
        }

        return false;
    }

    protected function isGeoLimit(){
        return true;
    }

    protected function CibilValidations(){
        if (!$this->is30PlusDPD12Month()){ // 30+ DPD in last 12 months not to be done
            $this->errorBag['30+DPD'] = true;
            return false;
        }
        if (!$this->accountValidation()){ // No Account should be Written Off / Settled (Excluding Credit Card with principal write off of less than Rs.7500/-)
            $this->errorBag['WrittenSettled'] = true;
            return false;
        }

        if (!$this->isWilfulDefaulter()){
            $this->errorBag['WilfulDefaulter'] = true;
            return false;//No Account Reported as wilful defaulter
        }

        return true;
    }

    protected function isBanking(){
        if (!$this->bankStatement3Month()){
            $this->errorBag['BankStatement3Month'] = true;
            return false;
        }

        if ($this->bounced){
            $this->errorBag['BankStatement3Month'] = true;
            return false;
        }

        return true;
    }

    private function bankStatement3Month(){
        return false;
    }

    private function is30PlusDPD12Month(){
        return false;
    }

    private function accountValidation(){
        return false;
    }

    private function isWilfulDefaulter(){
        return false;
    }

    protected function checkABB(){

        if (!$this->request->get('abb')){
            return false;
        }
        if (!$this->request->get('emi')){
            $this->errorBag['EMI'] = 'EMI not generated';
            return false;
        }

        if (in_array($this->request->get('employee_status'), ['SALARIED'])){
            if ($this->request->get('cibil_score')['max'] >= -1 && $this->request->get('cibil_score')['max'] <= 10){
                if ($this->request->get('loan_amount') <= 200000){
                    return $this->request->get('abb') >= $this->request->get('emi') ? true : false;//ABB >= 1 EMI
                }
            }else{
                if ($this->request->get('loan_amount') <= 200000){
                    return $this->request->get('abb') >= ($this->request->get('emi')*75)/100 ? true : false;//ABB >= 0.75 EMI*
                }else{
                    return $this->request->get('abb') >= $this->request->get('emi') ? true : false;//ABB >= 1 EMI*
                }
            }
        }elseif(in_array($this->request->get('employee_status'), ['Self Employed - Professional', 'Self Employed - Business'])){
            if ($this->request->get('loan_amount') <= 200000){
                return $this->request->get('abb') >= $this->request->get('emi') ? true : false;//ABB >= 1 EMI
            }else{
                return $this->request->get('abb') >= ($this->request->get('emi') * 2) ? true : false;//ABB >= 2 EMI
            }
        }
    }

    protected function setApprovalResponse(){
        $this->isCoRequired();
        $this->response['documents_to_be_collected'] = [
            'Agreement & photograph',
            'KYC as per KYC policy of Avanse',
            'Last 3 months salary account bank statement / ITR',
            'NACH'
        ];
    }

    private function isMetro(){
        if ($this->request->get('city') && in_array(strtolower($this->request->get('city')), ['mumbai', 'delhi', 'chennai', 'bangalore', 'kolkata', 'hyderabad'])){
            return true;
        }
        return false;
    }

    protected function isFoir(){
        if ($this->isMetro()) {
            if ($this->request->get('foir') == false){
                return false;
            }
            switch ($this->request->get('monthly_income')) {
                case ($this->request->get('monthly_income') >= 15000 && $this->request->get('monthly_income') <= 40000) :
                    return /*$this->request->get('foir') >= 0 && */$this->request->get('foir') <= 50 ? true : false;
                    break;
                case ($this->request->get('monthly_income') >= 40001 && $this->request->get('monthly_income') <= 60000) :
                    return /*$this->request->get('foir') > 50 && */$this->request->get('foir') <= 55 ? true : false;
                    break;
                case ($this->request->get('monthly_income') >= 60001) :
                    return /*$this->request->get('foir') > 55 && */$this->request->get('foir') <= 60 ? true : false;
                    break;
            }
        }else{
            switch ($this->request->get('monthly_income')) {
                case ($this->request->get('monthly_income') >= 15000 && $this->request->get('monthly_income') <= 30000) :
                    return /*$this->request->get('foir') >= 0 && */$this->request->get('foir') <= 50 ? true : false;
                    break;
                case ($this->request->get('monthly_income') >= 30001 && $this->request->get('monthly_income') <= 45000) :
                    return /*$this->request->get('foir') > 50 && */$this->request->get('foir') <= 55 ? true : false;
                    break;
                case ($this->request->get('monthly_income') > 45000) :
                    return /*$this->request->get('foir') > 55 && */$this->request->get('foir') <= 60 ? true : false;
                    break;
            }
        }

        return false;
    }

    protected function loadAdditionalData(){
        $this->finbit = FinBitData::where('application_id', $this->request->get('id'))->get();

        if ($this->finbit){
            $bounce_reported_in_3_months_count = 0;
            $bounce_reported_in_3_months = false;
            foreach ($this->finbit as $finbit){

                if (!$bounce_reported_in_3_months_count) {
                    $bounce_reported_in_3_months_count = 0;
                }

                $from_date = Carbon::createFromFormat('d/m/Y', trim($finbit->period_from));

                $to_date = Carbon::createFromFormat('d/m/Y', trim($finbit->period_too));

                if ($to_date->diffInMonths($from_date) >= 3){
                    if ($finbit->salary){
                        $salary = json_decode($finbit->salary);
                        if ($salary){
                            $this->salarySeen = true;
                        }
                    }

                    if ($finbit->net_credit_txn >= 2){
                        $this->creditSeen = true;
                    }

                    if ($finbit->inwards_bounce_transaction){
                        $bounce_reported_in_3_months = true;
                    }
                }

                if ($bounce_reported_in_3_months && $to_date->diffInMonths($from_date) >= 12){
                    if ($finbit->inwards_bounce_transaction){
                        $bounce_reported_in_3_months_count += $finbit->inwards_bounce_transaction;
                    }
                }
            }

            if ($bounce_reported_in_3_months_count > 2){
                $this->bounced = true;
            }
        }
    }
}



















