<?php

/**
 * Helper functions.
 *
 * @link       https://www.wpsaad.com
 * @since      2.0
 *
 * @package    ODDW
 * @subpackage ODDW/includes/functions
 */
/**
 * Check if WooCommerce HPOS (Custom Order Tables) is enabled.
 *
 * @return bool
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
function oddw_is_hpos_enabled() {
    if ( !class_exists( '\\Automattic\\WooCommerce\\Internal\\DataStores\\Orders\\CustomOrdersTableController' ) ) {
        return false;
    }
    if ( !function_exists( 'wc_get_container' ) ) {
        return false;
    }
    $controller = wc_get_container()->get( \Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController::class );
    if ( !$controller ) {
        return false;
    }
    return $controller->custom_orders_table_usage_is_enabled();
}

/**
 * Get an array of pages suitable for select options.
 *
 * @return array
 */
function oddw_get_pages_options() {
    $pages = get_pages( array(
        'post_status' => array('publish', 'draft'),
    ) );
    $options = array(
        '' => __( '— Select —', 'orders-delivery-drivers-for-woocommerce' ),
    );
    foreach ( $pages as $p ) {
        $options[$p->ID] = $p->post_title;
    }
    return $options;
}

/**
 * Get stored page id for a given shortcode type.
 *
 * @param string $type
 * @return int|null
 */
function oddw_get_page_id(  $type  ) {
    $key = 'oddw_settings_' . sanitize_key( $type ) . '_page_id';
    $val = get_option( $key );
    return ( $val ? absint( $val ) : null );
}

/**
 * Set stored page id for a given shortcode type.
 *
 * @param string $type
 * @param int $page_id
 * @return bool
 */
function oddw_set_page_id(  $type, $page_id  ) {
    $key = 'oddw_settings_' . sanitize_key( $type ) . '_page_id';
    return update_option( $key, absint( $page_id ) );
}

/**
 * Check whether a page id is already assigned to another shortcode type.
 *
 * @param int $page_id
 * @param string|null $exclude_type
 * @return bool True if unique (not used by other types), false if conflict.
 */
function oddw_is_page_id_unique(  $page_id, $exclude_type = null  ) {
    if ( !$page_id ) {
        return true;
    }
    $types = array('dashboard', 'monitor', 'application');
    foreach ( $types as $type ) {
        if ( $exclude_type && $type === $exclude_type ) {
            continue;
        }
        $existing = oddw_get_page_id( $type );
        if ( $existing && absint( $existing ) === absint( $page_id ) ) {
            return false;
        }
    }
    return true;
}

/**
 * Normalize order query args for wc_get_orders, supporting legacy-style keys.
 *
 * @param array $args
 * @return array
 */
function oddw_normalize_order_query_args(  $args  ) {
    if ( isset( $args['post_type'] ) && !isset( $args['type'] ) ) {
        $args['type'] = $args['post_type'];
        unset($args['post_type']);
    }
    if ( isset( $args['posts_per_page'] ) && !isset( $args['limit'] ) ) {
        $args['limit'] = $args['posts_per_page'];
        unset($args['posts_per_page']);
    }
    if ( isset( $args['post_status'] ) && !isset( $args['status'] ) ) {
        $args['status'] = $args['post_status'];
        unset($args['post_status']);
    }
    if ( isset( $args['status'] ) ) {
        if ( is_array( $args['status'] ) ) {
            $args['status'] = array_map( function ( $status ) {
                return ( is_string( $status ) ? ltrim( $status, 'wc-' ) : $status );
            }, $args['status'] );
        } elseif ( is_string( $args['status'] ) ) {
            $args['status'] = ltrim( $args['status'], 'wc-' );
        }
    }
    return $args;
}

/**
 * HPOS-safe order query wrapper.
 *
 * @param array $args
 * @return array
 */
function oddw_query_orders(  $args  ) {
    $args = oddw_normalize_order_query_args( $args );
    if ( !isset( $args['return'] ) ) {
        $args['return'] = 'objects';
    }
    return wc_get_orders( $args );
}

/**
 * Add convenient page labels in the Pages list via the built-in "post states" UI.
 * Labels are derived from saved page IDs for each shortcode.
 *
 * @param array   $states
 * @param WP_Post $post
 * @return array
 */
