<?php

trait TotalProcessingApplePayGatewayHelperTrait{
    
    public function applePayButtonsArray($buildBtn = false, $showStyle = false){
        $buttonData                  = [ 'cart', 'checkout' ];
        if( $buildBtn !== false && in_array($buildBtn, $buttonData) ){
	return '
            <ul class="wc_payment_methods payment_methods methods wc_tp_applepay_container" style="list-style:none;">
                <li class="wc_payment_method wc_tp_applepay_containerli">
                    <label for="payment_method_wc_tp_applepay" style="padding:1.41575em 0 1.41575em 0;">
                        All transactions are secured and encrypted 
                        <img src="'.TOTALPROCESSING_PAYMENTGATEWAY_APPLEPAY_BASEURL.'assets/img/apple-pay-logo@2x.png" alt="Apple Pay" style="height:24px; padding:0;float: right;margin: 2px;">
		    </label>
                    <div id="tp-appp-loader" class="tp-applepay-init-loader" style="display: flex;justify-content: center;margin-top:1.41575em;"><div class="dot-bricks"></div></div>
                    <div id="payment_method_wc_tp_applepayiframecontainer"></div>' . ( $buildBtn == 'cart' ? wc_get_template_html( 'checkout/terms.php' ) : '' ) . '
	        </li>
            </ul>';
        }
        return '';
    }

    public function inheritGatewayCrentialsFromCardProcessing(){
        if( $this->inheritcreds == 'yes' ){
            $TPPaymentObj                     = new WC_Payment_Gateway_TotalProcessing_Cards();
            $entityIdTest                     = $TPPaymentObj->get_option( 'entityId_test' );
            $accessTokenTest                  = $TPPaymentObj->get_option( 'accessToken_test' );
            $entityId                         = $TPPaymentObj->get_option( 'entityId' );
            $accessToken                      = $TPPaymentObj->get_option( 'accessToken' );
            $this->update_option('entityId_test', $entityIdTest);
            $this->update_option('accessToken_test', $accessTokenTest);
            $this->update_option('entityId', $entityId);
            $this->update_option('accessToken', $accessToken);
        }
    }

    public function getEntityID(){
        return ($this->platformBase == 'live' ? $this->entityId : $this->entityId_test);
    }

    public function getAccessToken(){
        return ($this->platformBase === 'live' ? $this->accessToken : $this->accessToken_test);
    }

    public function getPlatformBase(){
        return ($this->platformBase === 'live' ? 'eu-prod.oppwa.com' : 'eu-test.oppwa.com');
    }
    
    public function statusDomainVerifactionFile(){
        $pluginFilePath     = TOTALPROCESSING_PAYMENTGATEWAY_APPLEPAY_BASEPATH;
        $docBase            = trailingslashit($_SERVER['DOCUMENT_ROOT']);
        $certFilePath       = '.well-known/' . $this->domainVerificationFileName;
        $docFilePath        = $docBase . $certFilePath;
        $arrayFalse         = [
            "valid"       => false,
            "mark"        => "error",
            "description" => $certFilePath,
            "private"     => true,
            "button"      => [
                "value"       => "Move File",
                "pl_action"   => "moveValidationFile"
            ]
        ];
        $arrayTrue          =[
            "valid"       => true,
            "mark"        => "yes",
            "description" => $certFilePath,
            "private"     => false
        ];
        
        if( !is_writable( $docBase . '.well-known/' ) ){
            return [
                "valid"       => false,
                "mark"        => "yes",
                "description" => $certFilePath . ' is not writable',
                "private"     => false
            ];
        }

        $fileFolder         = trailingslashit( $pluginFilePath ) . 'appleValidation/';
        $location           = $fileFolder . $this->domainVerificationFileName;
        $destination        = $docFilePath;
        if( !file_exists( $destination ) ){
            return [
                "valid"       => false,
                "mark"        => "error",
                "description" => $certFilePath . ' is missing',
                "private"     => false,
                "button"      => [
                    "value"       => "Move File",
                    "pl_action"   => "moveValidationFile"
                ]
            ];
        }
        $origFileContent    = file_get_contents($location);
        $origFileContent    = trim($origFileContent);
        $destFileContent    = file_get_contents($destination);
        $destFileContent    = trim($destFileContent);
        if( file_exists( $destination ) && $origFileContent != $destFileContent ){
            return [
                "valid"       => false,
                "mark"        => "error",
                "description" => $certFilePath . ' is not right file',
                "private"     => false,
                "button"      => [
                    "value"       => "Move File",
                    "pl_action"   => "moveValidationFile"
                ]
            ];
        }
        return $arrayTrue;
    }
    
