<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @link       https://www.wpsaad.com
 * @since      1.0.0
 *
 * @package    ODDW
 * @subpackage ODDW/admin
 * @author     WPSAAD 
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class ODDW_Admin {
    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

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

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param      string    $plugin_name       The name of this plugin.
     * @param      string    $version    The version of this plugin.
     */
    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_styles() {
        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in Delivery_Drivers_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The Delivery_Drivers_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */
        wp_enqueue_style(
            $this->plugin_name,
            plugin_dir_url( __FILE__ ) . 'css/oddw-admin.css',
            array(),
            $this->version,
            'all'
        );
    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts() {
        wp_enqueue_script(
            $this->plugin_name,
            plugin_dir_url( __FILE__ ) . 'js/oddw-admin.js',
            array('jquery'),
            $this->version,
            false
        );
        wp_localize_script( $this->plugin_name, 'oddw_ajax', array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
        ) );
    }

}

/**
 * Add Delivery Driver Column to Orders screen
 *
 * @param [type] $columns
 * @since 2.1
 */
function oddw_show_custom_delivery_driver_column(  $columns  ) {
    $new_columns = ( is_array( $columns ) ? $columns : array() );
    // Save shipping address column.
    $shipping_address = $columns['shipping_address'];
    // Remove shiping address column.
    unset($new_columns['shipping_address']);
    // Save order actions column.
    $wc_actions = $columns['wc_actions'];
    // Remove order actions column.
    unset($new_columns['wc_actions']);
    // Add delivery driver column.
    $new_columns['delivery_driver'] = __( 'Delivery Driver', 'orders-delivery-drivers-for-woocommerce' );
    // Add shipping address column.
    $new_columns['shipping_address'] = $shipping_address;
    // Add shipping address column.
    $new_columns['wc_actions'] = $wc_actions;
    return $new_columns;
}

// // for HPOS-based orders
// add_filter( 'manage_woocommerce_page_wc-orders_columns', 'oddw_show_custom_delivery_driver_column' );
// // legacy â€“ for CPT-based orders
// add_filter( 'manage_edit-shop_order_columns', 'oddw_show_custom_delivery_driver_column' );
/**
 * Delivery Driver column for Orders screen
 *
 * @param [type] $column
 * @since 2.1
 */
// function oddw_custom_delivery_driver_column( $column ) {
//     global $post, $woocommerce, $the_order;
//     switch ( $column ) {
//         case 'delivery_driver' :
// 			// Noncename needed to verify where the data originated.
// 			echo '<input type="hidden" name="oddw_meta_noncename" id="oddw_meta_noncename" value="' .
// 			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 );
// 			// Echo Delivery Driver Metabox Input Field.
// 			echo '<div class="oddw-driver-box">';
// 			wp_dropdown_users( array(
// 				'show_option_none' => '--',
// 				'role'             => 'driver',
// 				'name'             => $post->ID,
// 				'id'               => 'oddw_driver_id',
// 				'selected'         => $oddw_driver_id,
// 				'class'            => 'widefat',
// 				'show'             => 'display_name'
// 			) );
// 			echo '</div>';
//         break;
//     }
// }
function oddw_custom_delivery_driver_column(  $column, $order_or_order_id  ) {
    global $post, $woocommerce, $the_order;
    switch ( $column ) {
        case 'delivery_driver':
            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.
            $order_id = ( method_exists( $order_or_order_id, 'get_id' ) ? $order_or_order_id->get_id() : $order_or_order_id->id );
            $oddw_driver_id = oddw_get_order_meta( $order_id, 'oddw_driver_id', true );
            // Echo Delivery Driver Metabox Input Field.
            echo '<div class="oddw-driver-box">';
            wp_dropdown_users( array(
                'show_option_none' => '--',
                'role'             => 'driver',
                'name'             => $order_id,
                'id'               => 'oddw_driver_id',
                'selected'         => $oddw_driver_id,
                'class'            => 'widefat',
                'show'             => 'display_name',
            ) );
            echo '</div>';
            break;
    }
}

// // legacy â€“ for CPT-based orders
// add_action( 'manage_shop_order_posts_custom_column', 'oddw_custom_delivery_driver_column', 25, 2 );
// // for HPOS-based orders
// add_action( 'manage_woocommerce_page_wc-orders_custom_column', 'oddw_custom_delivery_driver_column', 25, 2 );
/**
 * Add "no-link" class to tr's from WooCommerce orders screen
 * 
 * @since 2.1
 */
function oddw_add_no_link_to_woocommerce_orders(  $classes  ) {
    if ( current_user_can( 'manage_woocommerce' ) ) {
        //make sure we are shop managers
        foreach ( $classes as $class ) {
            if ( $class == 'type-shop_order' ) {
                $classes[] = 'no-link';
            }
        }
    }
    return $classes;
}

