<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

use Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController;

/**
 * The Delivery Driver Metaboxes.
 *
 * @link       https://www.wpsaad.com
 * @since      1.0.0
 *
 * @package    ODDW
 * @subpackage ODDW/admin
 */

/**
 * Order Details metabox
 *
 * Adds the order details metabox.
 *
 * @since    1.0
 */
function oddw_metaboxes($post_type, $post) {

        $screen = class_exists( '\Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController' ) && wc_get_container()->get( CustomOrdersTableController::class )->custom_orders_table_usage_is_enabled()
        ? wc_get_page_screen_id( 'shop-order' ): 'shop_order';

	add_meta_box(
		'oddw_metaboxes',
		__( 'Delivery Driver', 'orders-delivery-drivers-for-woocommerce' ),
		'oddw_build',
		$screen,
		'side',
		'high'
	);
}
add_action( 'add_meta_boxes', 'oddw_metaboxes' , 10,2);

/**
 * Building the metabox
 */
function oddw_build($post) {
	// global $post;
	// Get current WooCommerce admin order id as int and sanitize it.
                $post_id = ( method_exists( $post, 'get_id' ) ) ? $post->get_id() : absint( $post->ID );

	// Noncename needed to verify where the data originated.
        echo '<input type="hidden" name="oddw_meta_noncename" id="oddw_meta_noncename" value="' . esc_attr( wp_create_nonce( plugin_basename( __FILE__ ) ) ) . '" />';

	// Get the driver data if its already been entered.
	// $oddw_driver_id = get_post_meta( $post_id, 'oddw_driver_id', true );
            $oddw_driver_id = oddw_get_order_meta( $post_id, 'oddw_driver_id', true );
// var_dump( $oddw_driver_id);
        	// Echo Delivery Driver Metabox Input Field.
                 echo '<div class="oddw-driver-box">';
                 // translators: Assign a driver dropdown label, no placeholders
                 wp_dropdown_users( array(
                         'show_option_none' => __( 'Assign a driver', 'orders-delivery-drivers-for-woocommerce' ),
                         'option_none_value' => '-1',
                         'role'             => 'driver',
                         'name'             => 'oddw_driver_id',
                         'id'               => 'oddw_driver_id',
                         'selected'         => ($oddw_driver_id !== '' ? $oddw_driver_id : '-1'),
                         'class'            => 'widefat',
                         'show'             => 'display_name_with_login'
                 ) );
                 echo '</div>';

	// Get driver rating.
        $oddw_driver_rating = oddw_get_order_meta( $post_id, 'oddw_delivery_rating', true );

               // Display driver rating.
               if ( ! empty( $oddw_driver_rating ) ) {
                       /* translators: %s: delivery rating value */
                       echo '<p>' . esc_html( sprintf( __( 'Delivery rating: %s out of 5 stars', 'orders-delivery-drivers-for-woocommerce' ), esc_html( $oddw_driver_rating ) ) ) . '</p>';
               }

}

/**
 * Save the Metabox Data
 */
function oddw_driver_save_order_details( $post_id, $post ) {
        /**
         * Verify this came from our screen and with proper authorization,
         * because save_post can be triggered at other times
         */
        if (
                ! isset( $_POST['oddw_meta_noncename' ] ) ||
                ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['oddw_meta_noncename'] ) ), plugin_basename( __FILE__ ) )
        ) {
                return $post_id;
        }

        /** Is the user allowed to edit the post or page? */
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
                return $post_id;
        }

        /**
         * OK, we're authenticated: we need to find and save the data
         * We'll put it into an array to make it easier to loop though.
         */
                        if ( isset( $_POST['oddw_driver_id'] ) ) {
                                $driver_id = intval( wp_unslash( $_POST['oddw_driver_id'] ) );
                                $order = wc_get_order( $post_id );
                                if ( $driver_id > 0 ) {
                                        $oddw_driver_order_meta['oddw_driver_id'] = $driver_id;
                                        // Set order status to driver-assigned if not already completed/cancelled/refunded
                                        if ( $order && ! in_array( $order->get_status(), array( 'completed', 'cancelled', 'refunded' ), true ) ) {
                                                $order->set_status( 'driver-assigned' );
                                                $order->save();
                                        }
                                } elseif ( $driver_id === -1 ) {
                                        // Unassigned: delete meta or set to empty
                                        oddw_update_order_meta( $post_id, 'oddw_driver_id', '' );
                                        delete_post_meta( $post_id, 'oddw_driver_id' );
                                        // Remove from meta array so it's not set below
                                        unset( $oddw_driver_order_meta['oddw_driver_id'] );
                                        // Set order status back to processing if not completed/cancelled/refunded
                                        if ( $order && ! in_array( $order->get_status(), array( 'completed', 'cancelled', 'refunded' ), true ) ) {
                                                $order->set_status( 'processing' );
                                                $order->save();
                                        }
                                }
                        }


        // Store previously assigned driver for comparison (HPOS-safe).
        $previous_driver = oddw_get_order_meta( $post_id, 'oddw_driver_id', true );

        /** Add values of $oddw_driver_order_meta as custom fields (HPOS-safe) */
        foreach ( $oddw_driver_order_meta as $key => $value ) {
                if ( 'revision' === $post->post_type ) {
                        return;
                }
                $value = implode( ',', (array) $value );
                // Use HPOS-safe update
                oddw_update_order_meta( $post_id, $key, $value );
                if ( ! $value ) {
                        // Delete if blank (legacy only, HPOS ignores deletes for blank values)
                        delete_post_meta( $post_id, $key );
                }
        }

        // Trigger notification when a new driver is assigned.
        $new_driver = isset( $_POST['oddw_driver_id'] ) ? intval( wp_unslash( $_POST['oddw_driver_id'] ) ) : 0;
        if ( $new_driver > 0 && $new_driver !== intval( $previous_driver ) ) {
                do_action( 'oddw_driver_assigned', $post_id, $new_driver );
        }

}
add_action( 'save_post', 'oddw_driver_save_order_details', 1, 2 ); // Save the custom fields.
add_action( 'woocommerce_process_shop_order_meta', 'oddw_driver_save_order_details', 45, 2 );


