<?php
/**
 * Custom functions for adding Delivery Driver
 * details to Wommerce Orders
 *
 * @link       https://www.wpsaad.com
 * @since      1.6
 *
 * @package    ODDW
 * @subpackage ODDW/public/woocommerce
 */

/**
 * Add Driver details to customer's order
 *
 * @return string
 * @since 1.6
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

function oddw_driver_details_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, 'style' => true ),
        'h2' => array( 'class' => true ),
        'h3' => array( 'class' => true ),
        'strong' => array(),
        'br' => array(),
        'table' => array( 'class' => true ),
        'tbody' => array(),
        'tr' => array( 'class' => true ),
        'td' => array( 'class' => true, 'colspan' => true ),
        'form' => array( 'method' => true, 'action' => 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, 'disabled' => true ),
        'option' => array( 'value' => true, 'selected' => true ),
        'button' => array( 'type' => true, 'class' => true, 'name' => true, 'value' => true ),
        'img' => array(
            'src' => true,
            'srcset' => true,
            'sizes' => true,
            'alt' => true,
            'width' => true,
            'height' => true,
            'class' => true,
            'style' => true,
            'loading' => true,
            'decoding' => true,
        ),
    );
}

function oddw_order_driver_details( $order ) {
    // Ensure required public assets are loaded wherever rating UI is rendered.
    wp_enqueue_style(
        'orders-delivery-drivers-for-woocommerce',
        plugin_dir_url( dirname( __FILE__ ) ) . 'css/oddw-public.css',
        array(),
        defined( 'ODDW_VERSION' ) ? ODDW_VERSION : '1.0.0',
        'all'
    );
    wp_enqueue_script(
        'orders-delivery-drivers-for-woocommerce',
        plugin_dir_url( dirname( __FILE__ ) ) . 'js/oddw-public.js',
        array( 'jquery' ),
        defined( 'ODDW_VERSION' ) ? ODDW_VERSION : '1.0.0',
        true
    );
    wp_localize_script(
        'orders-delivery-drivers-for-woocommerce',
        'oddw_ajax',
        array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
        )
    );

    // Get Order ID.
    $order_id = $order->get_id();

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

    // Get order status.
    $order_status = $order_data['status'];

    // Get Driver ID.
    $driver_id = absint( oddw_get_order_meta( $order_id, 'oddw_driver_id', true ) );

    // If there's a driver ID attached.
    if ( $driver_id <= 0 ) {
        return;
    }
    $string = '<h2>' . esc_html__( 'Delivery Driver Details', 'orders-delivery-drivers-for-woocommerce' ) . '</h2>';
    $string  .= '<div class="oddw-driver-details">';
    $string .= oddw_driver_data_display( $driver_id );
    $string .= oddw_driver_private_details_table( $driver_id );

    // Display star rating.
    if ( 'completed' == $order_status ) {
        $oddw_delivery_rating = absint( oddw_get_order_meta( $order_id, 'oddw_delivery_rating', true ) );
        
        // Initialize defaults before nonce check
        $rating_submitted_flag = '';
        $rated_order_id        = 0;
        $rating_submitted      = false;
        
        // Verify nonce BEFORE reading GET parameters
        if ( isset( $_GET['oddw_view_order_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['oddw_view_order_nonce'] ) ), 'oddw_view_order' ) ) {
            $rating_submitted_flag = (string) filter_input( INPUT_GET, 'oddw_rating_submitted', FILTER_SANITIZE_SPECIAL_CHARS );
            $rated_order_id        = absint( (string) filter_input( INPUT_GET, 'oddw_rated_order', FILTER_SANITIZE_NUMBER_INT ) );
            $rating_submitted      = ( '1' === $rating_submitted_flag && $rated_order_id === absint( $order_id ) );
        }

        $string .= '<div class="driver-rating-container"><h3>' . esc_html__( 'Delivery Rating', 'orders-delivery-drivers-for-woocommerce' ) . '</h3>';

        if ( $rating_submitted ) {
            $string .= '<p class="oddw-rating-message oddw-rating-success">' . esc_html__( 'Thanks, your rating has been submitted.', 'orders-delivery-drivers-for-woocommerce' ) . '</p>';
        }

        if ( $oddw_delivery_rating > 0 ) {
            $string .= '<p class="oddw-rating-message">' . esc_html__( 'Rating already submitted.', 'orders-delivery-drivers-for-woocommerce' ) . '</p>';
            $string .= '<select class="driver-rating" id="rating_' . $order_id . '" data-id="rating_' . $order_id . '" data-initial-rating="' . esc_attr( $oddw_delivery_rating ) . '" disabled><option value=""></option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></select>';
        } else {
            $string .= '<form method="post" class="oddw-rating-form">';
            $string .= wp_nonce_field( 'oddw_submit_delivery_rating', 'oddw_delivery_rating_nonce', true, false );
            $string .= '<input type="hidden" name="oddw_order_id" value="' . esc_attr( $order_id ) . '" />';
            $string .= '<select class="driver-rating" id="rating_' . $order_id . '" name="oddw_delivery_rating" data-id="rating_' . $order_id . '" data-initial-rating=""><option value=""></option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></select>';
            $string .= '<button type="submit" class="button oddw-button oddw-submit-rating" name="oddw_submit_delivery_rating" value="1">' . esc_html__( 'Submit Rating', 'orders-delivery-drivers-for-woocommerce' ) . '</button>';
            $string .= '</form>';
        }

        $string .= '</div>';
    } elseif ( 'driver-assigned' == $order_status || 'out-for-delivery' == $order_status ) {
        if ( 'no' !== get_option( 'oddw_settings_driver_phone_number' ) ) {
            $driver_number = get_user_meta( $driver_id, 'phone_number', true );
            if ( $driver_number ) {
                $string .= '<a href="tel:' . esc_attr( $driver_number ) . '" class="button oddw-button customer">' . esc_html__( 'Call Driver', 'orders-delivery-drivers-for-woocommerce' ) . '</a> ';
            }
        }
    }

    $string .= '</div>';

    echo wp_kses( $string, oddw_driver_details_allowed_html() );
}

/**
 * Handle one-time delivery rating form submission.
 */
