<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Carbon;
use App\Models\User;
use App\Models\UserCharge;
use App\Models\UserIp;
use App\Models\UserTransaction;
use App\Models\PayoutModel;
use App\Models\ApiLog;

class PayoutIserveU extends Controller
{
    public function doPayout(Request $request)
    {
        die("not allowed");
        $jsonData = $request->json()->all();        
        $Authorization = $request->header('Authorization');

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'accountNumber' => 'required',
            'bankIfsc' => 'required',
            'mobileNumber' => 'required',
            'beneBankName' => 'required',
            'referenceNumber' => 'required|unique:payout_transactions,orderId',
            'transferAmount' => 'required',
            'transferMode' => 'required',
        ]);

        if($validator->fails()) {
            $responseData = [                
                'status' => FALSE,
                'error'=> TRUE,
                'message' => $validator->errors(),
            ];
            return response()->json($responseData, 422);
        }

        $getUser = User::where("user_token",$Authorization)->where("status",1)->where("user_type",1)->first();
        if(empty($getUser)){
            $responseData = [                
                'status' => FALSE,
                'error'=> TRUE,
                'message' => 'Invalid credentials',
            ];
            return response()->json($responseData , 401);
        }
        $userId = $getUser->id;
        $api_status = $getUser->api_status;
        if($api_status == 0){
            $responseData = [                
                'status' => FALSE,
                'error'=> TRUE,
                'message' => 'We are taking downtime due to some technical issues. Please wait till further update',
            ];
            return response()->json($responseData , 200);die;
        }
        $bank_deactive = $getUser->bank_deactive;
        if($bank_deactive == 1){
            $responseData = [                
                'status' => FALSE,
                'error'=> TRUE,
                'message' => 'Your API has been Deactivated by the Bank due to security reasons.',
            ];
            return response()->json($responseData , 200);die;
        }
        $tecnical_issue = $getUser->tecnical_issue;
        if($tecnical_issue == 1){
            $responseData = [                
                'status' => FALSE,
                'error'=> TRUE,
                'message' => 'We are facing technical issue from bank side.',
            ];
            return response()->json($responseData , 200);die;
        }

        $iserveu = $getUser->iserveu;
        if($iserveu != 1){
            $responseData = [                
                'status' => FALSE,
                'error'=> TRUE,
                'message' => 'This service is not active at this time. please use ICICI bank api.',
            ];
            return response()->json($responseData , 200);die;
        }

        $ipAddress = $request->ip();
        $checkIp = UserIp::where(['userId'=>$userId,'ipAddress'=>$ipAddress])->first();
        if(empty($checkIp)){
            $responseData = [                
                'status' => FALSE,
                'error'=> TRUE,
                'message' => 'your ip is not whitlisted, requested ip is '.$ipAddress,
            ];
            return response()->json($responseData , 401);
        }

        $txn_id = "SSPY".rand(123121,990999).Carbon::now()->timestamp;
        $name = $request['name'];
        $accountNumber = $request['accountNumber'];
        $bankIfsc = $request['bankIfsc'];
        $mobileNumber = $request['mobileNumber'];
        $beneBankName = $request['beneBankName'];
        $referenceNumber = $request['referenceNumber'];
        $transferAmount = $request['transferAmount'];
        $transferMode = $request['transferMode'];

        $getCommission = UserCharge::where('start_amount', '<=', $transferAmount)->where('end_amount', '>=', $transferAmount)->where('userId', '=', $userId)->first();
        if(empty($getCommission)){
            $charge = 20;
            $chargeType = "F";
        }else{
            $charge = $getCommission->payout_charge;
            $chargeType = $getCommission->payout_charge_type;
        }
        $gst = 18;
        if($chargeType == "F"){
            $totalCharge = $charge;
            $totalGst = ($totalCharge*$gst)/100;
        }else if($chargeType == "P"){
            $totalCharge = ($Amount*$charge)/100;
            $totalGst = ($totalCharge*$gst)/100;
        }
        $totalDeductAmount = $transferAmount +$totalCharge+$totalGst;
        $openBal = $getUser->wallet;
        $lien =$getUser->lien;
        $rolling_reserve = $getUser->rolling_reserve;
        $closeBal = $openBal - $totalDeductAmount;                    
        $checkAmount = $totalDeductAmount+$lien+$rolling_reserve;

        if($openBal == 0 || $openBal < $checkAmount){           
            $responseData = [                
                'status' => FALSE,
                'error'=> TRUE,
                'message' => 'Insufficient fund',
            ];
            return response()->json($responseData , 200);
        }
        
        $UserInstance = new User();
        $UserInstance->deductFund($userId,$totalDeductAmount);

        $remark = "Money Transfer Via Payout ";
        UserTransaction::create([
            'userId' => $userId,
            'txnId' => $txn_id,
            'orderId' => $referenceNumber,
            'type' => "DEBIT",  
            'operator' => "PAYOUT",
            'openBalance' =>$openBal, 
            'amount' => $totalDeductAmount,
            'walletBalance' =>$closeBal,
            'credit' =>0, 
            'debit' =>$totalDeductAmount,
            "status" => "PENDING",
            'remark' => $remark,   
            'api'=>"ISERVEU",
            'requestIp' => $ipAddress,          
            'created_by' => $userId,
        ]);

        PayoutModel::create([
            'userId' => $userId,
            'txnId' => $txn_id,
            'orderId' => $referenceNumber,
            'amount' => $transferAmount,
            'charge' =>$totalCharge,   
            'gst'=>$totalGst,
            'totalAmount' => $totalDeductAmount,   
            'mode'=>$transferMode,
            'beneName' => $name,          
            'beneBank' => $beneBankName,
            'beneAccount' => $accountNumber,   
            'beneIfsc' => $bankIfsc,          
            'status' => "PENDING",
            'api'=>"ISERVEU",
            'IpAddress' => $ipAddress,
        ]);

        $pincode = "201310";
        $customerName = $getUser->name;
        $customerMobileNumber = $getUser->mobile;
        $latitude = 19.0748;
        $longitude = 72.8856;        

        //$ISERVEU_CLIENT_ID = "8a2d0eb01b53fa2ae4c2a2f1f0f1b7278058778345346dba11b175ce6fb5e8853b6557c0c03eee674cfae0aaf5c60118";
        //$ISERVEU_CLIENT_SECRET = "62cbc2f6c99b8e10393ba98458629319a8fe92da8bc3a9a0dee1156a1011010ddc2cbcb74472ace6d9708a60324f33d07ccfacef94ff27656dfbc6a007dfd196";
        
        
        
        $ISERVEU_CLIENT_ID = "4a0bd19f05f4a07cceb56492c37c30608c9fa2bfd3c460a945f7923e2c3a03bf1467f68f5b64886c6b4f3a9be195e265";
        $ISERVEU_CLIENT_SECRET = "a5f2e7e906b86c7fb08d53ce0f9d31391fd5eeaeb34f9b801ed804bbccf4a7f79c80da880c3784f7ce894f156a3cf239e368752ad9bc0777f70cbf9eb1f1d0f5";

        $header = array(
            'Content-Type:application/json',
            'client_id: ' . $ISERVEU_CLIENT_ID,
            'client_secret: ' . $ISERVEU_CLIENT_SECRET
        );

        $request = [
            "beneName" => $name,
            "beneAccountNo" => $accountNumber,
            "beneifsc" => $bankIfsc,
            "benePhoneNo" => (int)$mobileNumber,
            "beneBankName" => $beneBankName,
            "clientReferenceNo" => $txn_id,
            "amount" => (float)$transferAmount,
            "fundTransferType" => $transferMode,
            "pincode" => (int)$pincode,
            "custName" => $customerName,
            "custMobNo" => $customerMobileNumber,
            "custIpAddress" => $ipAddress,
            "latlong" => $latitude . ',' . $longitude
        ];

        $payload1 = json_encode($request);

        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => "https://apigatewayprod.iserveu.tech/w1w2-payout/w1/cashtransfer",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => $header
        ]);

        //$response = curl_exec($curl);
        //$response = '{"transactionId":275424305152050,"subStatus":0,"status":"SUCCESS","statusDesc":"CO00 - Transaction is Successful.","beneName":"AJAY SHARMA SO BAL KRISHAN  SHARMA","beneAccountNo":"0240040150000474","beneifsc":"JAKA0CHNDAR","benePhoneNo":"9008770493","beneBankName":"JAKA","clientReferenceNo":"301253949604","latlong":"19.0748,72.8856","pincode":"141001","custName":"G K","custMobNo":"9988894793","rrn":"324016072167","paramA":"","paramB":"","dateTime":"08-28-2023 04:24:36","txnAmount":475,"txnType":"IMPS"}';
        $err = curl_error($curl);
        curl_close($curl);

        ApiLog::create([
            'txnId' => $txn_id,
            'request' => $payload,
            'response' => $response,  
            'service' => "PAYOUT",
            'service_api' =>"ISERVEU",   
        ]);

        $responseData = json_decode($response, true);                    
        $status = $responseData['status'];
        $statuscode = $responseData['subStatus'];
        $statusMessage = $responseData['statusDesc'];
        $transactionId = $responseData['transactionId'];        
        $clientReferenceNo = $responseData['clientReferenceNo'];

        

        if($statuscode == "-1" ||$statuscode == "2" ||$statuscode == "-2" || $status == "FAILED"){

            $updateUser = [
                'walletBalance' =>$openBal,
                'status' => "FAILED"
            ];  

            $UserTransaction = new UserTransaction();      
            $UserTransaction->updateUserTxnData($updateUser,$txn_id);

            $updatePayout = [
                "contactId"=>$transactionId,                
                "status"=>"FAILED",
                "remark"=>$statusMessage
            ];                  
            $PayoutModel = new PayoutModel();      
            $PayoutModel->updatePayoutData($updatePayout,$txn_id);

            //$user = User::findOrFail($userId);
            $UserInstance = new User();
            $UserInstance->addFund($userId,$totalDeductAmount);

            $responseData = [
                "status" => "FAILED",
                "message" => $statusMessage,
                "data" => array(
                    "payout_ref" => $referenceNumber,
                    "txn_id" => $txn_id,
                    "bank_ref" => ""
                ),
            ];
            return response()->json($responseData , 200);
            die;
        }

        if($statuscode == "0" && $status == "SUCCESS") {
            $rrn = $responseData['rrn'];

            $updateUser = [
                'status' => "SUCCESS"
            ];  

            $UserTransaction = new UserTransaction();      
            $UserTransaction->updateUserTxnData($updateUser,$txn_id);

            $updatePayout = [
                "contactId"=>$transactionId,
                "utr"=>$rrn,
                "status"=>"SUCCESS",
                "remark"=>$statusMessage
            ];                  
            $PayoutModel = new PayoutModel();      
            $PayoutModel->updatePayoutData($updatePayout,$txn_id);

            $responseData = [
                "status" => "SUCCESS",
                "message" => $statusMessage,
                "data" => array(
                    "payout_ref" => $referenceNumber,
                    "txn_id" => $txn_id,
                    "bank_ref" => $rrn
                ),
            ];
            return response()->json($responseData , 200);
            die;
        }

        $responseData = [
            "status" => "PENDING",
            "message" => "Transaction is under process",
            "data" => array(
                "payout_ref" => $referenceNumber,
                "txn_id" => $txn_id,
                "bank_ref" => ""
            ),
        ];
        return response()->json($responseData , 200);
        die;
    }
}
