<?php

/**
 * The Delivery Driver Dashboard Shortcode.
 *
 * @link       https://www.wpsaad.com
 * @since      1.0.0
 *
 * @package    ODDW
 * @subpackage ODDW/public/shortcodes
 */

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

function oddw_get_allowed_html() {
	return array(
		'a' => array(
			'href' => true,
			'class' => true,
			'target' => true,
			'rel' => true,
		),
		'div' => array( 'class' => true, 'id' => true ),
		'span' => array( 'class' => true ),
		'p' => array( 'class' => true ),
		'h3' => array( 'class' => true ),
		'h4' => array( 'class' => true ),
		'strong' => array(),
		'em' => array(),
		'table' => array( 'class' => true ),
		'thead' => array(),
		'tbody' => array(),
		'tfoot' => array(),
		'tr' => array( 'class' => true ),
		'td' => array( 'class' => true, 'colspan' => true ),
		'th' => array( 'class' => true, 'colspan' => true ),
		'form' => array( 'method' => true, 'action' => true, 'id' => true, 'class' => true ),
		'label' => array( 'for' => true, 'class' => true ),
		'input' => array(
			'type' => true,
			'name' => true,
			'value' => true,
			'placeholder' => true,
			'class' => true,
			'id' => true,
			'checked' => true,
		),
		'select' => array( 'name' => true, 'class' => true, 'id' => true ),
		'option' => array( 'value' => true, 'selected' => true ),
		'button' => array( 'type' => true, 'class' => true ),
	);
}