add_filter( 'post_class', 'oddw_add_no_link_to_woocommerce_orders' );
/**
 * AJAX function to update driver ID on WooCommerce Orders page
 * 
 * @since 2.1
 */
function oddw_delivery_driver_settings() {
    // Verify nonce for security
    if ( !isset( $_POST['oddw_delivery_driver_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['oddw_delivery_driver_nonce'] ) ), 'oddw_delivery_driver_settings' ) ) {
        wp_die( 'Security check failed' );
    }
    $item_id = ( isset( $_POST['item_id'] ) ? absint( wp_unslash( $_POST['item_id'] ) ) : 0 );
    $meta_key = ( isset( $_POST['metakey'] ) ? sanitize_key( wp_unslash( $_POST['metakey'] ) ) : '' );
    $meta_value = ( isset( $_POST['metavalue'] ) ? intval( wp_unslash( $_POST['metavalue'] ) ) : 0 );
    // Store previous driver to detect changes.
    $previous_driver = oddw_get_order_meta( $item_id, $meta_key, true );
    // Update driver ID for order.
    oddw_update_order_meta( $item_id, $meta_key, $meta_value );
    // codex/trigger-email-and-sms-on-driver-assignment-i6vif7
    // Get order.
    $order = ( function_exists( 'wc_get_order' ) ? wc_get_order( $item_id ) : new WC_Order($item_id) );
    // Update order status and trigger notification when assigning a driver.
    if ( -1 == $meta_value ) {
        $order->update_status( 'processing' );
    } else {
        $order->update_status( 'driver-assigned' );
        if ( intval( $meta_value ) > 0 && intval( $meta_value ) !== intval( $previous_driver ) ) {
            do_action( 'oddw_driver_assigned', $item_id, intval( $meta_value ) );
        }
    }
    // Get order.
    $order = ( function_exists( 'wc_get_order' ) ? wc_get_order( $item_id ) : new WC_Order($item_id) );
    // Update order status and trigger notification when assigning a driver.
    if ( -1 == $meta_value ) {
        $order->update_status( 'processing' );
    } else {
        $order->update_status( 'driver-assigned' );
        if ( intval( $meta_value ) > 0 && intval( $meta_value ) !== intval( $previous_driver ) ) {
            do_action( 'oddw_driver_assigned', $item_id, intval( $meta_value ) );
        }
    }
    // Update order status.
    if ( -1 == $meta_value ) {
        $order->update_status( 'processing' );
    } else {
        $order->update_status( 'driver-assigned' );
    }
    // WooCommerce product loop $args
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 1000,
    );
    // Get all products based on $args.
    $loop = get_posts( $args );
    // Loop through each product.
    foreach ( $loop as $item ) {
        // Update inventory.
        if ( $meta_value === get_post_meta( $item->ID, $meta_key, true ) ) {
            update_post_meta( $item->ID, $meta_key, $meta_value );
        }
    }
    exit;
}

add_action( 'wp_ajax_oddw_delivery_driver_settings', 'oddw_delivery_driver_settings' );
//add_action('wp_ajax_nopriv_oddw_delivery_driver_settings', 'oddw_delivery_driver_settings');
/**
 * AJAX function to update driver availability
 * 
 * @since 2.3
 */
function oddw_driver_availability_update() {
    // Verify nonce for security
    if ( !isset( $_POST['oddw_availability_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['oddw_availability_nonce'] ) ), 'oddw_driver_availability_update' ) ) {
        wp_die( 'Security check failed' );
    }
    $user_id = ( isset( $_POST['user_id'] ) ? absint( wp_unslash( $_POST['user_id'] ) ) : 0 );
    $meta_value = ( isset( $_POST['metavalue'] ) ? sanitize_text_field( wp_unslash( $_POST['metavalue'] ) ) : '' );
    if ( 'checked' == $meta_value ) {
        $new_value = 'on';
        $old_value = '';
    } else {
        $new_value = '';
        $old_value = 'on';
    }
    // Update driver availability.
    update_user_meta(
        $user_id,
        'oddw_driver_availability',
        $new_value,
        $old_value
    );
}

add_action( 'wp_ajax_oddw_driver_availability_update', 'oddw_driver_availability_update' );
add_action( 'wp_ajax_nopriv_oddw_driver_availability_update', 'oddw_driver_availability_update' );
/**
 * Display pending driver profile updates in admin
 *
 * @since 1.6
 */
function oddw_display_pending_driver_updates() {
    global $wpdb;
    // Query for users awaiting approval
    $pending_drivers = $wpdb->get_results( "SELECT user_id FROM {$wpdb->usermeta} \r\n         WHERE meta_key = 'oddw_driver_pending_approval' \r\n         AND meta_value = '1'" );
    if ( empty( $pending_drivers ) ) {
        return;
    }
    echo '<hr style="margin: 30px 0;" />';
    echo '<h2>' . esc_html__( 'Pending Driver Profile Updates', 'orders-delivery-drivers-for-woocommerce' ) . '</h2>';
    echo '<p>' . esc_html__( 'These drivers have updated their profiles and are awaiting your approval.', 'orders-delivery-drivers-for-woocommerce' ) . '</p>';
    echo '<table class="wp-list-table widefat fixed striped">';
    echo '<thead><tr>';
    echo '<th>' . esc_html__( 'Driver Name', 'orders-delivery-drivers-for-woocommerce' ) . '</th>';
    echo '<th>' . esc_html__( 'Email', 'orders-delivery-drivers-for-woocommerce' ) . '</th>';
    echo '<th>' . esc_html__( 'License Plate', 'orders-delivery-drivers-for-woocommerce' ) . '</th>';
    echo '<th>' . esc_html__( 'Transportation', 'orders-delivery-drivers-for-woocommerce' ) . '</th>';
    echo '<th>' . esc_html__( 'Vehicle', 'orders-delivery-drivers-for-woocommerce' ) . '</th>';
    echo '<th>' . esc_html__( 'Actions', 'orders-delivery-drivers-for-woocommerce' ) . '</th>';
    echo '</tr></thead><tbody>';
    foreach ( $pending_drivers as $pending ) {
        $user_id = $pending->user_id;
        $user = get_userdata( $user_id );
        if ( !$user ) {
            continue;
        }
        $license_plate = get_user_meta( $user_id, 'oddw_driver_license_plate', true );
        $transportation = get_user_meta( $user_id, 'oddw_driver_transportation_type', true );
        $vehicle = get_user_meta( $user_id, 'oddw_driver_vehicle', true );
        $vehicle_model = get_user_meta( $user_id, 'oddw_driver_vehicle_model', true );
        $vehicle_color = get_user_meta( $user_id, 'oddw_driver_vehicle_color', true );
        echo '<tr>';
        echo '<td><strong>' . esc_html( $user->display_name ) . '</strong> <a href="' . esc_url( admin_url( 'user-edit.php?user_id=' . $user_id ) ) . '" class="row-title">(Edit)</a></td>';
        echo '<td>' . esc_html( $user->user_email ) . '</td>';
        echo '<td>' . esc_html( $license_plate ) . '</td>';
        echo '<td>' . esc_html( $transportation ) . '</td>';
        echo '<td>' . esc_html( $vehicle . ' - ' . $vehicle_model . ' (' . $vehicle_color . ')' ) . '</td>';
        echo '<td>';
        echo '<form method="post" style="display:inline;">';
        wp_nonce_field( 'oddw_approve_driver_update', 'oddw_approve_nonce' );
        echo '<input type="hidden" name="user_id" value="' . esc_attr( $user_id ) . '" />';
        echo '<button class="button button-primary" name="oddw_action" value="approve_driver">' . esc_html__( 'Approve', 'orders-delivery-drivers-for-woocommerce' ) . '</button> ';
        echo '<button class="button" name="oddw_action" value="reject_driver" onclick="return confirm(\'' . esc_js( __( 'Are you sure? The driver will be notified.', 'orders-delivery-drivers-for-woocommerce' ) ) . '\')">' . esc_html__( 'Reject', 'orders-delivery-drivers-for-woocommerce' ) . '</button>';
        echo '</form>';
        echo '</td>';
        echo '</tr>';
    }
    echo '</tbody></table>';
}

/**
 * Handle pending driver approval/rejection
 *
 * @since 1.6
 */
function oddw_handle_driver_update_approval() {
    if ( isset( $_POST['oddw_action'], $_POST['user_id'], $_POST['oddw_approve_nonce'] ) ) {
        if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['oddw_approve_nonce'] ) ), 'oddw_approve_driver_update' ) ) {
            $action = sanitize_text_field( wp_unslash( $_POST['oddw_action'] ) );
            $user_id = absint( wp_unslash( $_POST['user_id'] ) );
            if ( 'approve_driver' === $action ) {
                delete_user_meta( $user_id, 'oddw_driver_pending_approval' );
                wp_safe_remote_post( admin_url( 'admin-ajax.php' ), array(
                    'blocking'  => false,
                    'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
                    'body'      => array(
                        'action'  => 'oddw_send_approval_email',
                        'user_id' => $user_id,
                    ),
                ) );
            } elseif ( 'reject_driver' === $action ) {
                delete_user_meta( $user_id, 'oddw_driver_pending_approval' );
                wp_safe_remote_post( admin_url( 'admin-ajax.php' ), array(
                    'blocking'  => false,
                    'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
                    'body'      => array(
                        'action'  => 'oddw_send_rejection_email',
                        'user_id' => $user_id,
                    ),
                ) );
            }
        }
    }
}

add_action( 'admin_init', 'oddw_handle_driver_update_approval' );