403Webshell
Server IP : 65.108.144.40  /  Your IP : 216.73.217.165
Web Server : Apache/2.4.52 (Ubuntu)
System : Linux ubuntu-8gb-hel1-1 5.15.0-173-generic #183-Ubuntu SMP Fri Mar 6 13:29:34 UTC 2026 x86_64
User : dev ( 1000)
PHP Version : 8.2.30
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /var/www/html/capital-catering/web/app/themes/capital-catering/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/capital-catering/web/app/themes/capital-catering/custom-adyen-sap-report.php
<?php

/**
 * Plugin Name: Adyen WooCommerce Report Merger
 */

add_action('admin_menu', function () {
    // mainmenu - Settings
    add_menu_page(
        __('Adyen Woo Report', 'capital-catering'),
        __('Adyen Woo Report', 'capital-catering'),
        'manage_options',
        'adyen-woo-report',
        'cc_render_adyen_woo_page'
    );

    // Submenu - Settings
    add_submenu_page(
        'adyen-woo-report',
        __('Adyen Settings', 'capital-catering'),
        __('Settings', 'capital-catering'),
        'manage_options', 
        'adyen-woo-settings', 
        'cc_render_adyen_settings_page'
    );
});

// Render Main Page
function cc_render_adyen_woo_page() {

    // Common merged file path
    $upload_dir = wp_upload_dir();
    $merged_path = trailingslashit($upload_dir['basedir']) . 'sap-reports/sap_merged_report.csv';
    $merged_url  = trailingslashit($upload_dir['baseurl']) . 'sap-reports/sap_merged_report.csv';

    ?>
    <div class="wrap">
        <h1><?php echo _e('Adyen + WooCommerce Report', 'capital-catering'); ?></h1>

        <h2><?php echo _e('๐Ÿงพ SAP Report:', 'capital-catering'); ?></h2>
        <p>
            <?php if (file_exists($merged_path)): ?>
                โœ… <a href="<?php echo esc_url($merged_url); ?>" target="_blank"><?php echo _e('Download SAP Report', 'capital-catering'); ?></a>
            <?php else: ?>
                โŒ <?php echo _e('SAP report not found.', 'capital-catering'); ?>
            <?php endif; ?>
        </p>
    </div>
    <?php
}

// Register settings
add_action('admin_init', function () {
    // Test Settings
    register_setting('adyen_settings_group', 'adyen_test_url');
    register_setting('adyen_settings_group', 'adyen_test_merchant');
    register_setting('adyen_settings_group', 'adyen_test_username');
    register_setting('adyen_settings_group', 'adyen_test_password');

    // Live Settings
    register_setting('adyen_settings_group', 'adyen_live_url');
    register_setting('adyen_settings_group', 'adyen_live_merchant');
    register_setting('adyen_settings_group', 'adyen_live_username');
    register_setting('adyen_settings_group', 'adyen_live_password');

    // Environment selector
    // register_setting('adyen_settings_group', 'adyen_environment');
});