function oddw_handle_delivery_rating_submission() {
    if ( ! isset( $_POST['oddw_submit_delivery_rating'], $_POST['oddw_delivery_rating_nonce'] ) ) {
        return;
    }

    if ( ! is_user_logged_in() ) {
        return;
    }

    if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['oddw_delivery_rating_nonce'] ) ), 'oddw_submit_delivery_rating' ) ) {
        return;
    }

    $order_id = isset( $_POST['oddw_order_id'] ) ? absint( wp_unslash( $_POST['oddw_order_id'] ) ) : 0;
    $rating   = isset( $_POST['oddw_delivery_rating'] ) ? absint( wp_unslash( $_POST['oddw_delivery_rating'] ) ) : 0;

    if ( $order_id <= 0 || $rating < 1 || $rating > 5 ) {
        return;
    }

    $order = wc_get_order( $order_id );
    if ( ! $order ) {
        return;
    }

    $customer_id = (int) $order->get_customer_id();
    if ( $customer_id <= 0 || get_current_user_id() !== $customer_id ) {
        return;
    }

    if ( 'completed' !== $order->get_status() ) {
        return;
    }

    $existing_rating = absint( oddw_get_order_meta( $order_id, 'oddw_delivery_rating', true ) );
    if ( $existing_rating > 0 ) {
        return;
    }

    oddw_update_order_meta( $order_id, 'oddw_delivery_rating', $rating );

    $redirect = wp_get_referer();
    if ( ! $redirect ) {
        $redirect = wc_get_endpoint_url( 'view-order', $order_id, wc_get_page_permalink( 'myaccount' ) );
    }
    $redirect = add_query_arg(
        array(
            'oddw_rating_submitted' => '1',
            'oddw_rated_order'      => $order_id,
        ),
        $redirect
    );

    wp_safe_redirect( $redirect );
    exit;
}
add_action( 'init', 'oddw_handle_delivery_rating_submission' );

// Display Driver Ratings if WooCommerce setting isn't set to NO.
if ( 'no' !== get_option( 'oddw_settings_driver_ratings' ) ) {
    add_action( 'woocommerce_order_details_after_order_table', 'oddw_order_driver_details' );
} else {
    // Do nothing.
}

/**
 * Save File upload in user profile.
 * 
 * @since 1.6
 */