function oddw_display_page_state(  $states, $post  ) {
    if ( !$post ) {
        return $states;
    }
    $map = array(
        'dashboard'   => ( function_exists( 'oddw_get_page_id' ) ? oddw_get_page_id( 'dashboard' ) : get_option( 'oddw_settings_dashboard_page_id' ) ),
        'monitor'     => ( function_exists( 'oddw_get_page_id' ) ? oddw_get_page_id( 'monitor' ) : get_option( 'oddw_settings_monitor_page_id' ) ),
        'application' => ( function_exists( 'oddw_get_page_id' ) ? oddw_get_page_id( 'application' ) : get_option( 'oddw_settings_application_page_id' ) ),
    );
    foreach ( $map as $label_key => $page_id ) {
        if ( $page_id && absint( $post->ID ) === absint( $page_id ) ) {
            $label = '';
            if ( 'dashboard' === $label_key ) {
                $label = __( 'Driver Dashboard', 'orders-delivery-drivers-for-woocommerce' );
            } elseif ( 'monitor' === $label_key ) {
                $label = __( 'Orders Monitor', 'orders-delivery-drivers-for-woocommerce' );
            } elseif ( 'application' === $label_key ) {
                $label = __( 'Driver Application', 'orders-delivery-drivers-for-woocommerce' );
            }
            if ( $label ) {
                $states['oddw_' . $label_key] = $label;
            }
        }
    }
    return $states;
}

add_filter(
    'display_post_states',
    'oddw_display_page_state',
    10,
    2
);
/**
 * Change order statuses
 *
 * @since 2.0
 */