function oddw_delivery_drivers_dashboard_shortcode()
{
	$output = '';
	
	// Check if WooCommerce is active
	if (!class_exists('WooCommerce')) {
        $output .= '<p>' . esc_html__('WooCommerce is required for this shortcode to work.', 'orders-delivery-drivers-for-woocommerce') . '</p>';
        return $output;
    }

	// Check if user is logged in.
	if (is_user_logged_in()) {
		// Get the user ID.
		$user_id = get_current_user_id();

		// Get the user object.
		$user_meta = get_userdata($user_id);

		if (0 != $user_id) {

			// Get all the user roles as an array.
			$user_roles = $user_meta->roles;

			// Check if the role you're interested in, is present in the array.
			if (in_array('driver', $user_roles, true)) {

				// Display driver availability switcher
				do_action('oddw_driver_dashboard_top');

				// Initialize order variables
				$order_id = 0;
				$order = null;
				$driver_id = '';
				
				// Verify nonce FIRST before reading orderid
				if ( isset( $_GET['oddw_view_order_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['oddw_view_order_nonce'] ) ), 'oddw_view_order' ) ) {
					$order_id = isset($_GET['orderid']) ? absint( wp_unslash( $_GET['orderid'] ) ) : 0;
					
					if ($order_id) {
						$order = wc_get_order($order_id);
						if ($order) {
							$driver_id = $order->get_meta('oddw_driver_id', true);
							// Verify that current user is the assigned driver
							if ( absint( $driver_id ) !== $user_id ) {
								$order_id = 0;
								$order = null;
								$driver_id = '';
							}
						}
					}
				}
				// Display order info if ?orderid is set and driver is assigned.
				if ($order_id && ($driver_id == $user_id)) {

					// Get store address using helper function
					$store_address = oddw_get_store_address();

					// Get an instance of the WC_Order object
					$order = wc_get_order($order_id);

					if (! $order) {
						return;
					}

					// Get the order data.
					$order_data = $order->get_data();

					// Specific order data.
					$order_id                   = $order->get_id();
					$order_parent_id            = $order->get_parent_id();
					$order_status               = $order->get_status();
					$order_currency             = $order->get_currency();
					$order_version              = $order->get_version();
					$order_payment_method       = $order->get_payment_method();
					$order_payment_method_title = $order->get_payment_method_title();
					$order_date_created         = $order->get_date_created() ? $order->get_date_created()->date('m-d-y') : '';
					$order_time_created         = $order->get_date_created() ? $order->get_date_created()->date('h:i a') : '';
					$order_discount_total       = $order->get_discount_total();
					$order_discount_tax         = $order->get_discount_tax();
					$order_shipping_total       = $order->get_shipping_total();
					$order_shipping_tax         = $order->get_shipping_tax();
					$order_cart_tax             = $order->get_cart_tax();
					$order_total                = $order->get_total();
					$order_total_tax            = $order->get_total_tax();

					// Get the order items.
					$order_items = $order->get_items();

					// Get the order billing data.
					$order_billing_first_name = $order->get_billing_first_name();
					$order_billing_last_name  = $order->get_billing_last_name();
					$order_billing_company    = $order->get_billing_company();
					$order_billing_address_1  = $order->get_billing_address_1();
					$order_billing_address_2  = $order->get_billing_address_2();
					$order_billing_city       = $order->get_billing_city();
					$order_billing_state      = $order->get_billing_state();
					$order_billing_postcode   = $order->get_billing_postcode();
					$order_billing_country    = $order->get_billing_country();
					$order_billing_email      = $order->get_billing_email();
					$order_billing_phone      = $order->get_billing_phone();

					// Get the order shipping data.
					$order_shipping_first_name = $order->get_shipping_first_name();
					$order_shipping_last_name  = $order->get_shipping_last_name();
					$order_shipping_company    = $order->get_shipping_company();
					$order_shipping_address_1  = $order->get_shipping_address_1();
					$order_shipping_address_2  = $order->get_shipping_address_2();
					$order_shipping_city       = $order->get_shipping_city();
					$order_shipping_state      = $order->get_shipping_state();
					$order_shipping_postcode   = $order->get_shipping_postcode();
					$order_shipping_country    = $order->get_shipping_country();

					// Get the order notes.
					$order_notes = $order->get_customer_order_notes();

					// Get the order currency symbol.
					$currency_symbol = get_woocommerce_currency_symbol($order_currency);

					$output .= '<div class="oddw-orders">';
					if (isset($order_id)) {
						$output .= '<h3 class="oddw">' . esc_html__('Order #', 'orders-delivery-drivers-for-woocommerce') . esc_html(apply_filters('oddw_order_number', $order_id)) . ' <span class="' . esc_attr($order_status) . '">' . esc_html(wc_get_order_status_name($order_status)) . '</span></h3>';
					}
					$output .= oddw_render_customer_contact_buttons($order);
					$output .= oddw_render_delivery_address($order, $store_address);
					$output .= oddw_render_order_details_table($order);
					$output .= oddw_render_order_items_table($order);
					$output .= wp_kses(
						apply_filters( 'oddw_driver_dashboard_change_status_forms', oddw_driver_dashboard_change_status_forms() ),
						oddw_get_allowed_html()
					);
					$output .= '</div>';
				} else {
					// Get assigned orders for this driver
					$assigned_orders = oddw_query_orders(array(
						'type' => 'shop_order',
						'status' => 'any',
						'limit' => -1,
						'meta_key' => 'oddw_driver_id',
						'meta_value' => $user_id,
					));

					if ($assigned_orders) {
						// Display assigned orders
						$output .= '<h3 class="oddw assigned-orders">' . esc_html__('Assigned Orders', 'orders-delivery-drivers-for-woocommerce') . '</h3>';
						$output .= '<table class="oddw-dashboard">';
						$output .= '<thead><tr><td>' . esc_html__('ID', 'orders-delivery-drivers-for-woocommerce') . '</td><td>' . esc_html__('Date', 'orders-delivery-drivers-for-woocommerce') . '</td><td>' . esc_html__('Status', 'orders-delivery-drivers-for-woocommerce') . '</td><td>' . esc_html__('Total', 'orders-delivery-drivers-for-woocommerce') . '</td></tr></thead>';
						$output .= '<tbody>';
						$has_assigned_orders = false;
						foreach ($assigned_orders as $driver_order) {
							if ( is_object( $driver_order ) && method_exists( $driver_order, 'get_id' ) ) {
								$driver_order_id = $driver_order->get_id();
								$driver_order_obj = $driver_order;
							} else {
								$driver_order_id = $driver_order->ID;
								$driver_order_obj = wc_get_order($driver_order_id);
							}
							$order_status = $driver_order_obj->get_status();
							if ( 'completed' === $order_status ) {
								continue;
							}
							$has_assigned_orders = true;
							$order_date_created = $driver_order_obj->get_date_created() ? $driver_order_obj->get_date_created()->date('m-d-Y') : '';
							$currency_code = $driver_order_obj->get_currency();
							$currency_symbol = get_woocommerce_currency_symbol($currency_code);
							$order_total = $driver_order_obj->get_total();
							$output .= '<tr>';
							$view_nonce = wp_create_nonce( 'oddw_view_order' );
							$order_url = add_query_arg( array( 'orderid' => $driver_order_id, 'oddw_view_order_nonce' => $view_nonce ) );
							$output .= '<td><a href="' . esc_url( $order_url ) . '">' . esc_html(apply_filters('oddw_order_number', $driver_order_id)) . '</a></td>';
							$output .= '<td>' . esc_html($order_date_created) . '</td>';
							$output .= '<td>' . esc_html(wc_get_order_status_name($order_status)) . '</td>';
							if (isset($order_total)) {
								$output .= '<td>' . esc_html($currency_symbol) . esc_html($order_total) . '</td>';
							} else {
								$output .= '<td>-</td>';
							}
							$output .= '</tr>';
						}
						if ( ! $has_assigned_orders ) {
							$output .= '<tr><td colspan="4">' . esc_html__('No assigned orders found.', 'orders-delivery-drivers-for-woocommerce') . '</td></tr>';
						}
						$output .= '</tbody>';
						$output .= '</table>';
						$output .= '<h4 class="oddw assigned-orders">' . esc_html__('Completed Orders', 'orders-delivery-drivers-for-woocommerce') . '</h4>';
						$output .= '<table class="oddw-dashboard">';
						$output .= '<thead><tr><td>' . esc_html__('ID', 'orders-delivery-drivers-for-woocommerce') . '</td><td>' . esc_html__('Date', 'orders-delivery-drivers-for-woocommerce') . '</td><td>' . esc_html__('Status', 'orders-delivery-drivers-for-woocommerce') . '</td><td>' . esc_html__('Total', 'orders-delivery-drivers-for-woocommerce') . '</td></tr></thead>';
						$output .= '<tbody>';
						$has_completed_orders = false;
						foreach ($assigned_orders as $driver_order) {
							if ( is_object( $driver_order ) && method_exists( $driver_order, 'get_id' ) ) {
								$driver_order_id = $driver_order->get_id();
								$driver_order_obj = $driver_order;
							} else {
								$driver_order_id = $driver_order->ID;
								$driver_order_obj = wc_get_order($driver_order_id);
							}
							$order_status = $driver_order_obj->get_status();
							if ( 'completed' !== $order_status ) {
								continue;
							}
							$has_completed_orders = true;
							$order_date_created = $driver_order_obj->get_date_created() ? $driver_order_obj->get_date_created()->date('m-d-Y') : '';
							$currency_code = $driver_order_obj->get_currency();
							$currency_symbol = get_woocommerce_currency_symbol($currency_code);
							$order_total = $driver_order_obj->get_total();
							$output .= '<tr>';
							$view_nonce = wp_create_nonce( 'oddw_view_order' );
							$order_url = add_query_arg( array( 'orderid' => $driver_order_id, 'oddw_view_order_nonce' => $view_nonce ) );
							$output .= '<td><a href="' . esc_url( $order_url ) . '">' . esc_html(apply_filters('oddw_order_number', $driver_order_id)) . '</a></td>';
							$output .= '<td>' . esc_html($order_date_created) . '</td>';
							$output .= '<td>' . esc_html(wc_get_order_status_name($order_status)) . '</td>';
							if (isset($order_total)) {
								$output .= '<td>' . esc_html($currency_symbol) . esc_html($order_total) . '</td>';
							} else {
								$output .= '<td>-</td>';
							}
							$output .= '</tr>';
						}
						if ( ! $has_completed_orders ) {
							$output .= '<tr><td colspan="4">' . esc_html__('No completed orders found.', 'orders-delivery-drivers-for-woocommerce') . '</td></tr>';
						}
						$output .= '</tbody>';
						$output .= '</table>';
					} else {
						$output .= '<h3 class="oddw assigned-orders">' . esc_html__('Assigned Orders', 'orders-delivery-drivers-for-woocommerce') . '</h3>';
						$output .= '<p>' . esc_html__('You do not have any assigned orders.', 'orders-delivery-drivers-for-woocommerce') . '</p>';
					}
				}
			} else {
				$output .= '<p>' . esc_html__('You are not a driver.', 'orders-delivery-drivers-for-woocommerce') . '</p>';
			}
		}
	} else {
		$login_form = wp_login_form( array( 'echo' => false ) );
		$login_form = apply_filters( 'oddw_dashboard_login_form', $login_form );
		$output .= wp_kses( $login_form, oddw_get_allowed_html() );
	}
	
	return $output;
}

/**
 * Backward-compatible wrapper.
 *
 * @deprecated 2.4.3 Use oddw_delivery_drivers_dashboard_shortcode() instead.
 */
function delivery_drivers_dashboard_shortcode() {
	return oddw_delivery_drivers_dashboard_shortcode();
}

add_shortcode('oddw_delivery_drivers_dashboard', 'oddw_delivery_drivers_dashboard_shortcode');
add_shortcode('oddw_dashboard', 'oddw_delivery_drivers_dashboard_shortcode');