// Render Settings Page
function cc_render_adyen_settings_page() {
    ?>
    <div class="wrap">
        <h1><?php echo _e('Adyen Settings', 'capital-catering'); ?></h1>
        <p><?php echo _e('The mode (test or live) is determined by the configuration set in the Adyen payment gateway settings.', 'capital-catering'); ?></p>
        <form method="post" action="options.php">
            <?php settings_fields('adyen_settings_group'); ?>
            <table class="form-table">

                <!-- <tr>
                    <th scope="row"><label for="adyen_environment"><?php // echo _e('Environment', 'capital-catering'); ?></label></th>
                    <td>
                        <select name="adyen_environment" id="adyen_environment">
                            <option value="test" <?php // selected(get_option('adyen_environment'), 'test'); ?>><?php // echo _e('Test', 'capital-catering'); ?></option>
                            <option value="live" <?php // selected(get_option('adyen_environment'), 'live'); ?>><?php // echo _e('Live', 'capital-catering'); ?></option>
                        </select>
                    </td>
                </tr> -->

                <!-- Test Settings -->
                <tr><th colspan="2"><h2><?php echo _e('Test Settings', 'capital-catering'); ?></h2></th></tr>
                <tr>
                    <th><label for="adyen_test_url"><?php echo _e('Test URL', 'capital-catering'); ?></label></th>
                    <td><input type="text" name="adyen_test_url" id="adyen_test_url" value="<?php echo esc_attr(get_option('adyen_test_url')); ?>" class="regular-text"></td>
                </tr>
                <tr>
                    <th><label for="adyen_test_merchant"><?php echo _e('Test Merchant', 'capital-catering'); ?></label></th>
                    <td><input type="text" name="adyen_test_merchant" id="adyen_test_merchant" value="<?php echo esc_attr(get_option('adyen_test_merchant')); ?>" class="regular-text"></td>
                </tr>
                <tr>
                    <th><label for="adyen_test_username"><?php echo _e('Test Username', 'capital-catering'); ?></label></th>
                    <td><input type="text" name="adyen_test_username" id="adyen_test_username" value="<?php echo esc_attr(get_option('adyen_test_username')); ?>" class="regular-text"></td>
                </tr>
                <tr>
                    <th><label for="adyen_test_password"><?php echo _e('Test Password', 'capital-catering'); ?></label></th>
                    <td><input type="password" name="adyen_test_password" id="adyen_test_password" value="<?php echo esc_attr(get_option('adyen_test_password')); ?>" class="regular-text"></td>
                </tr>

                <!-- Live Settings -->
                <tr><th colspan="2"><h2><?php echo _e('Live Settings', 'capital-catering'); ?></h2></th></tr>
                <tr>
                    <th><label for="adyen_live_url"><?php echo _e('Live URL', 'capital-catering'); ?></label></th>
                    <td><input type="text" name="adyen_live_url" id="adyen_live_url" value="<?php echo esc_attr(get_option('adyen_live_url')); ?>" class="regular-text"></td>
                </tr>
                <tr>
                    <th><label for="adyen_live_merchant"><?php echo _e('Live Merchant', 'capital-catering'); ?></label></th>
                    <td><input type="text" name="adyen_live_merchant" id="adyen_live_merchant" value="<?php echo esc_attr(get_option('adyen_live_merchant')); ?>" class="regular-text"></td>
                </tr>
                <tr>
                    <th><label for="adyen_live_username"><?php echo _e('Live Username', 'capital-catering'); ?></label></th>
                    <td><input type="text" name="adyen_live_username" id="adyen_live_username" value="<?php echo esc_attr(get_option('adyen_live_username')); ?>" class="regular-text"></td>
                </tr>
                <tr>
                    <th><label for="adyen_live_password"><?php echo _e('Live Password', 'capital-catering'); ?></label></th>
                    <td><input type="password" name="adyen_live_password" id="adyen_live_password" value="<?php echo esc_attr(get_option('adyen_live_password')); ?>" class="regular-text"></td>
                </tr>

            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

// Cron schedule.
add_filter('cron_schedules', function ($schedules) {
    if (!isset($schedules['daily'])) {
        $schedules['daily'] = [
            'interval' => 86400,
            'display' => __('Once Daily', 'capital-catering'),
        ];
    }
    return $schedules;
});

add_action('init', function () {
    if (!wp_next_scheduled('generate_combined_sap_report')) {
       // $timestamp = strtotime('09:00:00'); // Get 09 AM today
        if (time() > $timestamp) {
        //    $timestamp = strtotime('tomorrow 09:00:00');
        }
        wp_schedule_event($timestamp, 'daily', 'generate_combined_sap_report');
    }
});

add_action('generate_combined_sap_report', 'cc_generate_and_merge_sap_reports');

function cc_generate_and_merge_sap_reports() {
    error_log("โ–ถ Merging SAP Reports...");
    $adyen_path = cc_download_adyen_reports_by_name();
    $settlement_path = cc_download_adyen_reports_by_name( 'settlement_detail' );


    if (is_wp_error($adyen_path)) {
        error_log($adyen_path->get_error_message());
        return;
    }

    if (is_wp_error($settlement_path)) {
        error_log($settlement_path->get_error_message());
        return;
    }

	if (!file_exists($adyen_path) || !file_exists($settlement_path)) {
        error_log("โŒ One or both report files not found.");
        return;
    }

    $adyen_data = array_map('str_getcsv', file($adyen_path));
    $settlement_data = array_map('str_getcsv', file($settlement_path));

    $adyen_header = array_shift($adyen_data);
    $settlement_header = array_shift($settlement_data);

    // Get column indexes for filtering
    $adyen_record_type_idx = array_search('Record Type', $adyen_header);
    $adyen_merchant_ref_idx = array_search('Merchant Reference', $adyen_header);
    $adyen_psp_idx = array_search('Psp Reference', $adyen_header);
    $settle_psp_idx = array_search('Psp Reference', $settlement_header);
    $settle_record_type_idx = array_search('Record Type', $settlement_header);
    
    $order_ids = [];
    $psp_refs = [];
    
    // Process Adyen data to get order IDs from Merchant Reference
    $filtered_adyen_data = [];
    foreach ($adyen_data as $row) {
        $record_type = isset($row[$adyen_record_type_idx]) ? trim($row[$adyen_record_type_idx]) : '';
        $merchant_ref = isset($row[$adyen_merchant_ref_idx]) ? trim($row[$adyen_merchant_ref_idx]) : '';
        $psp = isset($row[$adyen_psp_idx]) ? trim($row[$adyen_psp_idx]) : '';
        
        // Include only 'Refunded' or 'Settled' records with valid merchant reference
        if (in_array($record_type, ['Refunded', 'Settled']) && $merchant_ref !== '') {
            // Convert to integer and validate the order ID
            $order_id = (int) $merchant_ref;
            if ($order_id > 0) {
                $order_ids[] = $order_id;
                if ($psp) {
                    $psp_refs[$psp] = true;
                }
                $filtered_adyen_data[] = $row;
            } else {
                error_log("โš  Invalid order ID in merchant reference: " . $merchant_ref);
            }
        }
    }
    $adyen_data = $filtered_adyen_data;
    
    // Process Settlement data to collect PSP references
    $filtered_settlement_data = [];
    $settlement_psp_refs = [];
    foreach ($settlement_data as $row) {
        $record_type = isset($row[$settle_record_type_idx]) ? trim($row[$settle_record_type_idx]) : '';
        $psp = isset($row[$settle_psp_idx]) ? trim($row[$settle_psp_idx]) : '';
        
        if (in_array($record_type, ['Refunded', 'Settled']) && $psp !== '') {
            $settlement_psp_refs[$psp] = true;
            $filtered_settlement_data[] = $row;
        }
    }
    $settlement_data = $filtered_settlement_data;
    
    // Get unique order IDs and PSP references
    $order_ids = array_values(array_unique($order_ids));
    $psp_refs = array_keys($psp_refs);
    $settlement_psp_refs = array_keys($settlement_psp_refs);
    
    if (empty($order_ids)) {
        error_log("No valid order IDs found in Adyen reports with 'Refunded' or 'Settled' status");
    } else {
        error_log("Found " . count($order_ids) . " unique order IDs with 'Refunded' or 'Settled' status");
    }

    // Generate WooCommerce CSV using the order IDs directly
    $woocommerce_path = cc_generate_sap_woocommerce_csv_reports($order_ids);
	if ( is_wp_error( $woocommerce_path ) || !file_exists($woocommerce_path) ) {
		error_log("โŒ WooCommerce report could not be generated.");
		return;
	}
	$wc_data = array_map('str_getcsv', file($woocommerce_path));
	$wc_header = array_shift($wc_data);

    // Find indexes
    $adyen_psp_index = array_search('Psp Reference', $adyen_header);
    $adyen_payment_method_index = array_search('Payment Method Variant', $adyen_header);

    // Get Settlement column indexes
    $settle_psp_index = array_search('Psp Reference', $settlement_header);
    $settle_markup_index = array_search('Markup (NC)', $settlement_header);
    $settle_scheme_index = array_search('Scheme Fees (NC)', $settlement_header);
    $settle_interchange_index = array_search('Interchange (NC)', $settlement_header);
    $settle_payment_fees_index = array_search('Payment Fees (NC)', $settlement_header);
    $settle_payment_method_index = array_search('Payment Method Variant', $settlement_header);

    $wc_psp_index = array_search('PSP Reference Number', $wc_header);
    $wc_markup_index = array_search('Markup (NC)', $wc_header);
    $wc_scheme_index = array_search('Scheme Fees (NC)', $wc_header);
    $wc_interchange_index = array_search('Interchange (NC)', $wc_header);
    $wc_payment_fees_index = array_search('Payment Fees (NC)', $wc_header);
    $wc_payment_method_index = array_search('Payment Method', $wc_header);

    // Map Adyen by PSP Reference
    $adyen_map = [];
    foreach ($adyen_data as $row) {
        $adyen_map[trim($row[$adyen_psp_index])] = $row;
    }

    // Map Settlement rows by PSP
    $settlement_map = [];
    foreach ($settlement_data as $row) {
        $psp = trim($row[$settle_psp_index]);
        $settlement_map[$psp] = $row;
    }

    // Update WC rows with Adyen fees
    foreach ($wc_data as &$row) {
        if ( 'Refund' == $row[$wc_payment_method_index] ) {
            break;
        }
        $psp = trim($row[$wc_psp_index]);
        if (isset($adyen_map[$psp])) {
            $adyen_row = $adyen_map[$psp];

            if ( isset( $adyen_row[$adyen_payment_method_index] ) && 'Refund' != $row[$wc_payment_method_index] ) {
                if ('amex_googlepay' == $adyen_row[$adyen_payment_method_index]) {
                    $row[$wc_payment_method_index] = 'Google Pay';
                } elseif ('amex_applepay' == $adyen_row[$adyen_payment_method_index]) {
                    $row[$wc_payment_method_index] = 'Apple Pay';
                } else {
                    $row[$wc_payment_method_index] = 'Card';
                }
            } else {
                $row[$wc_payment_method_index] = 'Card';
            }
        }

        // Merge from Settlement
        if (isset($settlement_map[$psp])) {
            $settlement_row = $settlement_map[$psp];
            if (isset( $settlement_row[$settle_markup_index] ) && !empty($settlement_row[$settle_markup_index]) ) {
                $row[$wc_markup_index] = number_format($settlement_row[$settle_markup_index], 2, '.', '');
            }
            $row[$wc_scheme_index] = ($settlement_row[$settle_scheme_index]) ? number_format($settlement_row[$settle_scheme_index], 2, '.', '') : 0;
            $row[$wc_interchange_index] = ($settlement_row[$settle_interchange_index]) ? number_format($settlement_row[$settle_interchange_index], 2, '.', '') : 0;
            if (isset( $settlement_row[$settle_payment_fees_index] ) && !empty($settlement_row[$settle_payment_fees_index]) ) {
                $row[$wc_payment_fees_index] = number_format($settlement_row[$settle_payment_fees_index], 2, '.', '');
            }
            if ( 0 == $row[$wc_payment_fees_index] ) {
                $pm_fees = floatval( $row[$wc_markup_index] ) + floatval( $row[$wc_scheme_index] ) + floatval( $row[$wc_interchange_index] ) + 0.17;
                $row[$wc_payment_fees_index] = number_format($pm_fees, 2, '.', '');
            }
            if ( isset( $settlement_row[$settle_payment_method_index] ) && 'Refund' != $row[$wc_payment_method_index] ) {
                if ('amex_googlepay' == $settlement_row[$settle_payment_method_index]) {
                    $row[$wc_payment_method_index] = 'Google Pay';
                } elseif ('amex_applepay' == $settlement_row[$settle_payment_method_index]) {
                    $row[$wc_payment_method_index] = 'Apple Pay';
                } else {
                    $row[$wc_payment_method_index] = 'Card';
                }
            } else {
                $row[$wc_payment_method_index] = 'Card';
            }
        }
    }
    unset($row);

    // Save merged file
    $folderDate = date('Y-m-d', strtotime('-1 day'));
    $upload_dir = wp_upload_dir();
    $baseDir = trailingslashit($upload_dir['basedir']) . 'sap-reports';
    if (!file_exists($baseDir)) wp_mkdir_p($baseDir);

    $final_path = $baseDir . '/sap_merged_report.csv';
    $fp = fopen($final_path, 'w');
    fputcsv($fp, $wc_header);
    foreach ($wc_data as $row) {
        fputcsv($fp, $row);
    }
    fclose($fp);

    error_log("โœ… Final merged SAP report generated: $final_path");

    // Common merged file path.
    if (untrailingslashit(home_url()) === 'https://capital-catering-plus.demandtech.org') {
        if (!empty($final_path)) {
            $uploaded = upload_csv_to_sftp_with_date($final_path);
            error_log('CSV uploaded successfully to ' . $uploaded);
        } else {
            error_log('CSV upload failed.');
        }
    }
}

// Existing Adyen download function...
function cc_download_adyen_reports_by_name( $report_name = 'payments_accounting' ) {
    // $env = get_option('adyen_environment'); // test or live
    $is_mode = get_option( '_wkwc_adyen_test_mode_enabled' );
    $env = ( 'yes' === $is_mode) ? 'test' : 'live'; // test or live

    $url = rtrim(get_option("adyen_{$env}_url"), '/');
    $merchant = get_option("adyen_{$env}_merchant");
    $username = get_option("adyen_{$env}_username");
    $password = get_option("adyen_{$env}_password");

    $reportDate = date('Y_m_d', strtotime('-1 day'));
    $folderDate = date('Y-m-d', strtotime('-1 day'));

    $file_name = ( 'payments_accounting' === $report_name ) ? $report_name . '_report_' . $reportDate . '.csv' : $report_name . '_report_' . $folderDate . '.csv';

    if ( ! empty( $url ) && ! empty( $merchant ) && ! empty( $username ) && ! empty( $password ) ) {
        $url .= "/reports/download/MerchantAccount/$merchant/$file_name";

        $upload_dir = wp_upload_dir();
        $baseDir = trailingslashit($upload_dir['basedir']) . 'sap-reports/' . $folderDate;
        if (!file_exists($baseDir)) wp_mkdir_p($baseDir);
        $savePath = $baseDir . "/$file_name";

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($http_code !== 200 || empty($response)) {
            return new WP_Error('adyen_download_failed', "Failed to download Adyen report: HTTP $http_code. Error: $error");
        }

        file_put_contents($savePath, $response);
        return $savePath;
    }
}
// Your WooCommerce report generator (unchanged)
function cc_generate_sap_woocommerce_csv_reports( $order_ids = array() ) {
    $reportDate = date('Y_m_d', strtotime('-1 day'));
    $folderDate = date('Y-m-d', strtotime('-1 day'));
    $upload_dir = wp_upload_dir();
    $baseDir = trailingslashit($upload_dir['basedir']) . 'sap-reports/' . $folderDate;
    if (!file_exists($baseDir)) wp_mkdir_p($baseDir);
    $filepath = $baseDir . "/sap_report_$reportDate.csv";

    $file = fopen($filepath, 'w');
    if (!$file) return new WP_Error('csv_open_error', "โŒ Could not open file for writing: $filepath");

    $headers = array(
        "Order Id", 
        "Invoice Number", 
        "Customer Name", 
        "Customer Contact", 
        "Customer Email",
        "Customer VAT Details (If applicable)", 
        "Customer Payment Method info (Masked)",
        "Business Place",
        "PSP Reference Number", 
        "ARN (Acquirer Reference Number)",
        "Date", 
        "Time", 
        "Currency Code", 
        "Payment Method", 
        "Sale Amount",
        "Delivery Charges", 
        "Gross Amount",
        "Discount", 
        "Tax Base Amount", 
        "Tax/ Vat Code", 
        "Tax Rate",
        "Output Tax", 
        "Total Amount (including VAT)", 
        "Markup (NC)", 
        "Scheme Fees (NC)", 
        "Interchange (NC)", 
        "Payment Status",
        "Payment Fees (NC)",
        "CCS Bank Charges Bearer",
    );
    fputcsv($file, $headers);

    $normal_rows = [];
    $refund_rows = [];

    // If no order IDs provided, return empty file
    if (empty($order_ids)) {
        fclose($file);
        return $filepath;
    }

    // Get orders by the provided order IDs
    $orders = wc_get_orders([
        'limit' => -1,
        'post__in' => array_map('intval', $order_ids),
    ]);

    // Log the number of orders found
    error_log("Found " . count($orders) . " WooCommerce orders matching the provided order IDs");

    foreach ($orders as $order) {
        if (!is_a($order, 'WC_Order')) continue;

        $inv_no = $order->get_meta('_wcpdf_invoice_number');
        $notifications = $order->get_meta('_adyen_notifications');
        $pspReference = ( isset($notifications['pspReference']) ) ? $notifications['pspReference'] : '';
		$arnref = ( isset($notifications['additionalData']) && isset($notifications['additionalData']['acquirerReference']) ) ? $notifications['additionalData']['acquirerReference'] : '';

		// If limiting by PSP Reference, skip orders not in the set
		if ( ! empty($allowed_psp_refs) ) {
			if ( '' === $pspReference || ! in_array( trim($pspReference), $allowed_psp_refs, true ) ) {
				continue;
			}
		}

        $order_status = in_array($order->get_status(), ['completed', 'processing', 'refunded'], true) ? 'Confirmed' : ucfirst($order->get_status());
        $payment_method = 'Card';

        $tax_label = '';
        $tax_rate = '';
        foreach ( $order->get_items('tax') as $tax_item ) {
            $rate_id    = $tax_item->get_rate_id();
            $tax_label  = $tax_item->get_label();
            $tax_rate   = WC_Tax::get_rate_percent($rate_id);
            $tax_label  = (5 == $tax_item->get_rate_percent()) ? 'S2' : $tax_label;
        }

        $customer_id = $order->get_customer_id();
        $customer_code = get_user_meta( $customer_id, 'customer_code', true );
        // error_log('$customer_code: ' . print_r($customer_code, true));

        $phone_number  = $order->get_billing_phone();
        $phone_number = ($phone_number) ? $phone_number : '-';

        $business_place  = get_option( 'woocommerce_store_city' );
        $business_place = ($business_place) ? $business_place : '-';

        // Total discount (all coupons applied)
        $discount = $order->get_discount_total(); // Discount excluding tax
        // $total_discount_tax = $order->get_discount_tax(); // Discount tax amount (if any)
        // $total_discount_incl_tax = $discount + $total_discount_tax; // Optional: Total including tax
        $shipping_amt = $order->get_shipping_total();
        $total_tax = $order->get_total_tax();
        $sale_amount = number_format($order->get_subtotal(), 2, '.', '');
        $gross_amt = $sale_amount + $shipping_amt;
        $tax_base_amt = $gross_amt - $discount;
        $total_amount = number_format($order->get_total(), 2, '.', '');
        $markup_nc = $total_amount * 0.0035;
        $payment_fees = $markup_nc + 0.17;
        $ccs_bank_charges = 'Yes';

        $row = array(
            $order->get_id(), // Order Id.
            $inv_no, // Invoice Number.
            trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()) ?: '-', // Customer  Name.
            $phone_number, // Customer Contact.
            $order->get_billing_email() ?: '-', // Customer Email.
            // $customer_code, // Customer Numeric Code Generated by WooCommerce.
            '', // Customer VAT Details (If applicable).
            '', // Customer Payment Method info (Masked).
            $business_place, // Business Place.
            $pspReference, // PSP Reference Number.
            $arnref, // ARN (Acquirer Reference Number).
            $order->get_date_created() ? $order->get_date_created()->date('Y-m-d') : '', // Date.
            $order->get_date_created() ? $order->get_date_created()->date('H:i:s') : '', // Time.
            $order->get_currency(), // Currency Code.
            $payment_method, // Payment Method.
            $sale_amount, // Sale Amount.
            $shipping_amt, // Delivery Charges.
            $gross_amt, // Gross Amount.
            $discount, // Discount.
            number_format($tax_base_amt, 2, '.', ''), // Tax Base Amount.
            $tax_label, // Tax/ VAT Code.
            $tax_rate, // Tax Rate.
            $total_tax, // Output Tax.
            $total_amount, // Total Amount (including VAT).
            number_format($markup_nc, 2, '.', ''), // Markup (NC).
            '', // Scheme Fees (NC).
            '', // Interchange (NC).
            $order_status, // Payment Status.
            number_format($payment_fees, 2, '.', ''), // Payment Fees (NC).
            $ccs_bank_charges, // CCS Bank Charges Bearer.
        );

        $normal_rows[] = $row;

        // Handle refunds
        if ('refunded' == $order->get_status()) {
            $refund_row = $row;
            if ( isset($refund_row[13]) && 'Card' == $refund_row[13] ) {
                $refund_row[13] = 'Refund';
            }
            if ( isset($refund_row[10]) ) {
                $refund_row[10] = $order->get_date_modified() ? $order->get_date_modified()->date('Y-m-d') : '';
            }
            if ( isset($refund_row[11]) ) {
                $refund_row[11] = $order->get_date_modified() ? $order->get_date_modified()->date('H:i:s') : '';
            }

            $refund_rows[] = $refund_row;
        }
    }

    // Write normal rows first
    foreach ($normal_rows as $row) {
        fputcsv($file, $row);
    }

    // Then write refund rows
    foreach ($refund_rows as $row) {
        fputcsv($file, $row);
    }

    fclose($file);
    return $filepath;
}