//Driver data display on driver dashboard function
// Helper: Render orders table for given statuses
function oddw_render_orders_table(  $orders, $statuses, $label  ) {
    $output = '';
    $output .= '<table class="oddw-dashboard">';
    $output .= '<thead><tr><td>' . __( 'ID', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . __( 'Date', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . __( 'Status', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . __( 'Total', 'orders-delivery-drivers-for-woocommerce' ) . '</td></tr></thead>';
    $output .= '<tbody>';
    $found = false;
    foreach ( $orders as $order ) {
        $order_obj = ( is_object( $order ) ? $order : wc_get_order( $order ) );
        if ( !$order_obj ) {
            continue;
        }
        $order_status = $order_obj->get_status();
        if ( !in_array( $order_status, $statuses, true ) ) {
            continue;
        }
        $found = true;
        $order_id = $order_obj->get_id();
        $order_date_created = ( $order_obj->get_date_created() ? $order_obj->get_date_created()->date( 'm-d-Y' ) : '' );
        $currency_code = $order_obj->get_currency();
        $currency_symbol = get_woocommerce_currency_symbol( $currency_code );
        $order_total = $order_obj->get_total();
        $output .= '<tr>';
        $output .= '<td><a href="?orderid=' . $order_id . '">' . apply_filters( 'oddw_order_number', $order_id ) . '</a></td>';
        $output .= '<td>' . $order_date_created . '</td>';
        $output .= '<td>' . wc_get_order_status_name( $order_status ) . '</td>';
        $output .= '<td>' . $currency_symbol . $order_total . '</td>';
        $output .= '</tr>';
    }
    if ( !$found ) {
        /* translators: %s: orders label */
        $output .= '<tr><td colspan="4">' . sprintf( __( 'No %s orders found.', 'orders-delivery-drivers-for-woocommerce' ), strtolower( $label ) ) . '</td></tr>';
    }
    $output .= '</tbody></table>';
    return $output;
}

function oddw_driver_dashboard_change_statuses() {
    // Get an instance of the WC_Order object.
    $order_id = ( isset( $_GET['orderid'] ) ? absint( wp_unslash( $_GET['orderid'] ) ) : 0 );
    if ( !isset( $_GET['oddw_view_order_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['oddw_view_order_nonce'] ) ), 'oddw_view_order' ) ) {
        return;
    }
    if ( !$order_id ) {
        return;
    }
    $order = wc_get_order( $order_id );
    if ( !$order ) {
        return;
    }
    $order_data = $order->get_data();
    $order_status = $order_data['status'];
    do_action( 'oddw_driver_dashboard_change_statuses_top' );
    // Update order status if marked OUT FOR DELIVERY by Driver.
    if ( isset( $_POST['outfordelivery'] ) ) {
        if ( !isset( $_POST['oddw_out_for_delivery_nonce_field'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['oddw_out_for_delivery_nonce_field'] ) ), 'oddw_out_for_delivery_nonce_action' ) ) {
            return;
        }
        // Update order status.
        $order->update_status( "out-for-delivery" );
        // Add driver note (if added).
        if ( isset( $_POST['outfordeliverymessage'] ) && !empty( $_POST['outfordeliverymessage'] ) ) {
            $message = sanitize_text_field( wp_unslash( $_POST['outfordeliverymessage'] ) );
            /* translators: %s: Driver note message */
            $note = sprintf( __( 'Driver Note: %s', 'orders-delivery-drivers-for-woocommerce' ), $message );
            // Add the note
            $order->add_order_note( $note );
            // Save the data
            $order->save();
        }
        // Run additional functions.
        do_action( 'oddw_email_customer_order_status_out_for_delivery', $order_id );
        // Redirect so the new order details show on the page.
        wp_redirect( get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) . 'driver-dashboard/?orderid=' . $order_id );
        exit;
    }
    // Update order status if marked COMPLETED by Driver.
    if ( isset( $_POST['ordercompleted'] ) ) {
        if ( !isset( $_POST['oddw_order_completed_nonce_field'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['oddw_order_completed_nonce_field'] ) ), 'oddw_order_completed_nonce_action' ) ) {
            return;
        }
        // Update order status.
        $order->update_status( "completed" );
        // Run additional functions.
        do_action( 'oddw_email_admin_order_status_completed', $order_id );
        // Redirect so the new order details show on the page.
        wp_redirect( get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) . 'driver-dashboard/?orderid=' . $order_id );
        exit;
    }
    do_action( 'oddw_driver_dashboard_change_statuses_bottom' );
}

add_action( 'oddw_driver_dashboard_change_status_forms_top', 'oddw_driver_dashboard_change_statuses' );
/**
 * Change order status forms
 * 
 * Displayed on the driver dashboard, allowing the driver to change
 * the status of an order as they deliver to customer.
 * 
 * @since 2.0
 */
function oddw_driver_dashboard_change_status_forms() {
    // Get an instance of the WC_Order object.
    $order_id = 0;
    // 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' ) ) {
        return;
    }
    $order_id = ( isset( $_GET['orderid'] ) ? absint( wp_unslash( $_GET['orderid'] ) ) : 0 );
    if ( !$order_id ) {
        return;
    }
    // Verify that current user is the assigned driver
    $user_id = get_current_user_id();
    $current_driver_id = absint( get_user_meta( $user_id, 'oddw_driver_id', true ) );
    if ( !$current_driver_id ) {
        return;
    }
    $order = wc_get_order( $order_id );
    if ( !$order ) {
        return;
    }
    $order_data = $order->get_data();
    $order_status = $order_data['status'];
    $change_status = '';
    $change_status .= do_action( 'oddw_driver_dashboard_change_status_forms_top' );
    if ( 'driver-assigned' == $order_status ) {
        $change_status = '<h4>' . esc_html__( 'Change Status', 'orders-delivery-drivers-for-woocommerce' ) . '</h4>';
        $change_status .= '<form method="post">';
        $change_status .= '<p><strong>' . esc_html__( 'Message for shop manager / administrator (optional)', 'orders-delivery-drivers-for-woocommerce' ) . '</strong></p>';
        $change_status .= '<input type="text" name="outfordeliverymessage" value="" placeholder="' . esc_attr__( 'Add a message to the order', 'orders-delivery-drivers-for-woocommerce' ) . '" class="oddw-ofdmsg" />';
        $change_status .= '<input type="hidden" name="outfordelivery" value="' . esc_attr( 'out-for-delivery' ) . '" />';
        $change_status .= '<input type="submit" value="' . esc_attr__( 'Out for Delivery', 'orders-delivery-drivers-for-woocommerce' ) . '" class="button oddw-change-status" />';
        $change_status .= wp_nonce_field( 'oddw_out_for_delivery_nonce_action', 'oddw_out_for_delivery_nonce_field' ) . '</form>';
    }
    if ( 'out-for-delivery' == $order_status ) {
        $change_status = '<h4>' . esc_html__( 'Change Status', 'orders-delivery-drivers-for-woocommerce' ) . '</h4>';
        $change_status .= '<form method="post">';
        $change_status .= '<input type="hidden" name="ordercompleted" value="' . esc_attr( 'completed' ) . '" />';
        $change_status .= '<input type="submit" value="' . esc_attr__( 'Completed', 'orders-delivery-drivers-for-woocommerce' ) . '" class="button oddw-change-status" />';
        $change_status .= wp_nonce_field( 'oddw_order_completed_nonce_action', 'oddw_order_completed_nonce_field' ) . '</form>';
    }
    $change_status .= do_action( 'oddw_driver_dashboard_change_status_forms_bottom' );
    return $change_status;
}

