<?php
/**
 * Created by PhpStorm.
 * User: sunil
 * Date: 28/11/18
 * Time: 12:39 PM
 */

namespace App;


use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Middleware\MongoMiddleware;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Logging\CloudWatchLoggerFactory;
use Illuminate\Support\Facades\DB;
use App\ContentLogger;
use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\Input;
use App\NameMatchService;

class KarzaAPI extends Model
{
    private $endPointDevelopment = '';
    private $karza_key = '';
    private $curl;
    private $payload;
    private $applicationID;
    private $firstInitiate = false;

    protected $table = 'gst_authentication';
    private $env = 'uat';

    public function setup(){
        $this->karza_key = (_env('KARZA_KEY', ''));
        $this->env = env('APP_CONNECTION') == 0 ? 'uat' : 'prod';
        $this->karza_key_aadhaar = env('KARZA_KEY_AADHAAR');
        
    }

    public function getGSTData($id, $gst_number){

        $type = is_array($gst_number) ? $gst_number['type'] : 'merchant_id';
        $gst_number = is_array($gst_number) ? $gst_number['gst_number'] : $gst_number;

        $this->setup();
        $this->endPointDevelopment = 'https://gst.karza.in/prod/v1/gstdetailed';
        if($this->endPointDevelopment && $this->karza_key) {
            $this->payload = json_encode(['gstin' => $gst_number, 'consent' => 'Y']);

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->endPointDevelopment,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $this->payload,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'cache-control: no-cache',
                    'x-karza-key: '. _env('KARZAKEY')
                ),
            ));

            $this->curl = $curl;
            $this->applicationID = $id;

            return $this->saveGSTData($id, $gst_number, $type);

        }

        return false;
    }

    public function saveUtilityValidation($data){
        $response = $this->get();
        // $response = json_decode('{"result":{"bill_no":"016008044213","bill_due_date":"11-07-2025","consumer_number":"60005058502","bill_amount":"Rs.0","bill_issue_date":"","mobile_number":"","amount_payable":"Rs.\u20b912140","total_amount":"","address":"","consumer_name":"Mr. GANESH  .","email_address":"","bill_date":"23-06-2025"},"request_id":"d114fe90-e9b6-4002-9da6-e0ce9212e5d6","status-code":"101"}', 1);
        $consumerElement = DB::selectOne("SELECT cae.inverter_monthly_power_bill, ca.state, ca.updated_by, ca.name, ca.co_applicant_name FROM consumer_application_element cae inner join consumer_application ca on ca.id = cae.application_id where cae.application_id = $data[id]");
        if ($this->firstInitiate && $response && isset($response['status-code']) && $response['status-code'] == 102){
            $ebill_ocr_data = DB::select('SELECT consumer_number FROM ebill_ocr_data WHERE application_id = ? AND consumer_number IS NOT NULL LIMIT 1',[$data['id']]);
            if(isset($ebill_ocr_data[0]->consumer_number) && $ebill_ocr_data[0]->consumer_number){
                ContentLogger::insert([
                        'application_id' => $data['id'],
                        'data' => json_encode(['ebill_customer_id' => ['old'=> $data['customerID'] ?? '','new'=> $ebill_ocr_data[0]->consumer_number]]),
                        'status' => $consumerElement->state,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'user_id' => 107
                ]);

                if(isset($data['file_id'])){
                    DB::update("UPDATE consumer_application_files SET customer_id = ? WHERE id = ?", [$ebill_ocr_data[0]->consumer_number, $data['file_id']]);
                }

                $data['customerID'] = $ebill_ocr_data[0]->consumer_number;
                return $this->utilityValidation($data); // This is for FlowEngine - OCR Data recheck
            }
        }
        
        // fetch the service provider name
        $discomsData = (new ConsumerApplicationController())->getDiscomsData();
        $providerName = $data['provider'];
        foreach ($discomsData['discoms'] as $discom) {
            if ($discom['code'] === $data['provider']) {
                $providerName = $discom['name'];
                break;
            }
        }
        if ($response && isset($response['status-code']) && $response['status-code'] == 101 && isset($response['result']) && $response['result']) {
            $validation = new UtilityValidation();
            $validation->data = json_encode($response);
            $validation->consumer_application_file_id = isset($data['file_id']) ? $data['file_id'] : 0;
            $validation->created_at = Carbon::now()->toDateTimeString();
            $user = Auth::user();
            $validation->user_id = $user->id ?? ($data['user_id'] ?? 0);
            $validation->consumer_application_id = isset($data['id']) ? $data['id'] : 0;
            $validation->save();
            if ($response['result']['bill_amount'] != "") {
                $billAmountStr = str_replace('Rs.', '', $response['result']['bill_amount']);
                $monthlyBill = (int)str_replace([','], '', trim($billAmountStr));
                ContentLogger::insert([
                    'application_id' => $data['id'],
                    'data' => json_encode(['inverter_monthly_power_bill' => ['old'=>isset($consumerElement->inverter_monthly_power_bill) ? $consumerElement->inverter_monthly_power_bill : '','new'=> $monthlyBill]]),
                    'status' => $consumerElement->state,
                    'created_at' => Carbon::now()->toDateTimeString(),
                    'user_id' => 107
                ]);
                DB::update("UPDATE consumer_application_element SET inverter_monthly_power_bill = ?, discom_service_provider = ? WHERE application_id = ?", [$monthlyBill, $providerName, $data['id']]);
            }
            (new ConsumerApplicationController())->generateBillValidation($data, $response['result']);
            \Session::flash('success', 'Successfully validated utility bill');
            return true;
        }
        $errorDisplayMessage = isset($response) && isset($response['status-code']) && $response['status-code'] == 102 ? 'Failed to validate utility bill from vendor - Please check the details' : 'Please connect with tech team';
        \Session::flash('error', $errorDisplayMessage);
        return false;
    }

    public function saveGSTData($id, $gst_number, $type){
        $response = $this->get();
        if (!$id){
            return $response;
        }
        if ($response && isset($response['statusCode']) && $response['statusCode'] == 101 && isset($response['result']) && $response['result']) {
            $this->data = json_encode($response);
            $this->merchant_id = $id;
            $this->gstin = $gst_number;
            $this->type = $type ?? 'merchant_id';
            $this->created_at = Carbon::now()->toDateTimeString();
            $this->user_id = Auth::user()->id;
            $this->save();
            return true;
        }
        return $response;
    }

    public function saveGSTPanData($id, $pan, $type, $user_id){
        $response = $this->get($id, $user_id);
        if (!$id){
            return $response;
        }
        $panReprt = new GSTPANData();
        $panReprt->data = json_encode($response);
        $panReprt->application_id = $id;
        $panReprt->pan = $pan;
        $panReprt->type = $type;
        $panReprt->created_at = Carbon::now()->toDateTimeString();
        $panReprt->user_id = Auth::user()->id ?? 107;

        $panReprt->status_code = isset($response['statusCode']) ? $response['statusCode'] : null;

        if ($response && isset($response['statusCode']) && $response['statusCode'] == 101 && isset($response['result']) && $response['result']) {
            $panReprt->status = 'success';
            $panReprt->save();
            (new ConsumerApplicationController())->generateGSTPANReport($id, $response, $type);
        } else {
            $panReprt->status = 'fail';
            $panReprt->save();
        }
        return $response;
    }

    public function utilityValidation($data){
        if(!$this->firstInitiate){
            $this->firstInitiate = true;
        }else{
            $this->firstInitiate = false;
        }
        $this->setup();
        if(isset($data['BPNumber']) && $data['BPNumber']){
            $this->endPointDevelopment = _env('KARZAURL').'png';
            $this->payload = json_encode(['consumer_id' => $data['customerID'], 'bp_no' => $data['BPNumber'], 'service_provider' => $data['provider'], 'consent' => 'Y']);
        }else{
            if (isset($data['district'])) {
                $this->payload = json_encode(['consumer_id' => $data['customerID'], 'service_provider' => $data['provider'], 'consent' => 'Y', 'district' => $data['district'], 'regMobileNo' => isset($data['mobile_number']) ? $data['mobile_number'] : '']);
            }else {
                $this->payload = json_encode(['consumer_id' => $data['customerID'], 'service_provider' => $data['provider'], 'consent' => 'Y', 'regMobileNo' => isset($data['mobile_number']) ? $data['mobile_number'] : '']);
            }

            $this->endPointDevelopment = _env('KARZAURL').'elec';
        }
        if($this->endPointDevelopment && $this->karza_key) {

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->endPointDevelopment,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $this->payload,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'cache-control: no-cache',
                    'x-karza-key: '. _env('KARZAKEY')
                ),
            ));

            $this->curl = $curl;
            return $this->saveUtilityValidation($data);
        }

        return false;
    }

    public function get($id = 0, $user_id = 0){
        try {
            $response = curl_exec($this->curl);
            if (curl_error($this->curl)) {
                $error = curl_error($this->curl);
            }
            curl_close($this->curl);
            $cwFactory = new CloudWatchLoggerFactory();
            $data = array('application_id'=>$id > 0 ? $id : $this->applicationID, 'user_id'=> $user_id > 0 ? $user_id : (Auth::id() ?? ''), 'vendor'=> 'Karza', 'api_url' => $this->endPointDevelopment,'Request'=> $this->payload ?? '{}', 'Response'=>json_decode($response, 1) ?? '', 'error_msg' => isset($error) ? json_decode($error, 1) : '');
            $cwFactory->logger(json_encode($data));
            if (isset($error)) {
                return false;
            }

            return json_decode($response, 1);

        }catch (\Exception $e){

        }
        return false;
    }

    public function getGSTByPan($id, $pan, $type, $user_id){
        $this->setup();
        $this->endPointDevelopment = 'https://gst.karza.in/'.$this->env.'/v1/search';
        if($this->endPointDevelopment && $this->karza_key) {
            $this->payload = json_encode(['pan' => $pan, 'consent' => 'Y']);

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->endPointDevelopment,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 150,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $this->payload,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'cache-control: no-cache',
                    'x-karza-key: '. _env('KARZAKEY')
                ),
            ));

            $this->curl = $curl;

            return $this->saveGSTPanData($id, $pan, $type, $user_id);

        }

        return false;
    }

    public function getReferenceDetailsFromNumber($reference_mobile_number){
        $this->setup();
        // $this->endPointDevelopment = 'https://api.karza.in/v3/mobile-vpa';
        $this->endPointDevelopment = 'https://testapi.karza.in/v3/mobile-vpa';
        if($this->endPointDevelopment && $this->karza_key_aadhaar) {
            $this->payload = json_encode(['mobileNo' => $reference_mobile_number, 'consent' => 'Y']);

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->endPointDevelopment,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $this->payload,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'cache-control: no-cache',
                    'x-karza-key: ' . _env('KARZA_KEY_AADHAAR')
                ),
            ));
            $response = curl_exec($curl);
            $err = curl_error($curl);
            curl_close($curl);
            if ($err) {
                return "cURL Error #:" . $err;
            } else {
                return json_decode($response, true);
            }
        }
        return false;
    }

    public function checkAadhaarMobileLink($aadhaar, $mobile)
    {
        $this->setup();
        $this->endPointDevelopment = 'https://api.karza.in/v3/aadhaar-mobilelink';
        // $this->endPointDevelopment = 'https://testapi.karza.in/v3/aadhaar-mobilelink';
        if ($this->endPointDevelopment && $this->karza_key_aadhaar) {
            $this->payload = json_encode([
                'aadhaar' => $aadhaar,
                'mobile' => $mobile,
                'consent' => 'Y',
                'clientData' => ['caseId' => null]
            ]);

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->endPointDevelopment,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $this->payload,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'cache-control: no-cache',
                    'x-karza-key: ' . _env('KARZA_KEY_AADHAAR')
                ),
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);
            curl_close($curl);

            if ($err) {
                return "cURL Error #:" . $err;
            } else {
                return json_decode($response, true);
            }
        }

        return false;
    }


    public function karzaTesting(){
        $this->setup();
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://secureapi.karza.in/v2/ssl-test",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode(['request' => 'ssl-test']),
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'cache-control: no-cache',
                'x-karza-key: '. _env('KARZAKEY')
            ),
        ));

        $this->curl = $curl;
        $response = curl_exec($this->curl);
        $error = '';
        if (curl_error($this->curl)) {
            $error = curl_error($this->curl);
        }
        curl_close($this->curl);

        (new Slack(new Request(['title' => 'Karza Testing', 'fields' => ['Response' => json_encode($response), 'error' => json_encode($error)], 'group' => Slack::$STAGE_TESTING])))->send();

    }
}
