<?php

/**
 * Orders page.
 *
 * All the orders functions.
 *
 * @package    DDFWM
 * @subpackage DDFWM/includes
 * @author     powerfulwp <cs@powerfulwp.com>
 */
/**
 * Orders class.
 *
 * All the orders functions.
 *
 * @package    DDFWM
 * @subpackage DDFWM/includes
 * @author     powerfulwp <cs@powerfulwp.com>
 */
class DDFWM_Orders {
    /**
     * Dashboard claim report query.
     *
     * @since 1.0.0
     * @return statement
     */
    public function ddfwm_claim_orders_dashboard_report_query() {
        global $wpdb, $ddfwm_vendor_id;
        if ( ddfwm_is_hpos_enabled() ) {
            // Query adapted for HPOS-enabled environments.
            $query = $wpdb->get_results( $wpdb->prepare( 'SELECT wco.status as post_status, COUNT(*) as orders
					FROM ' . $wpdb->prefix . 'wc_orders wco
					LEFT JOIN ' . $wpdb->prefix . 'wc_orders_meta pm ON wco.id = pm.order_id AND pm.meta_key = \'lddfw_driverid\'
					LEFT JOIN ' . $wpdb->prefix . 'wc_orders_meta pm1 ON wco.id = pm1.order_id AND pm1.meta_key = \'lddfw_delivered_date\'
					' . ddfwm_order_seller_query( 'INNER JOIN' ) . '
					WHERE wco.type = \'shop_order\' AND ( pm.meta_value IS NULL OR pm.meta_value = \'-1\' OR pm.meta_value = \'\' ) AND
					(
						wco.status IN (%s, %s, %s, %s) OR
						( wco.status = %s AND CAST( pm1.meta_value AS DATE ) >= %s AND CAST( pm1.meta_value AS DATE ) <= %s )
					)
					GROUP BY wco.status', array(
                get_option( 'lddfw_processing_status', '' ),
                get_option( 'lddfw_driver_assigned_status', '' ),
                get_option( 'lddfw_out_for_delivery_status', '' ),
                get_option( 'lddfw_failed_attempt_status', '' ),
                get_option( 'lddfw_delivered_status', '' ),
                date_i18n( 'Y-m-d' ),
                date_i18n( 'Y-m-d' )
            ) ) );
            // db call ok; no-cache ok.
        } else {
            // Original query for non-HPOS environments.
            $query = $wpdb->get_results( $wpdb->prepare( 'select post_status, count(*) as orders from ' . $wpdb->prefix . 'posts p
				left join ' . $wpdb->prefix . 'postmeta pm on p.id=pm.post_id and pm.meta_key = \'lddfw_driverid\'
				left join ' . $wpdb->prefix . 'postmeta pm1 on p.id=pm1.post_id and pm1.meta_key = \'lddfw_delivered_date\'
				' . ddfwm_order_seller_query( 'inner join' ) . '
				where post_type=\'shop_order\' and ( pm.meta_value is null or pm.meta_value = \'-1\' or pm.meta_value = \'\' ) and
				(
					post_status in (%s,%s,%s,%s) or
					( post_status = %s and CAST( pm1.meta_value AS DATE ) >= %s and CAST( pm1.meta_value AS DATE ) <= %s )
				)
				group by post_status', array(
                get_option( 'lddfw_processing_status', '' ),
                get_option( 'lddfw_driver_assigned_status', '' ),
                get_option( 'lddfw_out_for_delivery_status', '' ),
                get_option( 'lddfw_failed_attempt_status', '' ),
                get_option( 'lddfw_delivered_status', '' ),
                date_i18n( 'Y-m-d' ),
                date_i18n( 'Y-m-d' )
            ) ) );
            // db call ok; no-cache ok.
        }
        return $query;
    }

    /**
     * Drivers orders dashboard report.
     *
     * @since 1.0.0
     * @return statement
     */
    public function ddfwm_drivers_orders_dashboard_report_query() {
        global $wpdb, $ddfwm_vendor_id;
        if ( ddfwm_is_hpos_enabled() ) {
            // Query adapted for HPOS-enabled environments.
            $query = $wpdb->get_results( $wpdb->prepare( 'SELECT pm.meta_value driver_id, wco.status as post_status, u.display_name driver_name, COUNT(*) as orders
					FROM ' . $wpdb->prefix . 'wc_orders wco
					INNER JOIN ' . $wpdb->prefix . 'wc_orders_meta pm ON wco.id = pm.order_id AND pm.meta_key = \'lddfw_driverid\'
					' . ddfwm_order_seller_query( 'INNER JOIN' ) . '
					INNER JOIN ' . $wpdb->prefix . 'users u ON u.id = pm.meta_value
					LEFT JOIN ' . $wpdb->prefix . 'wc_orders_meta pm1 ON wco.id = pm1.order_id AND pm1.meta_key = \'lddfw_delivered_date\'
					WHERE wco.type = \'shop_order\' AND
					(
						wco.status IN (%s, %s, %s) OR
						( wco.status = %s AND CAST( pm1.meta_value AS DATE ) >= %s AND CAST( pm1.meta_value AS DATE ) <= %s )
					)
					GROUP BY pm.meta_value, wco.status
					ORDER BY pm.meta_value', array(
                get_option( 'lddfw_driver_assigned_status', '' ),
                get_option( 'lddfw_out_for_delivery_status', '' ),
                get_option( 'lddfw_failed_attempt_status', '' ),
                get_option( 'lddfw_delivered_status', '' ),
                date_i18n( 'Y-m-d' ),
                date_i18n( 'Y-m-d' )
            ) ) );
            // db call ok; no-cache ok.
        } else {
            // Original query for non-HPOS environments.
            $query = $wpdb->get_results( $wpdb->prepare( 'select pm.meta_value driver_id , post_status, u.display_name driver_name , count(*) as orders 
				from ' . $wpdb->prefix . 'posts p
				inner join ' . $wpdb->prefix . 'postmeta pm on p.id=pm.post_id and pm.meta_key = \'lddfw_driverid\'
				' . ddfwm_order_seller_query( 'inner join' ) . '
				inner join ' . $wpdb->prefix . 'users u on u.id = pm.meta_value
				left join ' . $wpdb->prefix . 'postmeta pm1 on p.id=pm1.post_id and pm1.meta_key = \'lddfw_delivered_date\'
				where post_type=\'shop_order\' and
				(
					post_status in (%s,%s,%s) or
					( post_status = %s and CAST( pm1.meta_value AS DATE ) >= %s and CAST( pm1.meta_value AS DATE ) <= %s )
				)
				group by pm.meta_value, post_status
				order by pm.meta_value ', array(
                get_option( 'lddfw_driver_assigned_status', '' ),
                get_option( 'lddfw_out_for_delivery_status', '' ),
                get_option( 'lddfw_failed_attempt_status', '' ),
                get_option( 'lddfw_delivered_status', '' ),
                date_i18n( 'Y-m-d' ),
                date_i18n( 'Y-m-d' )
            ) ) );
            // db call ok; no-cache ok.
        }
        return $query;
    }

    /**
     * Orders count query.
     *
     * @since 1.0.0
     * @param int $driver_id driver user id.
     * @return html
     */
    public function ddfwm_orders_count_query( $driver_id ) {
        global $wpdb;
        if ( ddfwm_is_hpos_enabled() ) {
            // Query adapted for HPOS-enabled environments.
            $query = $wpdb->get_results( $wpdb->prepare( 'SELECT wco.status as post_status, COUNT(*) as orders
					FROM ' . $wpdb->prefix . 'wc_orders wco
					INNER JOIN ' . $wpdb->prefix . 'wc_orders_meta pm ON wco.id = pm.order_id AND pm.meta_key = \'ddfwm_vendorid\' AND pm.meta_value = %s
					LEFT JOIN ' . $wpdb->prefix . 'wc_orders_meta pm1 ON wco.id = pm1.order_id AND pm1.meta_key = \'ddfwm_delivered_date\'
					' . ddfwm_order_seller_query( 'LEFT JOIN' ) . '
					WHERE wco.type = \'shop_order\' AND
					(
						wco.status IN (%s, %s, %s) OR
						( wco.status = %s AND CAST( pm1.meta_value AS DATE ) >= %s AND CAST( pm1.meta_value AS DATE ) <= %s )
					)
					GROUP BY wco.status', array(
                $driver_id,
                get_option( 'ddfwm_vendor_assigned_status', '' ),
                get_option( 'ddfwm_out_for_delivery_status', '' ),
                get_option( 'ddfwm_failed_attempt_status', '' ),
                get_option( 'ddfwm_delivered_status', '' ),
                date_i18n( 'Y-m-d' ),
                date_i18n( 'Y-m-d' )
            ) ) );
            // db call ok; no-cache ok.
        } else {
            // Original query for non-HPOS environments.
            $query = $wpdb->get_results( $wpdb->prepare( 'select post_status , count(*) as orders from ' . $wpdb->prefix . 'posts p
				inner join ' . $wpdb->prefix . 'postmeta pm on p.id=pm.post_id and pm.meta_key = \'ddfwm_vendorid\' and pm.meta_value = %s
				left join ' . $wpdb->prefix . 'postmeta pm1 on p.id=pm1.post_id and pm1.meta_key = \'ddfwm_delivered_date\'
				' . ddfwm_order_seller_query( 'left join' ) . '
				where post_type=\'shop_order\' and
				(
					post_status in (%s,%s,%s) or
					( post_status = %s and CAST( pm1.meta_value AS DATE ) >= %s and CAST( pm1.meta_value AS DATE ) <= %s )
				)
				group by post_status', array(
                $driver_id,
                get_option( 'ddfwm_vendor_assigned_status', '' ),
                get_option( 'ddfwm_out_for_delivery_status', '' ),
                get_option( 'ddfwm_failed_attempt_status', '' ),
                get_option( 'ddfwm_delivered_status', '' ),
                date_i18n( 'Y-m-d' ),
                date_i18n( 'Y-m-d' )
            ) ) );
            // db call ok; no-cache ok.
        }
        return $query;
    }

    /**
     * Drivers orders dashboard report.
     *
     * @since 1.0.0
     * @return html
     */
    public function ddfwm_vendors_orders_dashboard_report_query() {
        global $wpdb;
        if ( ddfwm_is_hpos_enabled() ) {
            // Query adapted for HPOS-enabled environments.
            $query = $wpdb->get_results( $wpdb->prepare( 'SELECT pm.meta_value driver_id, wco.status as post_status, u.display_name driver_name, COUNT(*) as orders
					FROM ' . $wpdb->prefix . 'wc_orders wco
					INNER JOIN ' . $wpdb->prefix . 'wc_orders_meta pm ON wco.id = pm.order_id AND pm.meta_key = \'ddfwm_vendorid\'
					INNER JOIN ' . $wpdb->prefix . 'users u ON u.id = pm.meta_value
					LEFT JOIN ' . $wpdb->prefix . 'wc_orders_meta pm1 ON wco.id = pm1.order_id AND pm1.meta_key = \'ddfwm_delivered_date\'
					' . ddfwm_order_seller_query( 'LEFT JOIN' ) . '
					WHERE wco.type = \'shop_order\' AND
					(
						wco.status IN (%s, %s, %s) OR
						( wco.status = %s AND CAST( pm1.meta_value AS DATE ) >= %s AND CAST( pm1.meta_value AS DATE ) <= %s )
					)
					GROUP BY pm.meta_value, wco.status
					ORDER BY pm.meta_value', array(
                get_option( 'ddfwm_vendor_assigned_status', '' ),
                get_option( 'ddfwm_out_for_delivery_status', '' ),
                get_option( 'ddfwm_failed_attempt_status', '' ),
                get_option( 'ddfwm_delivered_status', '' ),
                date_i18n( 'Y-m-d' ),
                date_i18n( 'Y-m-d' )
            ) ) );
            // db call ok; no-cache ok.
        } else {
            // Original query for non-HPOS environments.
            $query = $wpdb->get_results( $wpdb->prepare( 'select pm.meta_value driver_id , post_status, u.display_name driver_name , count(*) as orders 
				from ' . $wpdb->prefix . 'posts p
				inner join ' . $wpdb->prefix . 'postmeta pm on p.id=pm.post_id and pm.meta_key = \'ddfwm_vendorid\'
				inner join ' . $wpdb->prefix . 'users u on u.id = pm.meta_value
				left join ' . $wpdb->prefix . 'postmeta pm1 on p.id=pm1.post_id and pm1.meta_key = \'ddfwm_delivered_date\'
				' . ddfwm_order_seller_query( 'left join' ) . '
				where post_type=\'shop_order\' and
				(
					post_status in (%s,%s,%s) or
					( post_status = %s and CAST( pm1.meta_value AS DATE ) >= %s and CAST( pm1.meta_value AS DATE ) <= %s )
				)
				group by pm.meta_value, post_status
				order by pm.meta_value ', array(
                get_option( 'ddfwm_vendor_assigned_status', '' ),
                get_option( 'ddfwm_out_for_delivery_status', '' ),
                get_option( 'ddfwm_failed_attempt_status', '' ),
                get_option( 'ddfwm_delivered_status', '' ),
                date_i18n( 'Y-m-d' ),
                date_i18n( 'Y-m-d' )
            ) ) );
            // db call ok; no-cache ok.
        }
        return $query;
    }

    /**
     * Assign to driver count query.
     *
     * @since 1.0.0
     * @param int $driver_id driver user id.
     * @return array
     */
    public function ddfwm_assign_to_driver_count_query( $driver_id ) {
        global $wpdb;
        if ( ddfwm_is_hpos_enabled() ) {
            // Query adapted for HPOS-enabled environments.
            return $wpdb->get_results( $wpdb->prepare( 'SELECT COUNT(*) as orders
					FROM ' . $wpdb->prefix . 'wc_orders wco
					INNER JOIN ' . $wpdb->prefix . 'wc_orders_meta pm ON wco.id = pm.order_id AND pm.meta_key = \'lddfw_driverid\'
					' . ddfwm_order_seller_query( 'INNER JOIN' ) . '
					WHERE wco.type = \'shop_order\' AND wco.status IN (%s)
					AND pm.meta_value = %s
					GROUP BY wco.status', array(get_option( 'lddfw_driver_assigned_status', '' ), $driver_id) ) );
            // db call ok; no-cache ok.
        } else {
            // Original query for non-HPOS environments.
            return $wpdb->get_results( $wpdb->prepare( 'select count(*) as orders from ' . $wpdb->prefix . 'posts p
				inner join ' . $wpdb->prefix . 'postmeta pm on p.id=pm.post_id and pm.meta_key = \'lddfw_driverid\'
				' . ddfwm_order_seller_query( 'inner join' ) . '
				where post_type=\'shop_order\' and post_status in (%s)
				and pm.meta_value = %s group by post_status', array(get_option( 'lddfw_driver_assigned_status', '' ), $driver_id) ) );
            // db call ok; no-cache ok.
        }
    }

    /**
     * Orders_form_post
     *
     * @since 1.0.0
     * @param int $vendor_id vendor user id.
     * @return void
     */
    public function ddfwm_orders_form_post( $vendor_id ) {
        if ( isset( $_POST['ddfwm_wpnonce'] ) ) {
            $nonce = sanitize_text_field( wp_unslash( $_POST['ddfwm_wpnonce'] ) );
            if ( !wp_verify_nonce( $nonce, 'ddfwm-nonce' ) ) {
                $error = __( 'Security Check Failure - This alert may occur when you are logged in as an administrator and as a delivery driver on the same browser and the same device. If you want to work on both panels please try to work with two different browsers.', 'ddfwm' );
            } else {
                $ddfwm_action = ( isset( $_POST['ddfwm_action'] ) ? sanitize_text_field( wp_unslash( $_POST['ddfwm_action'] ) ) : '' );
                if ( '' != $ddfwm_action && isset( $_POST['ddfwm_order_id'] ) ) {
                    $driver = new LDDFW_Driver();
                    foreach ( $_POST['ddfwm_order_id'] as $order_id ) {
                        $order_id = sanitize_text_field( wp_unslash( $order_id ) );
                        $order = wc_get_order( $order_id );
                        // Update order Status.
                        if ( 'mark_driver_assigned' === $ddfwm_action ) {
                            $order->update_status( get_option( 'lddfw_driver_assigned_status' ), __( 'Order status has been changed by vendor.', 'ddfwm' ) );
                        } elseif ( 'mark_out_for_delivery' === $ddfwm_action ) {
                            $order->update_status( get_option( 'lddfw_out_for_delivery_status' ), __( 'Order status has been changed by vendor.', 'ddfwm' ) );
                        } elseif ( 'mark_failed' === $ddfwm_action ) {
                            $order->update_status( get_option( 'lddfw_failed_attempt_status' ), __( 'Order status has been changed by vendor.', 'ddfwm' ) );
                        } elseif ( 'mark_delivered' === $ddfwm_action ) {
                            $order->update_status( get_option( 'lddfw_delivered_status' ), __( 'Order status has been changed by vendor.', 'ddfwm' ) );
                        } else {
                            if ( '-1' === $ddfwm_action ) {
                                // Delete drivers.
                                $order->delete_meta_data( 'lddfw_driverid' );
                                $order->save();
                            } else {
                                // Assign a driver to order.
                                $driver->assign_delivery_driver( $order_id, $ddfwm_action, 'store' );
                            }
                        }
                    }
                    header( 'Location: ' . ddfwm_vendors_page_url( 'ddfwm_screen=orders' ) );
                }
            }
        }
    }

    /**
     * Orders
     *
     * @since 1.0.0
     * @param int $vendor_id vendor user id.
     * @return html
     */
    public function ddfwm_orders_page( $vendor_id ) {
        global $wpdb;
        // Handle orders form post.
        $this->ddfwm_orders_form_post( $vendor_id );
        global $ddfwm_page;
        // Get url params.
        $ddfwm_orders_filter = ( isset( $_GET['ddfwm_orders_filter'] ) ? sanitize_text_field( wp_unslash( $_GET['ddfwm_orders_filter'] ) ) : '' );
        $ddfwm_from_date = ( isset( $_GET['ddfwm_from_date'] ) ? sanitize_text_field( wp_unslash( $_GET['ddfwm_from_date'] ) ) : '' );
        $ddfwm_to_date = ( isset( $_GET['ddfwm_to_date'] ) ? sanitize_text_field( wp_unslash( $_GET['ddfwm_to_date'] ) ) : '' );
        $ddfwm_orders_status = ( isset( $_GET['ddfwm_orders_status'] ) ? sanitize_text_field( wp_unslash( $_GET['ddfwm_orders_status'] ) ) : '' );
        $ddfwm_dates = ( isset( $_GET['ddfwm_dates_range'] ) ? sanitize_text_field( wp_unslash( $_GET['ddfwm_dates_range'] ) ) : '' );
        /**
         * Set current status names
         */
        $ddfwm_driver_assigned_status_name = esc_html( __( 'Driver assigned', 'ddfwm' ) );
        $ddfwm_out_for_delivery_status_name = esc_html( __( 'Out for delivery', 'ddfwm' ) );
        $ddfwm_failed_attempt_status_name = esc_html( __( 'Failed delivery', 'ddfwm' ) );
        if ( function_exists( 'wc_get_order_statuses' ) ) {
            $result = wc_get_order_statuses();
            if ( !empty( $result ) ) {
                foreach ( $result as $key => $status ) {
                    switch ( $key ) {
                        case get_option( 'lddfw_out_for_delivery_status' ):
                            if ( $status !== $ddfwm_out_for_delivery_status_name ) {
                                $ddfwm_out_for_delivery_status_name = $status;
                            }
                            break;
                        case get_option( 'lddfw_failed_attempt_status' ):
                            if ( esc_html( __( 'Failed Delivery Attempt', 'ddfwm' ) ) !== $status ) {
                                $ddfwm_failed_attempt_status_name = $status;
                            }
                            break;
                        case get_option( 'lddfw_driver_assigned_status' ):
                            if ( $status !== $ddfwm_driver_assigned_status_name ) {
                                $ddfwm_driver_assigned_status_name = $status;
                            }
                            break;
                    }
                }
            }
        }
        $drivers = DDFWM_Driver::ddfwm_get_drivers( $vendor_id, 'all' );
        $html = '
		<form method="POST" name="ddfwm_orders_form" id="ddfwm_orders_form" action="' . ddfwm_vendors_page_url( 'ddfwm_screen=orders' ) . '">
		<input type="hidden" name="ddfwm_wpnonce" value="' . wp_create_nonce( 'ddfwm-nonce' ) . '">
		<div class="row">
		<div class="col-12">
		<!-- Nav tabs -->
		<ul class="nav nav-tabs" id="myTab" role="tablist">
			<li class="nav-item" role="presentation">
				<a class="nav-link active" id="filter-tab" data-bs-toggle="tab" data-bs-target="#filter" type="button" role="tab" aria-controls="filter" aria-selected="true">' . esc_html( __( 'Filter', 'ddfwm' ) ) . '</a>
			</li>
			<li class="nav-item" role="presentation">
				<a class="nav-link" id="filter-tab" data-bs-toggle="tab" data-bs-target="#bulk-action" type="button" role="tab" aria-controls="bulk-action" aria-selected="true">' . ddfwm_premium_feature( '' ) . esc_html( __( 'Bulk actions', 'ddfwm' ) ) . '</a>
		    </li>
		</ul>
		<!-- Tab panes -->
		<div class="tab-content" style="margin-top:10px;">
		<div class="tab-pane " id="bulk-action" role="tabpanel" aria-labelledby="bulk-action-tab">
		<div class="row">';
        if ( ddfwm_is_free() ) {
            $content = '<div class="col-12 col-md" style="margin-bottom:10px">' . '<p>' . ddfwm_premium_feature( '' ) . ' ' . esc_html( __( 'Bulk assign drivers to orders.', 'ddfwm' ) ) . '</p>' . '<p>' . ddfwm_premium_feature( '' ) . ' ' . esc_html( __( 'Bulk update order statuses.', 'ddfwm' ) ) . '</p>';
            $html .= '<div class="container">' . ddfwm_premium_feature_notice_content( $content ) . '</div></div>';
        }
        $html .= '</div></div>
<div class="tab-pane active" id="filter" role="tabpanel" aria-labelledby="filter-tab">
<div class="row">
 

<div class="col-12 col-md" style="margin-bottom:10px">
			<select class="form-select" id="ddfwm_orders_status" name="ddfwm_orders_status">
				<option value="">' . esc_attr( __( 'All Statuses', 'ddfwm' ) ) . '</option>
				<option ' . selected( get_option( 'lddfw_driver_assigned_status', '' ), $ddfwm_orders_status, false ) . ' value="' . get_option( 'lddfw_driver_assigned_status', '' ) . '">' . $ddfwm_driver_assigned_status_name . '</option>
				<option ' . selected( get_option( 'lddfw_out_for_delivery_status', '' ), $ddfwm_orders_status, false ) . ' value="' . get_option( 'lddfw_out_for_delivery_status', '' ) . '"> ' . $ddfwm_out_for_delivery_status_name . ' </option>
				<option ' . selected( get_option( 'lddfw_failed_attempt_status', '' ), $ddfwm_orders_status, false ) . ' value="' . get_option( 'lddfw_failed_attempt_status', '' ) . '">' . $ddfwm_failed_attempt_status_name . '</option>
				<option ' . selected( get_option( 'lddfw_delivered_status', '' ), $ddfwm_orders_status, false ) . ' value="' . esc_attr( get_option( 'lddfw_delivered_status' ) ) . '">' . esc_html( __( 'Delivered', 'ddfwm' ) ) . '</option>

			</select>
		</div>';
        $date_style = ( get_option( 'lddfw_delivered_status', '' ) === $ddfwm_orders_status ? '' : 'display:none' );
        $html .= '<div class="col-12 col-md ddfwm_dates_range_col"   style="' . $date_style . ';margin-bottom:10px">

	 
			<select class="form-select" id="ddfwm_dates_range" name="ddfwm_dates_range" >
				<option value="">' . esc_attr( __( 'All Dates', 'ddfwm' ) ) . '</option>	
				<option ' . selected( date_i18n( 'Y-m-d' ) . ',' . date_i18n( 'Y-m-d' ), $ddfwm_dates, false ) . ' value="' . date_i18n( 'Y-m-d' ) . ',' . date_i18n( 'Y-m-d' ) . '">' . esc_html( __( 'Today', 'ddfwm' ) ) . '</option>
				<option ' . selected( date_i18n( 'Y-m-d', strtotime( '-1 days' ) ) . ',' . date_i18n( 'Y-m-d', strtotime( '-1 days' ) ), $ddfwm_dates, false ) . ' value="' . date_i18n( 'Y-m-d', strtotime( '-1 days' ) ) . ',' . date_i18n( 'Y-m-d', strtotime( '-1 days' ) ) . '">' . esc_html( __( 'Yesterday', 'ddfwm' ) ) . '</option>
				<option ' . selected( date_i18n( 'Y-m-d', strtotime( 'first day of this month' ) ) . ',' . date_i18n( 'Y-m-d', strtotime( 'last day of this month' ) ), $ddfwm_dates, false ) . ' value="' . date_i18n( 'Y-m-d', strtotime( 'first day of this month' ) ) . ',' . date_i18n( 'Y-m-d', strtotime( 'last day of this month' ) ) . '">' . esc_html( __( 'This month', 'ddfwm' ) ) . '</option>
				<option ' . selected( date_i18n( 'Y-m-d', strtotime( 'first day of last month' ) ) . ',' . date_i18n( 'Y-m-d', strtotime( 'last day of last month' ) ), $ddfwm_dates, false ) . ' value="' . date_i18n( 'Y-m-d', strtotime( 'first day of last month' ) ) . ',' . date_i18n( 'Y-m-d', strtotime( 'last day of last month' ) ) . '">' . esc_html( __( 'Last month', 'ddfwm' ) ) . '</option>
			</select>
		</div>

		<div class="col-12 col-md" style="margin-bottom:10px">
			<select name="ddfwm_orders_filter"  id="ddfwm_orders_filter" class="form-select">
				<option value="">' . __( 'Filter By', 'ddfwm' ) . '</option>
				<option ' . selected( '-1', $ddfwm_orders_filter, false ) . ' value="-1" ';
        $html .= ( '-1' == $ddfwm_orders_filter ? 'selected' : '' );
        $html .= '>' . __( 'With drivers', 'lddfw' ) . '</option>
				<option ' . selected( '-2', $ddfwm_orders_filter, false ) . ' value="-2" ';
        $html .= ( '-2' == $ddfwm_orders_filter ? 'selected' : '' );
        $html .= '>' . __( 'Without drivers', 'lddfw' ) . '</option>
				';
        $html .= '<optgroup label="' . esc_attr( __( 'Drivers', 'lddfw' ) ) . '"></optgroup>';
        foreach ( $drivers as $driver ) {
            $driver_name = $driver->display_name;
            $selected = ( strval( $driver->ID ) === $ddfwm_orders_filter ? 'selected' : '' );
            $html .= '<option ' . esc_attr( $selected ) . ' value="' . esc_attr( $driver->ID ) . '">' . esc_html( $driver_name ) . '</option>';
        }
        $html .= '
			</select>
		</div>';
        $html .= '<div class="col-12 col-md-2"><button class="btn btn-primary" name="ddfwm_orders_filter_btn" id="ddfwm_orders_filter_btn" type="submit">' . esc_html( __( 'Filter', 'lddfw' ) ) . '</button></div>';
        $html .= '</div></div></div><div class="row"><div class="ddfwm_date_range col-12">';
        if ( '' === $ddfwm_dates ) {
            $html .= date_i18n( lddfw_date_format( 'date' ) );
            $from_date = date_i18n( 'Y-m-d' );
            $to_date = date_i18n( 'Y-m-d' );
        } else {
            $ddfwm_dates_array = explode( ',', $ddfwm_dates );
            if ( 1 < count( $ddfwm_dates_array ) ) {
                if ( $ddfwm_dates_array[0] === $ddfwm_dates_array[1] ) {
                    $html .= date_i18n( lddfw_date_format( 'date' ), strtotime( $ddfwm_dates_array[0] ) );
                    $from_date = date_i18n( 'Y-m-d', strtotime( $ddfwm_dates_array[0] ) );
                    $to_date = date_i18n( 'Y-m-d', strtotime( $ddfwm_dates_array[0] ) );
                } else {
                    $html .= date_i18n( lddfw_date_format( 'date' ), strtotime( $ddfwm_dates_array[0] ) ) . ' - ' . date_i18n( lddfw_date_format( 'date' ), strtotime( $ddfwm_dates_array[1] ) );
                    $from_date = date_i18n( 'Y-m-d', strtotime( $ddfwm_dates_array[0] ) );
                    $to_date = date_i18n( 'Y-m-d', strtotime( $ddfwm_dates_array[1] ) );
                }
            } else {
                $html .= date_i18n( lddfw_date_format( 'date' ), strtotime( $ddfwm_dates_array[0] ) );
                $from_date = date_i18n( 'Y-m-d', strtotime( $ddfwm_dates_array[0] ) );
                $to_date = date_i18n( 'Y-m-d', strtotime( $ddfwm_dates_array[0] ) );
            }
        }
        $html .= '</div>';
        // Orders query.
        $orders_per_page = 20;
        $counter = ( $ddfwm_page > 1 ? $orders_per_page * $ddfwm_page - $orders_per_page + 1 : 1 );
        // Status.
        if ( '' !== $ddfwm_orders_status ) {
            $status_array = array($ddfwm_orders_status);
        } else {
            $status_array = array(
                get_option( 'lddfw_driver_assigned_status', '' ),
                get_option( 'lddfw_out_for_delivery_status', '' ),
                get_option( 'lddfw_failed_attempt_status', '' ),
                get_option( 'lddfw_delivered_status', '' )
            );
        }
        // Filter by orders without drivers.
        $no_driver_array = array();
        if ( '-2' === $ddfwm_orders_filter ) {
            $no_driver_array = array(
                'relation' => 'or',
                array(
                    'key'     => 'lddfw_driverid',
                    'value'   => '-1',
                    'compare' => '=',
                ),
                array(
                    'key'     => 'lddfw_driverid',
                    'value'   => '',
                    'compare' => '=',
                ),
                array(
                    'key'     => 'lddfw_driverid',
                    'compare' => 'NOT EXISTS',
                ),
            );
        }
        // Filter by orders without drivers.
        $filter_array = array();
        if ( '-1' === $ddfwm_orders_filter ) {
            $filter_array = array(
                'relation' => 'and',
                array(
                    'key'     => 'lddfw_driverid',
                    'value'   => '-1',
                    'compare' => '!=',
                ),
                array(
                    'key'     => 'lddfw_driverid',
                    'compare' => 'EXISTS',
                ),
            );
        }
        // Filter by driver id.
        $driver_array = array();
        if ( 0 < intval( $ddfwm_orders_filter ) ) {
            $driver_array = array(
                'key'     => 'lddfw_driverid',
                'value'   => $ddfwm_orders_filter,
                'compare' => '=',
            );
        }
        $date_array = array();
        // Filter for delivered date range.
        if ( '' !== $ddfwm_from_date && '' !== $ddfwm_to_date ) {
            $date_array = array(
                'relation' => 'and',
                array(
                    'key'     => 'lddfw_delivered_date',
                    'value'   => $ddfwm_from_date,
                    'compare' => '>=',
                    'type'    => 'DATE',
                ),
                array(
                    'key'     => 'lddfw_delivered_date',
                    'value'   => $ddfwm_to_date,
                    'compare' => '<=',
                    'type'    => 'DATE',
                ),
            );
        }
        $params = array(
            'posts_per_page' => $orders_per_page,
            'post_status'    => $status_array,
            'post_type'      => 'shop_order',
            'paginate'       => true,
            'paged'          => $ddfwm_page,
            'return'         => 'ids',
            'orderby'        => array(
                'ID' => 'DESC',
            ),
        );
        $vendor_array = array();
        // Vendor.
        switch ( DDFWM_MULTIVENDOR ) {
            case 'dokan':
                $vendor_array = array(
                    'key'     => '_dokan_vendor_id',
                    'value'   => $vendor_id,
                    'compare' => '=',
                );
                break;
            case 'wcmp':
                $vendor_array = array(
                    'key'     => '_vendor_id',
                    'value'   => $vendor_id,
                    'compare' => '=',
                );
                break;
            case 'wcfm':
                $sql = "SELECT order_id FROM {$wpdb->prefix}wcfm_marketplace_orders";
                $sql .= ' WHERE 1=1';
                $sql .= ' AND `vendor_id` = ' . $vendor_id;
                $vendor_orders_list = $wpdb->get_results( $sql );
                if ( !empty( $vendor_orders_list ) ) {
                    $vendor_orders = array();
                    foreach ( $vendor_orders_list as $vendor_order_list ) {
                        $vendor_orders[] = $vendor_order_list->order_id;
                    }
                    $params['post__in'] = $vendor_orders;
                } else {
                    $params['post__in'] = 0;
                }
                break;
            default:
                $params['post__in'] = 0;
                break;
        }
        $params['meta_query'] = array(
            'relation' => 'AND',
            $vendor_array,
            $date_array,
            $driver_array,
            $filter_array,
            $no_driver_array,
        );
        if ( ddfwm_is_hpos_enabled() ) {
            $orders = wc_get_orders( $params );
            $orders_array = $orders->orders;
        } else {
            $orders = new WP_Query($params);
            $orders_array = array_map( function ( $order ) {
                return $order->ID;
            }, $orders->posts );
        }
        $date_format = lddfw_date_format( 'date' );
        $time_format = lddfw_date_format( 'time' );
        $html .= '
			</div>

			<div class="row">
			<div class="col-12">';
        if ( $orders ) {
            // Pagination.
            $base = ddfwm_vendors_page_url( 'ddfwm_screen=orders&ddfwm_orders_filter=' . $ddfwm_orders_filter . '&ddfwm_orders_status=' . $ddfwm_orders_status . '&ddfwm_from_date=' . $ddfwm_from_date . '&ddfwm_to_date=' . $ddfwm_to_date ) . '&ddfwm_page=%#%';
            $pagination = paginate_links( array(
                'base'         => $base,
                'total'        => $orders->max_num_pages,
                'current'      => $ddfwm_page,
                'format'       => '&ddfwm_page=%#%',
                'show_all'     => false,
                'type'         => 'array',
                'end_size'     => 2,
                'mid_size'     => 0,
                'prev_next'    => true,
                'prev_text'    => sprintf( '<i></i> %1$s', __( '<<', 'ddfwm' ) ),
                'next_text'    => sprintf( '%1$s <i></i>', __( '>>', 'ddfwm' ) ),
                'add_args'     => false,
                'add_fragment' => '',
            ) );
            if ( !empty( $pagination ) ) {
                $html .= '<div class="pagination text-sm-center"><nav aria-label="Page navigation" style="width:100%"><ul class="pagination justify-content-center">';
                foreach ( $pagination as $page ) {
                    $html .= "<li class='page-item ";
                    if ( strpos( $page, 'current' ) !== false ) {
                        $html .= ' active';
                    }
                    $html .= "'> " . str_replace( 'page-numbers', 'page-link', $page ) . '</li>';
                }
                $html .= '</nav></div>';
            }
            $html .= '	<div class="table-responsive"><table class="table table-striped table-hover">
				<thead class="table-dark">
					<tr>
						<th scope="row">
						<div class="form-check custom-checkbox">
								<input value="" id="ddfwm_multi_checkbox" type="checkbox" data="order_checkbox" class="form-check-input">
								<label class="custom-control-label" for="ddfwm_multi_checkbox"></label>
							</div>
						</th>
						<th scope="col">#</th>
						<th scope="col">' . esc_html( __( 'Order', 'ddfwm' ) ) . '</th>
						<th scope="col">' . esc_html( __( 'Date', 'ddfwm' ) ) . '</th>
						<th scope="col">' . esc_html( __( 'Status', 'ddfwm' ) ) . '</th>
						<th scope="col">' . esc_html( __( 'Driver', 'ddfwm' ) ) . '</th>
					</tr>
				</thead>
				<tbody>';
            // Results.
            foreach ( $orders_array as $order_id ) {
                $order = wc_get_order( $order_id );
                $order_date = $order->get_date_created()->format( lddfw_date_format( 'date' ) );
                $order_status = $order->get_status();
                $order_status_name = wc_get_order_status_name( $order_status );
                $billing_address_1 = $order->get_billing_address_1();
                $billing_address_2 = $order->get_billing_address_2();
                $billing_city = $order->get_billing_city();
                $billing_state = $order->get_billing_state();
                $billing_postcode = $order->get_billing_postcode();
                $billing_country = $order->get_billing_country();
                $billing_first_name = $order->get_billing_first_name();
                $billing_last_name = $order->get_billing_last_name();
                $billing_company = $order->get_billing_company();
                $shipping_company = $order->get_shipping_company();
                $shipping_first_name = $order->get_shipping_first_name();
                $shipping_last_name = $order->get_shipping_last_name();
                $shipping_address_1 = $order->get_shipping_address_1();
                $shipping_address_2 = $order->get_shipping_address_2();
                $shipping_city = $order->get_shipping_city();
                $shipping_state = $order->get_shipping_state();
                $shipping_postcode = $order->get_shipping_postcode();
                $shipping_country = $order->get_shipping_country();
                /**
                 * If shipping info is missing if show the billing info
                 */
                if ( '' === $shipping_first_name && '' === $shipping_address_1 ) {
                    $shipping_first_name = $billing_first_name;
                    $shipping_last_name = $billing_last_name;
                    $shipping_address_1 = $billing_address_1;
                    $shipping_address_2 = $billing_address_2;
                    $shipping_city = $billing_city;
                    $shipping_state = $billing_state;
                    $shipping_postcode = $billing_postcode;
                    $shipping_country = $billing_country;
                    $shipping_company = $billing_company;
                }
                $order_driverid = $order->get_meta( 'lddfw_driverid' );
                $driver = get_userdata( $order_driverid );
                $driver_name = ( !empty( $driver ) ? $driver->display_name : '' );
                $route = $order->get_meta( 'ddfwm_order_route' );
                $delivered_date = $order->get_meta( 'ddfwm_delivered_date' );
                $shippingaddress = $shipping_first_name . ' ' . $shipping_last_name . '<br>';
                if ( '' != $shipping_company ) {
                    $shippingaddress .= $shipping_company . '<br>';
                }
                $shippingaddress .= $shipping_address_1;
                if ( '' !== $shipping_address_2 ) {
                    $shippingaddress .= ', ' . $shipping_address_2;
                }
                $distance = '';
                if ( is_array( $route ) ) {
                    $distance = $route['distance_text'];
                }
                $html .= '
				<tr>
				<th scope="row">
				<div class="custom-control custom-checkbox">
						<input name="ddfwm_order_id[]" value="' . $order_id . '" id="ddfwm_order_id_' . $counter . '" type="checkbox"  class="order_checkbox form-check-input" >
						<label class="custom-control-label" for="ddfwm_order_id_' . $counter . '"></label>
					</div>
				</th>
				<td scope="row">' . $counter . '</td>
				<td><a href="' . ddfwm_vendors_page_url( 'ddfwm_screen=order&ddfwm_orderid=' . $order_id ) . '" >' . esc_html( $order->get_order_number() ) . '</a></td>
				<td>' . esc_html( $order_date ) . '</td>
				<td>' . esc_html( $order_status_name ) . '</td>
				<td>' . $driver_name . '</td>
			  </tr>';
                $counter++;
            }
            $html .= '</table></div></form>';
            if ( !empty( $pagination ) ) {
                $html .= '<div class="pagination text-sm-center"><nav aria-label="Page navigation" style="width:100%"><ul class="pagination justify-content-center">';
                foreach ( $pagination as $page ) {
                    $html .= "<li class='page-item ";
                    if ( strpos( $page, 'current' ) !== false ) {
                        $html .= ' active';
                    }
                    $html .= "'> " . str_replace( 'page-numbers', 'page-link', $page ) . '</li>';
                }
                $html .= '</nav></div>';
            }
        } else {
            $html .= '<div class="ddfwm_box min ddfwm_no_orders"><p>' . esc_html( __( 'There are no orders.', 'ddfwm' ) ) . '</p></div>';
        }
        $html .= '</div></div> ';
        return $html;
    }

}