/**
 * Checks if a particular user has one or more roles.
 *
 * Returns true on first matching role. Returns false if no roles match.
 *
 * @uses get_userdata()
 * @uses wp_get_current_user()
 *
 * @param array|string $roles Role name (or array of names).
 * @param int $user_id (Optional) The ID of a user. Defaults to the current user.
 * @return bool
 */
function oddw_check_user_roles(  $roles, $user_id = null  ) {
    if ( is_numeric( $user_id ) ) {
        $user = get_userdata( $user_id );
    } else {
        $user = wp_get_current_user();
    }
    if ( empty( $user ) ) {
        return false;
    }
    $user_roles = (array) $user->roles;
    foreach ( (array) $roles as $role ) {
        if ( in_array( $role, $user_roles ) ) {
            return true;
        }
    }
    return false;
}

/**
 * Build template tags for notifications.
 *
 * @param WC_Order $order
 * @param WP_User|null $driver
 * @return array
 */
function oddw_build_notification_tags(  $order, $driver = null  ) {
    $tags = array(
        'order_id'         => $order->get_id(),
        'order_number'     => $order->get_order_number(),
        'customer_name'    => trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ),
        'driver_name'      => '',
        'driver_phone'     => '',
        'store_name'       => get_bloginfo( 'name' ),
        'order_total'      => $order->get_formatted_order_total(),
        'status'           => $order->get_status(),
        'delivery_address' => wp_strip_all_tags( ( $order->get_formatted_shipping_address() ? $order->get_formatted_shipping_address() : $order->get_formatted_billing_address() ) ),
    );
    if ( $driver instanceof WP_User ) {
        $tags['driver_name'] = $driver->display_name;
        $tags['driver_phone'] = get_user_meta( $driver->ID, 'billing_phone', true );
    } else {
        $driver_id = absint( oddw_get_order_meta( $order->get_id(), 'oddw_driver_id', true ) );
        if ( $driver_id ) {
            $driver_user = get_userdata( $driver_id );
            if ( $driver_user ) {
                $tags['driver_name'] = $driver_user->display_name;
                $tags['driver_phone'] = get_user_meta( $driver_user->ID, 'billing_phone', true );
            }
        }
    }
    return $tags;
}

/**
 * Display driver data in HTML format
 *
 * @param int $driver_id The driver's user ID
 * @return string HTML output of driver information
 */