function oddw_save_custom_profile_fields( $user_id ) {

    // Get user.
    $user = get_userdata( $user_id );

    /**
     * If the user is a DRIVER, display the driver fields.
     */
    if ( in_array( 'driver', (array) $user->roles ) ) {
        // Verify nonce for security
        $nonce = '';
        if ( isset( $_POST['oddw_driver_profile_nonce'] ) ) {
            $nonce = sanitize_text_field( wp_unslash( $_POST['oddw_driver_profile_nonce'] ) );
        } elseif ( isset( $_POST['oddw_driver_profile_update_nonce'] ) ) {
            $nonce = sanitize_text_field( wp_unslash( $_POST['oddw_driver_profile_update_nonce'] ) );
        }
        if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'oddw_driver_profile_update' ) ) {
            return;
        }

        // Update license plate number.
        if ( isset( $_POST['oddw_driver_license_plate'] ) ) {
            update_user_meta( $user_id, 'oddw_driver_license_plate', sanitize_text_field( wp_unslash( $_POST['oddw_driver_license_plate'] ) ) );
        }

        // Update transportation type.
        if ( isset( $_POST['oddw_driver_transportation_type'] ) ) {
            update_user_meta( $user_id, 'oddw_driver_transportation_type', sanitize_text_field( wp_unslash( $_POST['oddw_driver_transportation_type'] ) ) );
        }

        // Update vehicle model.
        if ( isset( $_POST['oddw_driver_vehicle_model'] ) ) {
            update_user_meta( $user_id, 'oddw_driver_vehicle_model', sanitize_text_field( wp_unslash( $_POST['oddw_driver_vehicle_model'] ) ) );
        }

        // Update vehicle color.
        if ( isset( $_POST['oddw_driver_vehicle_color'] ) ) {
            update_user_meta( $user_id, 'oddw_driver_vehicle_color', sanitize_text_field( wp_unslash( $_POST['oddw_driver_vehicle_color'] ) ) );
        }

        // Update driver availability.
        if ( isset( $_POST['oddw_driver_availability'] ) ) {
            update_user_meta( $user_id, 'oddw_driver_availability', sanitize_text_field( wp_unslash( $_POST['oddw_driver_availability'] ) ) );
        }

        // Remove driver picture from user profile.
        if ( isset( $_POST['remove_driver_picture'] ) ) {
            update_user_meta( $user_id, 'oddw_driver_picture', '' );
        }

        // If no new files are uploaded, return.
        if ( ! isset( $_FILES ) || empty( $_FILES ) || ! isset( $_FILES['oddw_driver_picture'] ) )
            return;
        if ( empty( $_FILES['oddw_driver_picture']['name'] ) ) {
            return;
        }

        // Include file for wp_handle_upload.
        if ( ! function_exists( 'wp_handle_upload' ) ) {
            require_once( ABSPATH . 'wp-admin/includes/file.php' );
        }

        // Include file for wp_generate_attachment_metadata.
        if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
            require_once( ABSPATH . 'wp-admin/includes/image.php' );
        }

        // Handle the upload.
        $_POST['action'] = 'wp_handle_upload';

        // Get driver picture file upload (if any).
        $oddw_driver_picture = wp_handle_upload( $_FILES['oddw_driver_picture'], array( 'test_form' => false, 'mimes' => array( 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', 'jpeg' => 'image/jpeg' ) ) );

        // Take driver picture upload, add to media library.
        if ( isset( $oddw_driver_picture['file'] ) ) {
            // Update driver picture meta.
            update_user_meta( $user_id, 'oddw_driver_picture', $oddw_driver_picture, get_user_meta( $user_id, 'oddw_driver_picture', true ) );

            $filename   = $oddw_driver_picture['file'];
            $title      = explode( '.', basename( $filename ) );
            $ext        = array_pop( $title );
            $attachment = array(
                'guid'           => $oddw_driver_picture['url'], 
                'post_mime_type' => $oddw_driver_picture['type'],
                'post_title'     => implode( '.', $title ),
                'post_content'   => '',
                'post_status'    => 'inherit'
            );
            $attach_id   = wp_insert_attachment( $attachment, $filename );
            $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );

            wp_update_attachment_metadata( $attach_id, $attach_data );
            update_user_meta( $user_id, 'oddw_driver_image', $attach_id );
        }
    }
}
add_action( 'personal_options_update', 'oddw_save_custom_profile_fields' );
add_action( 'edit_user_profile_update', 'oddw_save_custom_profile_fields' );
add_action( 'woocommerce_save_account_details', 'oddw_save_custom_profile_fields' );

/**
 * Add profile options to Edit User screen
 * 
 * @since 1.6
 */
/**
 * Add form upload capabilites to edit user page.
 * 
 * @since 1.6
 */
add_action(
	'user_edit_form_tag',
	function() {
		echo ' enctype="multipart/form-data"';
	}
);

/**
 * Driver Ratings - Account-related functions moved to oddw-woocommerce-account-tab.php
 * 
 * @since 1.6
 */

// Ratings and delivery tracking functions below