    public function moveValidationFile(){
        $status                       = false;
                                      
        $targetDir                    = $this->createRootFolderProcedure('.well-known');
                                      
        $tpapFs_docRoot               = $_SERVER["DOCUMENT_ROOT"];
        $tpapFs_homePath              = get_home_path();
        $tpapFs_pluginFilePath        = plugin_dir_path( __FILE__ );
        
        if($targetDir !== false){
            $location                 = TOTALPROCESSING_PAYMENTGATEWAY_APPLEPAY_BASEPATH . '/appleValidation/' . $this->domainVerificationFileName;
            $destination              = trailingslashit($tpapFs_docRoot) . '.well-known/' . $this->domainVerificationFileName;
            $status                   = $this->moveFileDir($location, $destination);
        }
        wp_send_json_success( [
            "valid"                  => $status,
            "containerId"            => "statusTablesContainer",
            "html"                   => $this->generateStatusArray(true)
        ] );
    }

    public function createRootFolderProcedure($dir){
        $docBase = $_SERVER['DOCUMENT_ROOT'];
        
        $docPath = trailingslashit($docBase) . $dir;
        
        if(!is_dir($docPath)){
            if(mkdir($docPath)) {
                if(chmod($docPath, 0755)){
                    return $docPath;
                }
            }
        } else {
            return $docPath;
        }
        return false;
    }
    
    public function moveFileDir($location, $destination){
        if(file_exists($location)){
            file_put_contents($destination, file_get_contents($location));
            return true;
        }
        return false;
    }
    
