<?php
/**
 * The WCVendors Export Helper Class
 *
 * This is the helper class to help exporting data for vendors
 *
 * @package    WCVendors_Pro
 * @subpackage WCVendors_Pro/public
 * @author     Ketul Sheth <support@wcvendors.com>
 */

if ( ! defined( 'ABSPATH' ) ) {
    return;
}

/**
 * WCVendors Pro Commission Export class.
 *
 * @version 1.8.4
 * @since   1.8.4
 */
class WCVendors_Pro_Export_Helper_Commisson {

    /**
     * The ID of this plugin.
     *
     * @since    1.8.4
     * @access   private
     * @var      string $wcvendors_pro The ID of this plugin.
     */
    private $wcvendors_pro;

    /**
     * The version of this plugin.
     *
     * @since    1.8.4
     * @access   private
     * @var      string $version The current version of this plugin.
     */
    private $version;

    /**
     * Is the plugin in debug mode
     *
     * @since    1.8.4
     * @access   private
     * @var      bool $debug plugin is in debug mode
     */
    private $debug;

    /**
     * Is the plugin base directory
     *
     * @since    1.8.4
     * @access   private
     * @var      string $base_dir string path for the plugin directory
     */
    private $base_dir;

    /**
     * Whether the vendor is allowed to export commissions to a CSV file.
     *
     * @var boolean
     * @version 1.8.8
     * @since   1.8.8
     */
    public $can_export_commisson_csv = false;

    /**
     * Initialize the class and set its properties.
     *
     * @version 1.8.4
     * @since   1.8.4
     *
     * @param string $wcvendors_pro The name of the plugin.
     * @param string $version       The version of this plugin.
     * @param string $debug         Whether debug is turned on or not.
     */
    public function __construct( $wcvendors_pro, $version, $debug ) {

        $this->wcvendors_pro            = $wcvendors_pro;
        $this->version                  = $version;
        $this->debug                    = $debug;
        $this->base_dir                 = plugin_dir_path( __DIR__ );
        $this->can_export_commisson_csv = wc_string_to_bool( get_option( 'wcvendors_capability_commission_export', 'no' ) );
    }

    /**
     * Send the CSV to the browser for download
     *
     * @version 1.8.4
     * @since   1.8.4
     *
     * @param array $all_commission All the Commission to export.
     */
    public function format_orders_export( $all_commission ) {

        $rows = array();

        if ( ! empty( $all_commission ) ) {

            foreach ( $all_commission as $_order ) {

                $order            = $_order->order;
                $order_staus      = $order->get_status();
                $completed_status = apply_filters( 'wcvendors_completed_statuses', array( 'completed', 'processing' ) );

                if ( ! in_array( $order_staus, $completed_status, true ) ) {
                    continue;
                }

                $products       = '';
                $needs_shipping = false;
                $needs_to_ship  = false;
                $downloadable   = false;
                $order_currency = $order->get_currency();

                foreach ( $_order->order_items as $key => $item ) {
                    $product_id         = ( $item->get_variation_id() ) ? $item->get_product_id() : $item->get_product_id();
                    $_product           = new WC_Product( $product_id );
                    $item_qty           = $item->get_quantity();
                    $product_commission = ( $item_qty > 1 ) ? $_order->product_commissions[ $product_id ] / $item_qty : $_order->product_commissions[ $product_id ];
                    $commission_due     = $_order->total_due;
                    $needs_shipping     = $_product->is_virtual();
                    if ( ! $needs_shipping ) {
                        $needs_shipping = 0;
                    }
                    $downloadable = ( $_product->is_downloadable() ) ? true : false;
                    if ( is_null( $downloadable ) ) {
                        $downloadable = 0;
                    }
                    $item_qty      = $item['qty'];
                    $commission    = $commission_due;
                    $item_name     = $item['name'];
                    $products     .= "$item_name \r";
                    $needs_to_ship = ( $needs_shipping || ! $downloadable ) ? true : false;
                }

                $shippers = (array) $order->get_meta( 'wc_pv_shipped' );
                $shippers = array_filter( $shippers );

                $has_shipped               = in_array( get_current_user_id(), $shippers, true ) ? __( 'Yes', 'wcvendors-pro' ) : __( 'No', 'wcvendors-pro' );
                $shipped                   = ( $needs_to_ship ) ? $has_shipped : __( 'NA', 'wcvendors-pro' );
                $order_date                = $order->get_date_created();
                $new_row                   = array();
                $new_row['order_number']   = $order->get_order_number();
                $new_row['products']       = $products;
                $new_row['qty']            = $item_qty;
                $new_row['commission_due'] = $commission;
                $new_row['total']          = $_order->total;
                $new_row['status']         = $shipped;
                $new_row['order_date']     = date_i18n( 'Y-m-d', strtotime( $order_date ) );

                $rows[] = $new_row;

            }
        } // check for Commission

        return $rows;
    }

    /**
     * Send the CSV to the browser for download
     *
     * @version 1.8.4
     * @since   1.8.4
     *
     * @param    array  $headers  The CSV column headers.
     * @param    array  $body     The CSV body.
     * @param    string $filename The CSV filename.
     */
    public function download_csv( $headers, $body, $filename ) { // phpcs:ignore

        // Clear browser output before this point.
        if ( ob_get_contents() ) {
            ob_end_clean();
        }

        if ( ! $body ) {
            return false;
        }
        $filename_comm = 'Commission';

        // Output headers so that the file is downloaded rather than displayed.
        header( 'Content-Type: text/csv; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename=' . $filename_comm . '.csv' );

        // Create a file pointer connected to the output stream.
        $csv_output = fopen( 'php://output', 'w' );

        // Output the column headings.
        fputcsv( $csv_output, $headers );

        // Body.
        foreach ( $body as $data ) {
            fputcsv( $csv_output, $data );
        }

        die();
    } // download_csv

    /**
     * Headers for the Commission export CSV
     *
     * @version 1.8.4
     * @since   1.8.4
     *
     * @return array
     */
    public function get_export_headers() {
        $headers = array(
            'order'          => __( 'Order ID', 'wcvendors-pro' ),
            'product'        => __( 'Product Title', 'wcvendors-pro' ),
            'qty'            => __( 'QTY', 'wcvendors-pro' ),
            'commission_due' => __( 'Commission ', 'wcvendors-pro' ),
            'total'          => __( 'Order Total', 'wcvendors-pro' ),
            'status'         => __( 'Shipped', 'wcvendors-pro' ),
            'date'           => __( 'Date', 'wcvendors-pro' ),
        );
        return apply_filters( 'wcv_export_headers', $headers );
    }
}
