<?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\PayinModel;
use App\Models\ApiLog;

class PayintIserveU extends Controller
{
    public function genratePaymentLink(Request $request)
    {
        $jsonData = $request->json()->all();        
        $Authorization = $request->header('Authorization');

        $validator = Validator::make($request->all(), [
            'name' => 'required',           
            'referenceNumber' => 'required|unique:payin_transactions,orderId',
            'phone' => 'required',
            'email' => 'required',
            'amount' => '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;
        }

        $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 = "SEOS".rand(123121,990999).Carbon::now()->timestamp;
        $Name = $request['name'];
        $ReferenceId = $request['referenceNumber'];
        $Email = $request['email'];
        $Phone = $request['phone'];
        $Amount = $request['amount'];
        $PaymentMode = "INTENT";//$this->request->getVar('PaymentMode');

        $ISERVEU_CLIENT_ID = "42Zuw71Ok7e2TGAgHPKttM7PFGMspJLLy3ewq15dhgjtGM9l";
        $ISERVEU_CLIENT_SECRET = "MDB9krmA8OqYdgjTKflkXXU7BTNAJgVDEWBmhWjQ8YBvAPNKNPLbxnJGSKcKiEV9";

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

        $request = [
            "virtualAddress" => "7682961933@ybl",
            "paymentMode" => $PaymentMode,
            "isWalletTopUp" => false,
            "amount" => $Amount,
            "channelId" => "WEBUSER",
            "remarks" => "Upi",
            "clientRefId" => $txn_id,
            "merchantType" => "AGGREGATE",
            "requestingUserName" =>"mappsink",
        ];

        $payload = json_encode($request);

            $curl = curl_init();
            $url = "https://apiprod.iserveu.tech/productionV2/api/upi/initiate-dynamic-transaction";

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            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);
        $err = curl_error($curl);
        curl_close($curl);

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

        $responseData = json_decode($response, true);   

    }
    
     
    public function genrateQR(Request $request)
    {
        $jsonData = $request->json()->all();        
        // $Authorization = $request->header('Authorization');

    
        $validator = Validator::make($request->all(), [
        'amount' => 'required|regex:/^\d+(\.\d{1,2})?$/',
        'remark' => 'nullable|max:50',
        'orderId' => 'required',
        'expireAfter' => 'required|integer|min:5|max:32400', 
        ]);

        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();
        $getUser = User::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;
        }

        // $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);
        // }

        //$orderId = "SEOS".rand(123121,990999).Carbon::now()->timestamp;
        $amount = $request['amount'];
        $remark = $request['remark'];
        $orderId = $request['orderId'];
        $expireAfter = $request['expireAfter'];
        
    //  $orderId ="SEOS".rand(123121,990999).Carbon::now()->timestamp;
    

        $CLIENT_ID = "735400e1-6cd6-40ea-8a0e-87471eb2cda7";
        $CLIENT_SECRET = "7feed092-803b-42f9-97a7-a98c209b176a";

        $header = array(
            'Content-Type:application/json',
            'program_id: ' . $CLIENT_ID,
            'client_secret: ' . $CLIENT_SECRET
        );

        $request = [
            
            "amount" => $amount,
            "remark" => $remark,
           "orderId"=>  $orderId ,
           "expireAfter"=>$expireAfter,
        ];