    public function generateStatusArray($retHtml=false,$colSpan=4){
        $array                        = [];
        if($retHtml){
            $html                     = '';
        }
        if(!is_admin()){
            return $array;
        }
        $array                        = [
            [
                "group" => "General Settings",
                "data"  => [
                    [ 
                        "name"          => "WooCommerce Apple Pay payments",
                        "status"        => $this->statusCheckIsEnabled($this->enabled,'',false)
                    ],
                    [
                        "name"          => "Apple Pay buttons restricted to only admins",
                        "status"        => $this->statusCheckIsEnabled($this->onlyadmins, '', true, 'yes', 'warning' )
                    ],
                    [
                        "name"          => "Apple Pay console.log()",
                        "status"        => $this->statusCheckIsEnabled( $this->get_option( 'jsLogging' ), '', true, ($this->jsLogging == 'yes' ? 'warning' : 'yes'), ($this->jsLogging == 'yes' ? 'warning' : 'warning') )
                    ],
                    [
                        "name"          => "SSL Protocol",
                        "status"        => $this->usingSSL()
                    ],
                ]
            ],
            [
                "group" => "Gateway Configurations",
                "data"  => [
                    [
                        "name"          => "Selected Payment Environment",
                        "status"        => [
                            "valid"           => true,
                            "mark"            => ($this->platformBase != 'test' ? 'yes' : 'warning'),
                            "description"     => $this->platformBase,
                            "private"         => false
                        ]
                    ],
                    [
                        "name"          => "TEST Processing: accessToken",
                        "helptip"       => "",
                        "status"        => $this->stringCheck($this->accessToken_test, '/[a-zA-Z0-9]{58}[=]{2}/m', ($this->platformBase != 'test' ? 'warning' : 'error'), 'yes')
                    ],
                    [
                        "name"          => "TEST Processing: entityId",
                        "helptip"       => "",
                        "status"        => $this->stringCheck($this->entityId_test, '/[a-z0-9]{32}/m', ($this->platformBase != 'test' ? 'warning' : 'error'), 'yes')
                    ],
                    [
                        "name"          => "LIVE Processing: accessToken",
                        "helptip"       => "",
                        "status"        => $this->stringCheck($this->accessToken, '/[a-zA-Z0-9]{58}[=]{2}/m', ($this->platformBase != 'live' ? 'warning' : 'error'), 'yes')
                    ],
                    [
                        "name"          => "LIVE Processing: entityId",
                        "helptip"       => "",
                        "status"        => $this->stringCheck($this->entityId, '/[a-z0-9]{32}/m', ($this->platformBase != 'live' ? 'warning' : 'error'), 'yes')
                    ],
                ]
            ],
            [
                "group" => "Apple Domain Registration",
                "data"  => [
                    [
                        "name"          => "Domain Registration Request",
                        "helptip"       => "",
                        "status"        => $this->statusDomainRegistrationRequest()
                    ],
                ]
            ],
            [
                "group" => "Apple Domain Validation",
                "data"  => [
                    [
                        "name"          => $this->domainVerificationFileName,
                        "helptip"       => "",
                        "status"        => $this->statusDomainVerifactionFile()
                    ],
                ]
            ],
            [
                "group" => "Webhook variables (for Total Processing ref.)",
                "data"  => [
                    [
                        "name"     => "var:domain",
                        "status"   => [
                            "valid"       => true,
                            "description" => $_SERVER['HTTP_HOST'],
                            "private"     => true
                        ]
                    ],
                    [
                        "name"     => "var:wp_path",
                        "status"   => [
                            "valid"       => true,
                            "description" => site_url(),
                            "private"     => true
                        ]
                    ],
                    [
                        "name"     => "get_home_path",
                        "status"   => [
                            "valid"       => true,
                            "description" => get_home_path(),
                            "private"     => true
                        ]
                    ],
                    [
                        "name"     => "SERVER_SOFTWARE",
                        "status"   => [
                            "valid"       => true,
                            "description" => $_SERVER['SERVER_SOFTWARE'] . ' PHP v' . phpversion(),
                            "private"     => false
                        ]
                    ],
                    [
                        "name"     => "SERVER_PROTOCOL",
                        "status"   => [
                            "valid"       => true,
                            "description" => $_SERVER['SERVER_PROTOCOL'],
                            "private"     => false
                        ]
                    ],
                ]
            ],
        ];
        if($retHtml){
            foreach($array as $tbl){
                $html.='<table class="wc_status_table widefat" cellspacing="0">'."\n";
                $html.='<thead>'."\n";
                $html.='<tr>'."\n";
                $html.='<th colspan="'.$colSpan.'" data-export-label="'.$tbl['group'].'">'."\n";
                $html.='<h2>'.$tbl['group'].'</h2></th>'."\n";
                $html.='</tr>'."\n";
                $html.='</thead>'."\n";
                $html.='<tbody>'."\n";
                if(isset($tbl['group']) && is_array($tbl['data'])){
                    foreach($tbl['data'] as $tr){
                        $html.='<tr>'."\n";
                        $html.='<td data-export-label="'.$tr['name'].'">'.$tr['name'].'</td>'."\n";
                        $html.='<td class="help">'."\n";
                        if(isset($tr['helptip'])){
                            $html.='<span class="woocommerce-help-tip">'.$tr['helptip'].'</span>'."\n";
                        }
                        $html.='</td>'."\n";
                        $html.='<td>'."\n";
                        if(isset($tr['status']['mark'])){
                            if((bool)$tr['status']['valid'] === true){
                                $dashIcon = $tr['status']['mark'];
                            } else {
                                $dashIcon = 'warning';
                            }
                            $html.='<mark class="'.$tr['status']['mark'].'"><span class="dashicons dashicons-'.$dashIcon.'"></span> '."\n";
                        }
                        if(isset($tr['status']['private']) && (bool)$tr['status']['private']===true){
                            $html.='<code class="private">'."\n";
                        }
                        $html.= $tr['status']['description'];
                        if(isset($tr['status']['private']) && (bool)$tr['status']['private']===true){
                            $html.='</code>'."\n";
                        }
                        if(isset($tr['status']['mark'])){
                            $html.='</mark>'."\n";
                        }
                        $html.='</td>'."\n";
                        $html.='<td style="text-align:right;">'."\n";
                        if(isset($tr['status']['button'])){
                            $html.='<button class="button tp-admin-ajax" data-pl_action="'.$tr['status']['button']['pl_action'].'" value="'.$tr['status']['button']['value'].'">'.$tr['status']['button']['value'].'</button>'."\n";
                        }
                        $html.='</td>'."\n";
                        $html.='</tr>'."\n";
                    }
                }
                $html.='</tbody>'."\n";
                $html.='</table>'."\n";
            }
            return $html;
        }
        return $array;
    }
    