function oddw_driver_data_display(  $driver_id  ) {
    // Add stylesheet for driver display
    wp_enqueue_style(
        'oddw-driver-display',
        plugin_dir_url( dirname( dirname( __FILE__ ) ) ) . 'public/css/oddw-driver-display.css',
        array(),
        ODDW_VERSION,
        'all'
    );
    if ( !$driver_id ) {
        return '';
    }
    $driver = get_userdata( $driver_id );
    if ( !$driver || !in_array( 'driver', (array) $driver->roles ) ) {
        return '';
    }
    // Get driver details
    $driver_image_id = get_user_meta( $driver_id, 'oddw_driver_image', true );
    $legacy_driver_picture = get_user_meta( $driver_id, 'oddw_driver_picture', true );
    $car_image_id = get_user_meta( $driver_id, 'oddw_driver_car_image', true );
    $car_type = get_user_meta( $driver_id, 'oddw_driver_car_type', true );
    $phone = get_user_meta( $driver_id, 'oddw_driver_phone', true );
    $license_plate = get_user_meta( $driver_id, 'oddw_driver_license_plate', true );
    $driver_license = get_user_meta( $driver_id, 'oddw_driver_license', true );
    $transportation_type = get_user_meta( $driver_id, 'oddw_driver_transportation_type', true );
    if ( empty( $transportation_type ) ) {
        $transportation_type = get_user_meta( $driver_id, 'oddw_driver_car_type', true );
    }
    $vehicle_model = get_user_meta( $driver_id, 'oddw_driver_vehicle_model', true );
    if ( empty( $vehicle_model ) ) {
        $vehicle_model = get_user_meta( $driver_id, 'oddw_driver_vehicle', true );
    }
    $vehicle_color = get_user_meta( $driver_id, 'oddw_driver_vehicle_color', true );
    $availability = get_user_meta( $driver_id, 'oddw_driver_availability', true );
    $availability_window = get_user_meta( $driver_id, 'oddw_driver_availability_window', true );
    $driver_experience = get_user_meta( $driver_id, 'oddw_driver_experience', true );
    $driver_message = get_user_meta( $driver_id, 'oddw_driver_message', true );
    $output = '';
    $output .= '<div class="oddw-driver-profile">';
    $output .= '<div class="oddw-driver-info">';
    // Driver image.
    $output .= '<div class="oddw-driver-image"><p><strong>' . esc_html__( 'Driver Image', 'orders-delivery-drivers-for-woocommerce' ) . '</strong></p>';
    if ( $driver_image_id ) {
        $output .= wp_get_attachment_image(
            $driver_image_id,
            'thumbnail',
            false,
            array(
                'style' => 'max-width:100px;height:auto;',
            )
        );
    } elseif ( is_array( $legacy_driver_picture ) && !empty( $legacy_driver_picture['url'] ) ) {
        $output .= '<img src="' . esc_url( $legacy_driver_picture['url'] ) . '" alt="" style="max-width:100px;height:auto;" />';
    } else {
        $output .= get_avatar( $driver_id, 100 );
    }
    $output .= '</div>';
    $output .= '<table class="oddw-driver-details"><tbody>';
    // Driver name.
    $output .= '<tr><td>' . esc_html__( 'Driver Name', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td><strong>' . esc_html( $driver->display_name ) . '</strong></td></tr>';
    // Driver phone.
    if ( $phone ) {
        $output .= '<tr><td>' . esc_html__( 'Driver Phone Number', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td><a href="tel:' . esc_attr( $phone ) . '">' . esc_html( $phone ) . '</a></td></tr>';
    }
    if ( $license_plate ) {
        $output .= '<tr><td>' . esc_html__( 'License Plate Number', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . esc_html( $license_plate ) . '</td></tr>';
    }
    if ( $driver_license ) {
        $output .= '<tr><td>' . esc_html__( 'Driver License Number', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . esc_html( $driver_license ) . '</td></tr>';
    }
    if ( $transportation_type ) {
        $output .= '<tr><td>' . esc_html__( 'Transportation Type', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . esc_html( $transportation_type ) . '</td></tr>';
    }
    if ( $vehicle_model ) {
        $output .= '<tr><td>' . esc_html__( 'Vehicle Model', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . esc_html( $vehicle_model ) . '</td></tr>';
    }
    if ( $vehicle_color ) {
        $output .= '<tr><td>' . esc_html__( 'Vehicle Color', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . esc_html( $vehicle_color ) . '</td></tr>';
    }
    // Private fields are rendered separately for admins/assigned driver.
    if ( !$license_plate && !$driver_license && !$transportation_type && !$vehicle_model && !$vehicle_color && empty( $availability ) ) {
        $output .= '<tr><td colspan="2">' . esc_html__( 'No driver details available.', 'orders-delivery-drivers-for-woocommerce' ) . '</td></tr>';
    }
    $output .= '</tbody></table>';
    $output .= '</div>';
    if ( $car_image_id ) {
        $output .= '<div class="oddw-car-preview">';
        $output .= '<p style="text-align:center;"><strong>' . esc_html__( 'Vehicle Image', 'orders-delivery-drivers-for-woocommerce' ) . '</strong> </p>';
        $output .= wp_get_attachment_image(
            $car_image_id,
            'thumbnail',
            false,
            array(
                'class' => 'car-thumbnail',
            )
        );
        $output .= '</div>';
    }
    return $output;
}

/**
 * Render private driver fields for admins and assigned driver only.
 *
 * @param int $driver_id
 * @return string
 */
function oddw_driver_private_details_table(  $driver_id  ) {
    if ( !is_user_logged_in() ) {
        return '';
    }
    $current_user_id = get_current_user_id();
    if ( !current_user_can( 'manage_options' ) && $current_user_id !== absint( $driver_id ) ) {
        return '';
    }
    $availability_window = get_user_meta( $driver_id, 'oddw_driver_availability_window', true );
    $driver_experience = get_user_meta( $driver_id, 'oddw_driver_experience', true );
    $driver_message = get_user_meta( $driver_id, 'oddw_driver_message', true );
    $availability = get_user_meta( $driver_id, 'oddw_driver_availability', true );
    if ( empty( $availability_window ) && empty( $driver_experience ) && empty( $driver_message ) && empty( $availability ) ) {
        return '';
    }
    $output = '<div class="oddw-driver-private">';
    $output .= '<p class="oddw-private-note">' . esc_html__( 'These details are visible to administrators and the assigned driver only.', 'orders-delivery-drivers-for-woocommerce' ) . '</p>';
    $output .= '<table class="oddw-driver-details"><tbody>';
    if ( $driver_experience ) {
        $output .= '<tr><td>' . esc_html__( 'Years of Driving Experience', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . esc_html( $driver_experience ) . '</td></tr>';
    }
    if ( $availability_window ) {
        $output .= '<tr><td>' . esc_html__( 'Available Hours', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . esc_html( $availability_window ) . '</td></tr>';
    }
    if ( $driver_message ) {
        $output .= '<tr><td>' . esc_html__( 'Additional Information', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . esc_html( $driver_message ) . '</td></tr>';
    }
    if ( !empty( $availability ) ) {
        $output .= '<tr><td>' . esc_html__( 'Availability', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . esc_html( ( $availability === 'on' ? __( 'Available', 'orders-delivery-drivers-for-woocommerce' ) : __( 'Unavailable', 'orders-delivery-drivers-for-woocommerce' ) ) ) . '</td></tr>';
    }
    $output .= '</tbody></table>';
    $output .= '</div>';
    return $output;
}

/**
 * Get store address formatted for Google Maps
 * 
 * @return string Formatted store address
 */
function oddw_get_store_address() {
    // The store address.
    $store_address = get_option( 'woocommerce_store_address' );
    $store_address_2 = get_option( 'woocommerce_store_address_2' );
    $store_city = get_option( 'woocommerce_store_city' );
    $store_postcode = get_option( 'woocommerce_store_postcode' );
    // The store country/state.
    $store_raw_country = get_option( 'woocommerce_default_country' );
    // Split the store country/state.
    $split_country = explode( ':', $store_raw_country );
    // Check to see if State & Country are available.
    if ( false == strpos( $store_raw_country, ':' ) ) {
        // Store country only.
        $store_country = $split_country[0];
        $store_state = '';
    } else {
        // Store country and state separated.
        $store_country = $split_country[0];
        $store_state = $split_country[1];
    }
    // Create store address.
    $store_address = $store_address . ' ' . $store_address_2 . ' ' . $store_city . ' ' . $store_state . ' ' . $store_postcode . ' ' . $store_country;
    // Filter the store address.
    return apply_filters( 'oddw_driver_dashboard_store_address', $store_address );
}

/**
 * Get delivery address from order
 * 
 * @param WC_Order $order The order object
 * @return string Formatted delivery address
 */
function oddw_get_delivery_address(  $order  ) {
    $order_shipping_address_1 = $order->get_shipping_address_1();
    if ( isset( $order_shipping_address_1 ) && '' !== $order_shipping_address_1 ) {
        add_filter( 'woocommerce_order_formatted_shipping_address', 'oddw_custom_order_formatted_address' );
        return str_replace( '<br/>', ' ', $order->get_formatted_shipping_address() );
    } else {
        add_filter( 'woocommerce_order_formatted_billing_address', 'oddw_custom_order_formatted_address' );
        return str_replace( '<br/>', ' ', $order->get_formatted_billing_address() );
    }
}

/**
 * Render customer contact buttons
 * 
 * @param WC_Order $order The order object
 * @return string HTML for contact buttons
 */
function oddw_render_customer_contact_buttons(  $order  ) {
    $output = '<p>';
    if ( $order->get_billing_phone() ) {
        $output .= '<a href="tel:' . esc_attr( $order->get_billing_phone() ) . '" class="button oddw-button customer">' . esc_html__( 'Call Customer', 'orders-delivery-drivers-for-woocommerce' ) . '</a> ';
    }
    if ( get_option( 'oddw_settings_dispatch_phone_number' ) ) {
        $output .= '<a href="tel:' . esc_attr( get_option( 'oddw_settings_dispatch_phone_number' ) ) . '" class="button oddw-button dispatch">' . esc_html__( 'Call Dispatch', 'orders-delivery-drivers-for-woocommerce' ) . '</a>';
    }
    $output .= '</p>';
    return $output;
}

/**
 * Render Google Maps for delivery address
 * 
 * @param WC_Order $order The order object
 * @param string $store_address The store address
 * @return string HTML for Google Maps
 */
function oddw_render_google_maps(  $order, $store_address  ) {
    $output = '';
    $google_maps_api_key = get_option( 'oddw_settings_google_maps_api_key' );
    $delivery_address = oddw_get_delivery_address( $order );
    // Always show the delivery address
    $plain_address = '<p>';
    if ( $order->get_shipping_address_1() ) {
        add_filter( 'woocommerce_order_formatted_shipping_address', 'oddw_custom_order_formatted_address' );
        $plain_address .= wp_kses_post( $order->get_formatted_shipping_address() );
    } else {
        add_filter( 'woocommerce_order_formatted_billing_address', 'oddw_custom_order_formatted_address' );
        $plain_address .= wp_kses_post( $order->get_formatted_billing_address() );
    }
    $plain_address .= '</p>';
    $output .= wp_kses_post( apply_filters( 'oddw_delivery_address_plain_text', $plain_address, $delivery_address ) );
    // Google Map if API key is available
    if ( !empty( $google_maps_api_key ) ) {
        // Create the Google Map.
        $google_map = '<div class="oddw-google-map" style="margin: 10px 0;">';
        $google_map .= '<iframe width="100%" height="450" frameborder="0" style="border:0; max-width: 600px;" src="https://www.google.com/maps/embed/v1/directions?origin=' . esc_attr( apply_filters( 'oddw_google_maps_origin_address', $store_address ) ) . '&destination=' . esc_attr( apply_filters( 'oddw_google_maps_delivery_address', $delivery_address ) ) . '&key=' . esc_attr( $google_maps_api_key ) . '" allowfullscreen></iframe>';
        $google_map .= '</div>';
        // Display the Google Map with delivery address.
        $output .= apply_filters(
            'oddw_delivery_address_google_map',
            $google_map,
            $delivery_address,
            $store_address
        );
    }
    // Get Directions Link (only once)
    $directions_address = str_replace( '<br/>', ' ', $delivery_address );
    $directions_link = 'https://www.google.com/maps/search/?api=1&query=' . rawurlencode( $directions_address );
    $output .= '<p><a target="_blank" href="' . esc_url( $directions_link ) . '" class="button">' . esc_html__( 'Get Directions', 'orders-delivery-drivers-for-woocommerce' ) . '</a></p>';
    return $output;
}

/**
 * Render order details table
 * 
 * @param WC_Order $order The order object
 * @return string HTML for order details table
 */
function oddw_render_order_details_table(  $order  ) {
    $output = '<h4>' . esc_html__( 'Order details', 'orders-delivery-drivers-for-woocommerce' ) . '</h4>';
    $output .= '<table class="oddw-dashboard">';
    $output .= '<tbody>';
    // Customer Name
    if ( $order->get_shipping_first_name() ) {
        $output .= '<tr><td><strong>' . esc_html__( 'Customer', 'orders-delivery-drivers-for-woocommerce' ) . '</strong></td><td>' . esc_html( $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name() ) . '</td></tr>';
    } elseif ( $order->get_billing_first_name() ) {
        $output .= '<tr><td><strong>' . esc_html__( 'Customer', 'orders-delivery-drivers-for-woocommerce' ) . '</strong></td><td>' . esc_html( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ) . '</td></tr>';
    }
    // Payment Method
    $payment_gateway = wc_get_payment_gateway_by_order( $order );
    if ( $payment_gateway ) {
        $output .= '<tr><td><strong>' . esc_html__( 'Payment method', 'orders-delivery-drivers-for-woocommerce' ) . '</strong></td><td>' . esc_html( $payment_gateway->title ) . '</td></tr>';
    }
    // Order Date
    if ( $order->get_date_created() ) {
        $output .= '<tr><td><strong>' . esc_html__( 'Order date', 'orders-delivery-drivers-for-woocommerce' ) . '</strong></td><td>' . esc_html( $order->get_date_created()->date( 'm-d-Y - h:i a' ) ) . '</td></tr>';
    }
    $output .= '</tbody></table>';
    return $output;
}

/**
 * Render order items table
 * 
 * @param WC_Order $order The order object
 * @return string HTML for order items table
 */
function oddw_render_order_items_table(  $order  ) {
    $output = '<table class="oddw-dashboard">';
    $output .= '<thead><tr><td>' . esc_html__( 'Product', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . esc_html__( 'Qty', 'orders-delivery-drivers-for-woocommerce' ) . '</td><td>' . esc_html__( 'Total', 'orders-delivery-drivers-for-woocommerce' ) . '</td></tr></thead>';
    $output .= '<tbody>';
    $currency_symbol = get_woocommerce_currency_symbol( $order->get_currency() );
    foreach ( $order->get_items() as $item ) {
        $output .= '<tr>';
        $output .= '<td>' . esc_html( $item->get_name() ) . '</td>';
        $output .= '<td>' . esc_html( $item->get_quantity() ) . '</td>';
        $output .= '<td>' . esc_html( $currency_symbol ) . esc_html( number_format( $item->get_total(), 2 ) ) . '</td>';
        $output .= '</tr>';
    }
    // Delivery Total
    $output .= '<tr class="delivery-charge">';
    $output .= '<td colspan="2"><strong>' . esc_html__( 'Delivery', 'orders-delivery-drivers-for-woocommerce' ) . '</strong></td>';
    $output .= '<td class="total">' . esc_html( $currency_symbol ) . esc_html( number_format( $order->get_shipping_total(), 2 ) ) . '</td>';
    $output .= '</tr>';
    // Order Total
    $output .= '<tr class="order-total">';
    $output .= '<td colspan="2"><strong>' . esc_html__( 'Order total', 'orders-delivery-drivers-for-woocommerce' ) . '</strong></td>';
    $output .= '<td class="total">' . esc_html( $currency_symbol ) . esc_html( $order->get_total() ) . '</td>';
    $output .= '</tr>';
    $output .= '</tbody></table>';
    return $output;
}

/**
 * Render delivery address section
 * 
 * @param WC_Order $order The order object
 * @param string $store_address The store address
 * @return string HTML for delivery address section
 */
function oddw_render_delivery_address(  $order, $store_address  ) {
    $output = '<h4>' . esc_html__( 'Delivery Address', 'orders-delivery-drivers-for-woocommerce' ) . '</h4>';
    $output .= oddw_render_google_maps( $order, $store_address );
    return $output;
}

/**
 * Display driver availability table
 * 
 * @return string HTML table showing driver availability status
 */
function oddw_driver_availability_table() {
    // Get all users with driver role
    $drivers = get_users( array(
        'role' => 'driver',
    ) );
    if ( empty( $drivers ) ) {
        return '<p>' . __( 'No drivers found.', 'orders-delivery-drivers-for-woocommerce' ) . '</p>';
    }
    $output = '';
    $output .= '<table class="woocommerce-orders-table woocommerce-MyAccount-orders shop_table shop_table_responsive my_account_orders">';
    $output .= '<thead>';
    $output .= '<tr>';
    $output .= '<th>' . esc_html__( 'Driver', 'orders-delivery-drivers-for-woocommerce' ) . '</th>';
    $output .= '<th>' . esc_html__( 'Status', 'orders-delivery-drivers-for-woocommerce' ) . '</th>';
    $output .= '<th>' . esc_html__( 'Active Orders', 'orders-delivery-drivers-for-woocommerce' ) . '</th>';
    $output .= '<th>' . esc_html__( 'Completed Orders', 'orders-delivery-drivers-for-woocommerce' ) . '</th>';
    $output .= '</tr>';
    $output .= '</thead>';
    $output .= '<tbody>';
    foreach ( $drivers as $driver ) {
        $availability = get_user_meta( $driver->ID, 'oddw_driver_availability', true );
        $active_orders = count( oddw_query_orders( array(
            'status'     => array('driver-assigned', 'out-for-delivery'),
            'meta_key'   => 'oddw_driver_id',
            'meta_value' => $driver->ID,
            'return'     => 'ids',
        ) ) );
        $output .= '<tr style="text-align: center;">';
        $output .= '<td>' . esc_html( $driver->display_name ) . '</td>';
        $output .= '<td>';
        $output .= '<span class="driver-status ' . (( $availability === 'on' ? 'available' : 'unavailable' )) . '">';
        $output .= ( $availability === 'on' ? esc_html__( 'Available', 'orders-delivery-drivers-for-woocommerce' ) : esc_html__( 'Unavailable', 'orders-delivery-drivers-for-woocommerce' ) );
        $output .= '</span>';
        $output .= '</td>';
        $output .= '<td>' . esc_html( $active_orders ) . '</td>';
        $completed_orders = count( oddw_query_orders( array(
            'status'     => 'completed',
            'meta_key'   => 'oddw_driver_id',
            'meta_value' => $driver->ID,
            'return'     => 'ids',
        ) ) );
        $output .= '<td>' . esc_html( $completed_orders ) . '</td>';
        $output .= '</tr>';
    }
    $output .= '</tbody>';
    $output .= '</table>';
    return $output;
}