        $payload = json_encode($request);

           
        
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://collectbot.neokred.tech/payin/fn/api/v1/external/upi/qr/generate',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>$payload,
  CURLOPT_HTTPHEADER =>$header
));

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


    

        ApiLog::create([
            'txnId' => $orderId,
            'request' => $payload,
            'response' => $response,  
            'service' => "PAYIN",
            'service_api' =>"Neokred",   
        ]);

       
        $responseData = json_decode($response, true);

        $transactionId = null;
        $status = null;
        if (isset($responseData['data']['transaction_id'])) {
            $transactionId = $responseData['data']['transaction_id'];
        }
        if (isset($responseData['data']['txnStatus'])) {
            $status = $responseData['data']['txnStatus'];
        }

    // $transactionId = $responseData['transaction_id'];
    // $status = $responseData['txnStatus'];

        PayinModel::create([
            'userId'=> $userId,
            'txnId' =>  $transactionId,
            'status'=> $status,
            'orderId' => $orderId,

            
        ]);
        return response()->json($responseData);

    }
    
     
    public function callback(Request $request) {
        $jsonData = $request->json()->all();
    
        if(empty($jsonData)){
            return response()->json(['status' => 1, 'statusDesc' => 'Failure']);
        }
    
    
      if(!isset($jsonData['transactionId'])) {
        return response()->json([
            'status' => false,
            'error' => true,
            'message' => 'Transaction ID not found in JSON data.',
        ]);
    }
        // ApiLog::create([
        //     'txnId' => "",
        //     'request' =>"",
        //     'response' => json_encode($jsonData),
        //     'service' => "CALLBACK",
        //     'service_api' => "Testing",   
        // ]);
    
        $ClientRefID = $jsonData['transactionId'];
    
        $existingTransaction = PayinModel::where('txnId', $ClientRefID)->first();
    
        if (!$existingTransaction) {
            return response()->json([
                'status' => false,
                'error' => true,
                'message' => 'Transaction not found.',
            ]);
        }
    
        // Update the existing transaction data based on the provided transaction_id
        $existingTransaction->update([
            'upiId' => $jsonData['upiId'],
            'amount' => $jsonData['amount'],
            'mcc' => $jsonData['mcc'],
            'payerName' => $jsonData['customerName'],
            'utr' => $jsonData['custRefNo'],
            'upiTxnId' => $jsonData['upiTxnId'],
             'txnId' => $jsonData['transactionId'],
            'orderId' => $jsonData['orderId'],
            'status' => $jsonData['txnStatus'],
            'txn_time' => $jsonData['txnTime'],
        ]);
    
        // Return a success response
        return response()->json(['result' => 'ok']);
    }
    
    
    // public function checknewstatus(Request $request)
    // {
    //     $jsonData = $request->json()->all();
       
        
    //     $validator = Validator::make($request->all(), [
    //         'transactionId' => 'required',            
    //     ]);
    
    
    //     $transactionId = $jsonData['transactionId'];
    
    //     $getUser = User::where("status",1)->where("user_type",1)->first();
    //     if(empty($getUser)){
    //         $responseData = [                
    //             'status' => FALSE,
    //             'error'=> TRUE,
    //             'message' => 'Invalid credentials.',
    //         ];
    //         return response()->json($responseData , 401); die;
    //     }
    
    //     $userId = $getUser->id;
    //     // $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);
    //     // }
    //     $transactionId = $request['transactionId'];
    //     $checkTxn = PayinModel::where("txnId",$transactionId)->where("userId",$userId)->get()->toArray();
    //     if(count($checkTxn) == 0){
    //         $responseData = [                
    //             'status' => FALSE,
    //             'error'=> TRUE,
    //             'message' => 'Transaction not found.',
    //         ];
    //         return response()->json($responseData , 200); die;
    //     }
    
    
    //     $CLIENT_ID = "735400e1-6cd6-40ea-8a0e-87471eb2cda7";
    //     $CLIENT_SECRET = "7feed092-803b-42f9-97a7-a98c209b176a";
    
    //     $header = [
    //         'Content-Type: application/json',
    //         'client_secret: ' . $CLIENT_SECRET,
    //         'client_id: ' . $CLIENT_ID,
    //     ];
    
    //     $payload = json_encode(['transactionId' => $transactionId]);
    
    //     $curl = curl_init();
    
    //     curl_setopt_array($curl, [
    //         CURLOPT_URL => 'https://collectbot.neokred.tech/payin/fn/api/v1/external/upi/qr/status',
    //         CURLOPT_RETURNTRANSFER => true,
    //         CURLOPT_ENCODING => "",
    //         CURLOPT_MAXREDIRS => 10,
    //         CURLOPT_TIMEOUT => 30,
    //         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    //         CURLOPT_CUSTOMREQUEST => "POST",
    //         CURLOPT_POSTFIELDS => $payload,
    //         CURLOPT_HTTPHEADER => $header,
    //     ]);
    
    //     $response = curl_exec($curl);
    //     $err = curl_error($curl);
    //     curl_close($curl);
    
        
     
    //     ApiLog::create([
    //         'txnId' => $transactionId,
    //         'request' => $payload,
    //         'response' => $response,  
    //         'service' => "CHECKSTATUS",
    //         'service_api' =>"Testing",   
    //     ]);
    
    //     if ($err) {
    //         $responseData = [
    //             'status' => FALSE,
    //             'error' => TRUE,
    //             'message' => 'Failed to fetch transaction status.',
    //         ];
    //         return response()->json($responseData, 400);
    //     }
    
    //     $responseData = json_decode($response, true);
    
    //     if (!isset($responseData['status'])) {
    //         $responseData = [
    //             'status' => FALSE,
    //             'error' => TRUE,
    //             'message' => 'Invalid response received.',
    //         ];
    //         return response()->json($responseData, 400);
    //     }
    
       

    //     return response()->json($responseData);
    // }

}