    public function statusCheckIsEnabled($item,$customDescription='',$reverse=false,$errorClass='error',$successClass='yes'){
        $condition='yes';
        $arrayFalse=["valid"=>false,"mark"=>$errorClass,"description"=>"Disabled","private"=>false];
        $arrayTrue=["valid"=>true,"mark"=>$successClass,"description"=>"Enabled","private"=>false];
        if($reverse){
            $arrayFalse["valid"] = true;
        }
        if($item == $condition){
            $array = $arrayTrue;
        } else {
            $array = $arrayFalse;
        }
        if(trim($customDescription) != ''){
            $array['description'] = $array['description'].' ('. $customDescription.')';
        }
        return $array;
    }
    
    public function stringCheck($item,$pattern,$errorClass='error',$successClass='yes'){
        $arrayFalse=["valid"=>false,"mark"=>$errorClass,"description"=>"","private"=>false];
        $arrayTrue=["valid"=>true,"mark"=>$successClass,"description"=>"","private"=>false];
        preg_match_all($pattern, $item, $matches, PREG_SET_ORDER, 0);
        if(count($matches)>0){
            return $arrayTrue;
        }
        if($pattern == '/[a-zA-Z0-9]{58}[=]{2}/m' || $pattern == '/[a-z0-9]{32}/m'){
            if($errorClass == 'warning'){
                $arrayFalse['description'] = "*Not essential when in current processing environment";
            } else {
                $arrayFalse['description'] = "ERROR processing will fail in selected processing environment!";
            }
        }
        return $arrayFalse;
    }
    
    public function usingSSL($errorClass='error',$successClass='yes'){
        $arrayFalse=["valid"=>false,"mark"=>$errorClass,"description"=>"","private"=>false];
        $arrayTrue=["valid"=>true,"mark"=>$successClass,"description"=>"","private"=>false];
        if(is_ssl()){
            return $arrayTrue;
        }
        return $arrayFalse;
    }

    public function insUpPluginOption($option, $value, $unset=false){
        $value               = sanitize_text_field($value);
        if(get_option($option) !== $unset){
            return update_option($option, $value);
        } else {
            return add_option($option,$value);
        }
    }

