<?php
/**
 * PeachPay order helpers
 *
 * @package PeachPay
 */

if ( ! defined( 'PEACHPAY_ABSPATH' ) ) {
	exit;
}

define( 'PEACHPAY_PAYMENT_META_KEY', '_peachpay_payment_meta' );

/**
 * Adds CSV export option to bulk actions menu
 *
 * @param array $actions input array.
 */
function peachpay_add_bulk_export_csv( $actions ) {
	$actions['export_to_csv'] = __( 'Export to CSV', 'peachpay-for-woocommerce' );
	return $actions;
}

/**
 * CSV export bulk action handler
 *
 * @param string $redirect_to url to redirect to.
 * @param string $doaction action that was selected.
 * @param array  $order_ids IDs of orders selected.
 */
function peachpay_handle_bulk_export_csv( $redirect_to, $doaction, $order_ids ) {
	if ( 'export_to_csv' !== $doaction ) {
		return $redirect_to;
	}
	$redirect_to = add_query_arg( 'bulk_exported_orders', implode( ',', $order_ids ), $redirect_to );
	return $redirect_to;
}

/**
 * Displays CSV link
 */
function peachpay_bulk_export_csv_notice() {
	// phpcs:ignore -- no nonce is generated by the bulk action form
	if ( ! empty( $_REQUEST['bulk_exported_orders'] ) ) {
		// phpcs:ignore -- no nonce is generated by the bulk action form
		echo "<div id=\"message\" class=\"updated\"><p><a download=\"orders.csv\" href=\"" . peachpay_generate_data_uri( $_REQUEST['bulk_exported_orders'] ) . "\">Download order data CSV</a></p></div>";
	}
}

/**
 * Generates data URI of CSV
 *
 * @param array $order_ids input array.
 */
function peachpay_generate_data_uri( $order_ids ) {
	$data          = array(
		array(
			'Order ID',
			'Status',
			'First name',
			'Last name',
			'Address line 1',
			'Address line 2',
			'City',
			'ZIP/Postcode',
			'State',
			'Country',
			'Phone',
			'Email',
		),
	);
	$order_ids_arr = explode( ',', $order_ids );
	foreach ( $order_ids_arr as $order_id ) {
		$order  = wc_get_order( $order_id );
		$data[] = array(
			$order->get_id(),
			$order->get_status(),
			$order->get_shipping_first_name(),
			$order->get_shipping_last_name(),
			$order->get_shipping_address_1(),
			$order->get_shipping_address_2(),
			$order->get_shipping_city(),
			$order->get_shipping_postcode(),
			$order->get_shipping_state(),
			$order->get_shipping_country(),
			$order->get_shipping_phone(),
			$order->get_billing_email(),
		);
	}
	// phpcs:ignore -- base64 has to be used
	return 'data:text/csv;base64,' . base64_encode( peachpay_array2csv( $data ) );
}

/**
 * Converts 2D array to CSV
 *
 * @param array  $data input array.
 * @param string $delimiter delimeter.
 * @param string $enclosure quotes char.
 * @param string $escape_char escape char.
 */
function peachpay_array2csv( $data, $delimiter = ',', $enclosure = '"', $escape_char = '\\' ) {
	// phpcs:ignore -- PHP fopen has to be used since we're not accesing a file
	$f = fopen( 'php://memory', 'r+' );
	foreach ( $data as $item ) {
		fputcsv( $f, $item, $delimiter, $enclosure, $escape_char );
	}
	rewind( $f );
	return stream_get_contents( $f );
}

/**
 * .
 *
 * @param WC_Order $order to get data from.
 */
function peachpay_get_order_pay_details( $order ) {
	return array(
		'currency'           => $order->get_currency(),

		'is_only_free_trial' => floatVal( 0 ) === floatVal( $order->get_total( '' ) ),
		'needs_shipping'     => false,
		'shipping_packages'  => array(),

		'item_lines'         => peachpay_get_order_line_items( $order ),
		'subtotal_line'      => array(
			'label'  => __( 'Subtotal', 'peachpay-for-woocommerce' ),
			'amount' => strval( $order->get_subtotal() ),
		),
		'shipping_lines'     => array(
			array(
				'label'  => __( 'Shipping', 'peachpay-for-woocommerce' ),
				'amount' => strval( $order->get_shipping_total() ),
			),
		),
		'discount_lines'     => array(
			array(
				'label'  => __( 'Discount', 'peachpay-for-woocommerce' ),
				'amount' => strval( $order->get_total_discount() ),
			),
		),
		'tax_lines'          => array(
			array(
				'label'  => __( 'Tax', 'peachpay-for-woocommerce' ),
				'amount' => strval( $order->get_total_tax() ),
			),
		),
		'total_line'         => array(
			'label'  => __( 'Total', 'peachpay-for-woocommerce' ),
			'amount' => strval( $order->get_total() ),
		),
	);
}

/**
 * .
 *
 * @param WC_Order $order to get data from.
 */
function peachpay_get_order_line_items( $order ) {
	$line_items = array();
	foreach ( $order->get_items() as $item ) {
		$product = $item->get_product();
		if ( ! $product ) {
			continue;
		}
		$line_items[] = array(
			'id'       => strval( $product->get_id() ),
			'label'    => $product->get_title(),
			'amount'   => strval( $product->get_price() ),
			'quantity' => $item->get_quantity(),
		);
	}

	return $line_items;
}