// composer require phpseclib/phpseclib : Use this command for sftp library.
require_once get_template_directory() . '/vendor/autoload.php';
use phpseclib3\Net\SFTP;

function upload_csv_to_sftp_with_date() {

    // $sftp_host = 'ccskeyconnect.blob.core.windows.net';
    // $sftp_user = 'ccskeyconnect.ccsipos';
    // $sftp_pass = 'cOGYaK6eMuPaZBc6ih8YbZIms7tfJo8L';

     $sftp_host = 'growthnstg.sftp.wpengine.com';
    $sftp_user = 'growthnstg-vishal';
    $sftp_pass = 'sdfcOGYa8YbZIms7tfJo8L';

    $upload_dir = wp_upload_dir();
    $merged_path = trailingslashit($upload_dir['basedir']) . 'sap-reports/sap_merged_report.csv';
    $local_file_url  = trailingslashit($upload_dir['baseurl']) . 'sap-reports/sap_merged_report.csv';

    if (!file_exists($merged_path)) {
        error_log('CSV file not found: ' . $local_file_url);
        return false;
    }

    // Remote folder and file name
    $remote_folder = '/Website';
    $date = date('Y_m_d');
    $remote_file_name = "sap_merged_report_{$date}.csv";
    $remote_full_path = "{$remote_folder}/{$remote_file_name}";

    // SFTP connect
    $sftp = new SFTP($sftp_host);
    if (!$sftp->login($sftp_user, $sftp_pass)) {
        error_log('SFTP login failed');
        return false;
    }

    // Create folder if it doesn't exist
    if (!$sftp->is_dir($remote_folder)) {
        if (!$sftp->mkdir($remote_folder)) {
            error_log("Failed to create folder: {$remote_folder}");
            return false;
        }
    }

    // Upload file
    $upload = $sftp->put($remote_full_path, file_get_contents($merged_path));
    if ($upload) {
        error_log("Uploaded successfully: {$remote_file_name}");
    } else {
        error_log("Upload failed: {$remote_file_name}");
    }

    return $upload;
}

Youez - 2016 - github.com/yon3zu
LinuXploit