    /**
     * UPDATED: Always get fresh cart amount and generate unique checkout ID
     */
    public function requestCheckoutID( $obj = true, $forceAmount = false ){
        try {
            // Get required address fields
            $requiredBillingContactFields = $this->billingAddressFields;
            $requiredShippingContactFields = $this->shippingAddressFields;
            
            if($this->reqShipping() === true || !empty($requiredShippingContactFields)){
                if(!in_array("postalAddress", $requiredShippingContactFields)){
                    $requiredShippingContactFields[] = "postalAddress";
                }
                if(!in_array("name", $requiredShippingContactFields)){
                    $requiredShippingContactFields[] = "name";
                }
                
                $billingFields = $this->genAddrReq('GB', 'billing_');
                if(in_array('billing_phone', $billingFields) && !in_array("phone", $requiredShippingContactFields)){
                    $requiredShippingContactFields[] = "phone";
                }
            }
            
            $requiredShippingContactFields = array_unique($requiredShippingContactFields);
            $requiredBillingContactFields = array_unique($requiredBillingContactFields);
    
            // UPDATED: Always get fresh cart total
            $amount = WC()->cart->get_total('edit');
    
            if((float)$amount <= 0){
                wp_send_json_error(['message' => 'Invalid amount: ' . $amount], 400);
                return;
            }
    
            // Anti-spam protection with unique session key
            $session_id = WC()->session ? WC()->session->get_customer_id() : '';
            
            // UPDATED: Prepare checkout request with unique merchant transaction ID
            $payload = [
                'entityId' => $this->getEntityID(),
                'paymentType' => $this->paymentType,
                'amount' => number_format($amount, 2, '.', ''),
                'currency' => get_woocommerce_currency(),
            ];

	    if(is_user_logged_in()){
		$payload['customer.merchantCustomerId'] = get_current_user_id();
	    }

            $remoteUrl = 'https://' . $this->getPlatformBase() . '/v1/checkouts';
            
            $array = [
                'method' => 'POST',
                'timeout' => 20,
                'redirection' => 5,
                'httpversion' => '1.0',
                'blocking' => true,
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
                    'Authorization' => 'Bearer '.$this->getAccessToken(),
                    'Cache-Control' => 'no-cache'
                ],
                'body' => $payload
            ];
    
            $response = wp_remote_request( $remoteUrl , $array);
            
            if( is_wp_error( $response ) ){
                $errorMessage = $response->get_error_message();
                $this->writeLog('Checkout request failed: ' . $errorMessage, '', 'error');
                wp_send_json_error(['message' => 'Request failed: ' . $errorMessage], 500);
                return;
            }
            
            $responseData = json_decode($response['body']);
    
            if(isset($responseData->id)){
                if(isset($responseData->result->code)){
                    if(in_array($responseData->result->code,['000.200.000','000.200.100','000.200.101'])){
                        $checkout_id = (string)$responseData->id;
                        WC()->session->set('tp_checkout_id', $checkout_id);
                        // UPDATED: Create response with fresh data
                        $checkout_response = [
                            "termAndConditionCheckbox" => wc_terms_and_conditions_checkbox_enabled() && $this->enableTermCheckbox == 'yes',
                            "currencyCode" => get_woocommerce_currency(),
                            "merchantCapabilities" => $this->acceptedCards,
                            "supportedNetworks" => $this->supportedNetworks,
                            "displayName" => empty( $this->displayName ) ? get_bloginfo( 'name' ) : $this->displayName,
                            "total" => [
                                "label" => empty( $this->displayName ) ? get_bloginfo( 'name' ) : $this->displayName,
                                "amount" => (string)$amount, // UPDATED: Always fresh amount
                            ],
                            "requiredBillingContactFields" => $requiredBillingContactFields,
                            "requiredShippingContactFields" => $requiredShippingContactFields,
                            "shippingType" => "shipping",
                            "shippingMethods" => [],
                            "platformBase" => $this->getPlatformBase(),
                            "checkout_id" => $checkout_id,
                            "termAndConditionValidationText" => $this->termCheckboxErrorText,
                            "timestamp" => time(),
                            "cart_hash" => WC()->cart ? WC()->cart->get_cart_hash() : '',
                            "session_id" => $session_id,
                        ];
                        
                        // UPDATED: Store checkout ID with merchant transaction ID mapping
                        set_transient('checkout_' . $checkout_id, [
                            'created' => time(), 
                            'session_id' => $session_id,
                            'user_id' => get_current_user_id(),
                            'cart_hash' => WC()->cart ? WC()->cart->get_cart_hash() : '',
                            'amount' => $amount
                        ], 1800);

                        //Add metabox log here
                        $this->logInfo(
                            "requestCheckoutID -> Generated checkoutID: " . $checkout_id,
                            [
                                'action' => 'generateing new checkout id',
                                'payload' => $payload,
                                'checkout_id' => $checkout_id,
                                'response' => $responseData,
                            ],
                            null,
                            null,
                            $checkout_id
                        );
                        
                        $this->writeLog('Generated checkout ID: ' . $checkout_id . ' for amount: ' . $amount, '', 'debug');
                        
                        wp_send_json_success($checkout_response);
                        return;
                    }
                }
            }
            
            $this->writeLog('Invalid checkout response: ' . json_encode($responseData), '', 'error');
            wp_send_json_error(['message' => 'Invalid response from payment gateway'], 400);
            
        } catch (Exception $e) {
            $this->writeLog('Checkout request exception: ' . $e->getMessage(), '', 'error');
            wp_send_json_error(['message' => 'Request failed: ' . $e->getMessage()], 500);
        }
    }
    
    public function updateTransactionData($id, $payload){
        $url="https://" . $this->getPlatformBase() . "/v1/checkouts/$id";
        $payload['entityId'] = $this->getEntityID();
	$headers = [
		'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
		'Authorization' => 'Bearer '.$this->getAccessToken()
	];
        return $this->prepareRemoteRequest($url, $headers, $payload, 'POST');
    }
    
    public function prepareOrderDataForPayload($order_data, $additionalParams = []){
        global $wp_version;
        $payload = [
            "paymentType"                               => $this->paymentType,
            "amount"                                    => number_format($order_data['total'], 2, '.', ''),
            "currency"                                  => $order_data['currency'],
            "merchantTransactionId"                     => $order_data['id'],
            "customer.merchantCustomerId"               => $order_data['customer_id'],
            "customParameters[SHOPPER_amount]"          => number_format($order_data['total'], 2, '.', ''),
            "customParameters[SHOPPER_currency]"        => $order_data['currency'],
            "customParameters[SHOPPER_order_key]"       => $order_data['order_key'],
            "customParameters[SHOPPER_cart_hash]"       => $order_data['cart_hash'],
            "customParameters[SHOPPER_platform]"        => "WooCommerce",
            "customParameters[SHOPPER_version_data]"    => "WPVER_" . $wp_version . "|" . "WCVER_" . WC_VERSION . "|" . "TPMOD_".$this->id,
            "customParameters[SHOPPER_plugin]"          => tpGetPluginFileData( 'Version' ),
            "customer.ip"                               => $order_data['customer_ip_address'],
            "customer.browserFingerprint.value"         => $order_data['customer_user_agent'],
        ];
        
        if(isset($order_data['billing']['phone'])){
            if(!empty($order_data['billing']['phone'])){
                $payload["customer.mobile"]             = $order_data['billing']['phone'];
            }
        }
        if(isset($order_data['billing']['address_1'])){
            if(!empty($order_data['billing']['address_1'])){
                $payload["billing.street1"]             = $order_data['billing']['address_1'];
            }
        }
        if(isset($order_data['billing']['address_2'])){
            if(!empty($order_data['billing']['address_2'])){
                $payload["billing.street2"]             = $order_data['billing']['address_2'];
            }
        }
        if(isset($order_data['billing']['city'])){
            if(!empty($order_data['billing']['city'])){
                $payload["billing.city"]                = $order_data['billing']['city'];
            }
        }
        if(isset($order_data['billing']['postcode'])){
            if(!empty($order_data['billing']['postcode'])){
                $payload["billing.postcode"]            = $order_data['billing']['postcode'];
            }
        }
        if(isset($order_data['billing']['country'])){
            if(!empty($order_data['billing']['country'])){
                $payload["billing.country"]             = $order_data['billing']['country'];
            }
        }
        if(isset($order_data['shipping']['address_1'])){
            if(!empty($order_data['shipping']['address_1'])){
                $payload["shipping.street1"]            = $order_data['shipping']['address_1'];
            }
        }
        if(isset($order_data['shipping']['address_2'])){
            if(!empty($order_data['shipping']['address_2'])){
                $payload["shipping.street2"]            = $order_data['shipping']['address_2'];
            }
        }
        if(isset($order_data['shipping']['city'])){
            if(!empty($order_data['shipping']['city'])){
                $payload["shipping.city"]               = $order_data['shipping']['city'];
            }
        }
        if(isset($order_data['shipping']['state'])){
            if(!empty($order_data['shipping']['state'])){
                $payload["shipping.state"]              = $order_data['shipping']['state'];
            }
        }
        if(isset($order_data['shipping']['postcode'])){
            if(!empty($order_data['shipping']['postcode'])){
                $payload["shipping.postcode"]           = $order_data['shipping']['postcode'];
            }
        }
        if(isset($order_data['shipping']['country'])){
            if(!empty($order_data['shipping']['country'])){
                $payload["shipping.country"]            = $order_data['shipping']['country'];
            }
        }
        return array_merge($payload, $this->getCartItemsOrderData($order_data['id']), $additionalParams);
    }
    
    public function getCartItemsOrderData($order_id){
        $payload = [];
        $cartItems = [];
        $order_id = (int)$order_id;
        $oObj = wc_get_order($order_id);
        foreach($oObj->get_items(['line_item']) as $oItemId => $oItem){
            $oProd = $oItem->get_product();
            $cartItem = [
                'name' => substr($oItem->get_name(),0,255),
                'merchantItemId' => $oItem->get_product_id(),
                'quantity' => (int)$oItem->get_quantity(),
                'type' => ($oProd->is_virtual() === true ? 'DIGITAL' : 'PHYSICAL'),
                'sku' => ($oProd->get_sku() === '' ? $oItem->get_product_id() : $oProd->get_sku()),
                'currency' => $oObj->get_currency(),
                'description' => substr(wp_strip_all_tags($oProd->get_description()),0,255),
                'price' => number_format((float)$oObj->get_item_subtotal($oItem), 2, '.', ''),
                'totalAmount' => number_format(((float)$oItem->get_total() + (float)$oObj->get_line_tax($oItem)), 2, '.', ''),
                'taxAmount' => number_format( (float)$oObj->get_item_tax($oItem), 2, '.', '' ),
                'totalTaxAmount' => number_format( (float)$oObj->get_line_tax($oItem), 2, '.', '' )
            ];
            $cartItems[] = $cartItem;
        }
        foreach( $oObj->get_items('shipping') as $oItemId => $shipping_item_obj ){
            $cartItem = [
                'name' => 'Shipping',
                'merchantItemId' => $shipping_item_obj->get_method_id() .':'. $shipping_item_obj->get_instance_id(),
                'quantity' => 1,
                'type' => 'MIXED',
                'currency' => $oObj->get_currency(),
                'description' => substr($shipping_item_obj->get_method_title(),0,255),
                'price' => number_format( (float)$shipping_item_obj->get_total(), 2, '.', '' ),
                'shipping' => number_format( (float)$shipping_item_obj->get_total(), 2, '.', '' ),
                'shippingMethod' => substr($shipping_item_obj->get_name(),0,255),
                'totalAmount' => number_format( (float)$shipping_item_obj->get_total() + (float)$shipping_item_obj->get_total_tax(), 2, '.', '' ),
                'taxAmount' => number_format( (float)$shipping_item_obj->get_total_tax(), 2, '.', '' ),
                'totalTaxAmount' => number_format( (float)$shipping_item_obj->get_total_tax(), 2, '.', '' )
            ];
            $cartItems[] = $cartItem;
        }
        $n = 0;
        foreach($cartItems as $lineItemArray){
            foreach($lineItemArray as $k => $v){
                if(!empty($v) || $v !== ''){
                    if(in_array($k,$this->arrStaticData('forcePrecision2Dp'))){
                        $v = number_format($v, 2, '.', '');
                    }
                    $payload['cart.items['.$n.'].'.$k] = $v;
                }
            }
            $n++;
        }
        return $payload;
    }

    public function reqShipping(){
        if($this->enforceShipping == 'yes'){
            return false;
        }
        $cart_contents  = WC()->cart->cart_contents;
        $needs_shipping = false;
        if ( ! empty( $cart_contents ) ) {
            foreach ( $cart_contents as $cart_item_key => $values ) {
                if ( $values['data']->needs_shipping() ) {
                    $needs_shipping = true;
                    break;
                }
            }
        }
        return $needs_shipping;
    }

    public function statusDomainRegistrationRequest(){
        $gatewayType            = $this->get_option( 'platformBase' );
        $requestStatus          = get_option( 'applepayDomainRegStatus', 0 );
        if( $gatewayType != 'live' ){
            return [
                "valid"       => false,
                "mark"        => "error",
                "description" => 'Applepay is currently only available via Live credentials',
                "private"     => false,
            ];
        }
        if( $requestStatus == 1 ){
            return [
                "valid"       => false,
                "mark"        => "warning",
                "description" => 'Request sent for domain registration, Awaiting status. If you want to communicate, please send us email at ' . TP_APPLEPAY_SUPPORT_EMAIL,
                "private"     => false,
                "button"      => [
                    "value"       => "Re-Send Request",
                    "pl_action"   => "sendDomainRegistrationRequest"
                ]
            ];
        }
        if( $requestStatus == 2 ){
            return [
                "valid"       => true,
                "mark"        => "yes",
                "description" => 'Domain registration is done successfully. If you want to communicate, please send us email at ' . TP_APPLEPAY_SUPPORT_EMAIL,
                "private"     => false,
            ];
        }
        return [
            "valid"       => false,
            //"mark"        => "no",
            "description" => 'Click button to request for domain registration',
            "private"     => false,
            "button"      => [
                "value"       => "Send Request",
                "pl_action"   => "sendDomainRegistrationRequest"
            ]
        ];
    }

    public function sendDomainRegistrationRequest(){
        $domain                       = get_option('siteurl'); //or home
        $domain                       = str_replace('http://', '', $domain);
        $domain                       = str_replace('https://', '', $domain);
        $domain                       = str_replace('www', '', $domain);
        $adminEmail                   = get_option('admin_email');

        // Get the user object for the admin email
        $adminUser                    = get_user_by('email', $adminEmail);

        // Default name if the user is not found
        $adminName                    = $adminUser ? $adminUser->display_name : 'Admin';

        // Get the merchant email from WooCommerce settings
        $merchantEail                 = get_option('woocommerce_email_from_address');
    
        // Fallback to site admin email if not set
        if (empty($merchantEmail)) {
            $merchantEmail            = $adminEmail;
        }

        // Get the merchant name from WooCommerce email settings
        $merchantName                 = get_option('woocommerce_email_from_name');

        // Fallback to the site name if the WooCommerce setting is not set
        if (empty($merchantName)) {
            $merchantName             = $adminName;
        }

	$entityId                     = $this->get_option( 'entityId' );
        $pluginVer                    = \TotalProcessing\WC_TotalProcessing_Constants::getPluginFileData('Version');

        $hash                         = get_option('applepayDomainRegStatusHash', null);
        if( empty($hash) ){
            $hash                     = md5( time() );
            $this->insUpPluginOption('applepayDomainRegStatusHash', $hash);
        }
        $domainRegStatusLink          = admin_url( 'admin-ajax.php?action=tpApplepaydomainRegistationSuccess&hash=' . $hash );
        
        $status                       = true;
        $to                           = TP_APPLEPAY_SUPPORT_EMAIL;
	$subject                      = $domain . ' - Applepay Authorisation request';
        ob_start();
        include TOTALPROCESSING_PAYMENTGATEWAY_APPLEPAY_BASEPATH . 'emails/domain-registration-email.php';
        $body                         = ob_get_contents();
        ob_end_clean();
        $headers                      = array('Content-Type: text/html; charset=UTF-8');

        wp_mail( $to, $subject, $body, $headers );

        $this->insUpPluginOption('applepayDomainRegStatus', 1);
        wp_send_json_success( [
            "valid"                  => $status,
            "containerId"            => "statusTablesContainer",
            "html"                   => $this->generateStatusArray(true),
        ] );
    }

    public function domainRegistrationRequestThanks(){
        $rHash                        = sanitize_text_field( $_REQUEST['hash'] );
        $hash                         = get_option('applepayDomainRegStatusHash', null);
        if( !empty( $rHash ) && $hash == $rHash ){
            $this->insUpPluginOption('applepayDomainRegStatus', 2);
            ob_start();
            include TOTALPROCESSING_PAYMENTGATEWAY_APPLEPAY_BASEPATH . 'templates/domain-registration-thankyou.php';
            $body                         = ob_get_contents();
            ob_end_clean();
            die( $body );
	}
    }

    public function prepareRemoteRequest($url, $headers, $payload=false, $customRequest = 'POST'){
        $headers              = [
            'Content-Type'        => 'application/x-www-form-urlencoded; charset=UTF-8',
            'Authorization'       => 'Bearer ' . $this->getAccessToken()
        ];

        $array                = [
            'method'              => $customRequest,
            'timeout'             => 45,
            'redirection'         => 5,
            'httpversion'         => '1.0',
            'blocking'            => true,
            'headers'             => $headers
        ];
        if($payload !== false){
            $array['body']        = $payload;
        }

        $response                 = wp_remote_request( $url, $array );

        $responseData             = json_decode( $response['body'] );

        return $responseData;
    }
}
