<?php

namespace App\Http\Controllers\Admin;

use App\QueueLog;
use App\Events\V1\EventAutoDecision;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Logging\CloudWatchLoggerFactory;
use Carbon\Carbon;

class autoBRE {
    private $cloudwatchLogger;

    public function __construct() {
        $this->cloudwatchLogger = new CloudWatchLoggerFactory();
    }

    public function checkDataPoints($id, $request) {
        // skipped category data point since we are checking merchant_id and it is dependent on category_id
        $data_points = ['consumer_application' => ['Name' => 'name', 'Gender' => 'gender', 'Pan Number' => 'pan_card', 'Loan Amount' => 'loan_amount',
        'DOB' => 'dob', 'Permanent Address Line1' => 'permanent_address_line_1', 'Permanent Address City' => 'permanent_address_city',
        'Permanent Address State' => 'permanent_address_state', 'Permanent Address Pincode' => 'permanent_address_pincode',
        'Current Address Line1' => 'current_address_line_1', 'Current Address City' => 'current_address_city',
        'Current Address State' => 'current_address_state', 'Current Address Pincode' => 'current_address_pincode',
        'Mobile Number' => 'mobile_number', 'Monthly Income' => 'monthly_income', 'Merchant' => 'merchant_id', 'Tenure' => 'offer_id',
        'Employee Status' => 'employee_status'],
        'consumer_application_element' => ['KW Installation' => 'inverter_KW_installation',
        'Power Savings' => 'inverter_power_savings']
        ];

        $nullFields = [];

        $consumerApplicationResult = DB::table('consumer_application')
        ->select(array_values($data_points['consumer_application']))
        ->where('id', $id)
        ->first();
        if ($consumerApplicationResult) {
            foreach ($data_points['consumer_application'] as $label => $column) {
                if (is_null($consumerApplicationResult->$column) || $consumerApplicationResult->$column == "" || preg_match('/^[^a-zA-Z0-9]+$/', $consumerApplicationResult->$column)) {
                    $nullFields[] = $column;
                }
            }
        }

        $consumerElementResult = DB::table('consumer_application_element')
        ->select(array_values($data_points['consumer_application_element']))
        ->where('application_id', $id)
        ->first();
        if ($consumerElementResult) {
            foreach ($data_points['consumer_application_element'] as $label => $column) {
                if (is_null($consumerElementResult->$column) || $consumerElementResult->$column == "" || preg_match('/^[^a-zA-Z0-9]+$/', $consumerElementResult->$column)) {
                    $nullFields[] = $column;
                }
            }
        }

        if (!empty($nullFields) && !$request->filled($nullFields)) {
            $this->cloudwatchLogger->logger(json_encode(['application_id' => $id, 'null_fields' => implode(', ', $nullFields)]));
            return false;
        }

        # Check if request param has special char or blank spaces
        foreach ($nullFields as $requestParam) {
            $input = $request->get($requestParam);
            if ((isset($input) && $input == "") || preg_match('/^[^a-zA-Z0-9]+$/', $input)) {
                $this->cloudwatchLogger->logger(json_encode(['application_id' => $id, 'invalid_field' => $requestParam]));
                return false;
            }
        }

        return true;
    }

    public function checkAutoBREStatus($id) {
        try {
            $queueLog = DB::select('select * from queue_log where `input` like "%'.$id.'%" and `input` like "%AutoDecision%" order by created_at desc limit 1');
            if(count($queueLog) > 0) {
                if ($queueLog[0]->job_status == 1) {
                    if ($queueLog[0]->status != 'com' && $queueLog[0]->attempt_count != 1) {
                        $created_at = Carbon::parse($queueLog[0]->created_at);
                        if ($created_at->diffInMinutes(Carbon::now()) > 9) {
                            return response()->json(['status' => 'SUCCESS','autoBRE' => 'not completed','message'=>'Queue not executed since 9 minutes'], 200);
                        }
                        return response()->json(['status' => 'FAIL','autoBRE' => 'in-progress','message'=>'Please wait till Autodecision is complete'], 200);
                    } else if ($queueLog[0]->status == 'com' && $queueLog[0]->attempt_count == 1) {
                        return response()->json(['status' => 'SUCCESS','autoBRE' => 'completed','message'=>'Auto BRE completed'], 200);
                    }
                }
                return response()->json(['status' => 'FAIL','autoBRE' => 'pending','message'=>'Autodecision is pending'], 200);
            }
            return response()->json(['status' => 'SUCCESS','message'=>'Auto BRE not created'], 200);
        } catch (\Exception $e) {
            $this->cloudwatchLogger->logger(json_encode(['application id' => $id, 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
        }
    }

    public function calculateNetLoanAmount($loanAmount, $offer) {
        try {
        $emiCalculation = new \App\EMICalculation();
        $emiCalculation->setLoanAmount((float)$loanAmount)
            ->setNetLoanAmount((float)$loanAmount)
            ->setAdvanceEMI($offer->advance_emi)
            ->setAdvanceType($offer->advance_type)
            ->setTenure($offer->tenure);
        $net_loan_amount = $emiCalculation->netLoanCalculation(true);
        return $net_loan_amount;
        } catch (\Exception $e) {
            $this->cloudwatchLogger->logger(json_encode(['title' => 'net loan amount calculation', 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
        }
    }
}