<?php

/**
 * WooCommerce Account Tab - Drivers
 *
 * @link       https://www.wpsaad.com
 * @since      1.0.0
 *
 * @package    ODDW
 * @subpackage ODDW/public/woocommerce
 */

/**
 * Register new endpoint to use inside My Account page.
 *
 * @see https://developer.wordpress.org/reference/functions/add_rewrite_endpoint/
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

function oddw_endpoints() {
	add_rewrite_endpoint( 'driver-dashboard', EP_ROOT | EP_PAGES );
}
add_action( 'init', 'oddw_endpoints' );

/**
 * Add new query var.
 *
 * @param array $vars
 * @return array
 * 
 * @since 1.2
 */
add_filter( 'woocommerce_get_query_vars', function ( $vars ) {
    foreach ( ['driver-dashboard'] as $e ) {
        $vars[$e] = $e;
    }
    return $vars;
} );

// Flush rewrite rules.
function oddw_flush_rewrite_rules() {
	add_rewrite_endpoint( 'driver-dashboard', EP_ROOT | EP_PAGES );
	flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'oddw_flush_rewrite_rules' );

/**
 * Insert the new endpoint into the My Account menu.
 *
 * @param array $items
 * @return array
 */
function oddw_my_account_menu_items( $items ) {
	// Get current user.
	$user = wp_get_current_user();
	// Get customer-logout menu item.
	$logout = $items['customer-logout'];
	// Remove the customer-logout menu item.
	unset( $items['customer-logout'] );
	// Set user roles.
	$roles = array( 'driver' );
	// Check user role.
	if ( oddw_check_user_roles( apply_filters( 'oddw_my_account_check_user_role_array', $roles ) ) ) {
		// Insert the driver-dashboard endpoint.
		$items['driver-dashboard'] = apply_filters( 'oddw_my_account_menu_item_driver_dashboard', __( 'Driver Dashboard', 'orders-delivery-drivers-for-woocommerce' ) );
	}
	// Insert back the customer-logout item.
	$items['customer-logout'] = $logout;

	return $items;
}
add_filter( 'woocommerce_account_menu_items', 'oddw_my_account_menu_items' );

/**
 * Endpoint HTML content.
 */
function oddw_endpoint_content() {
	echo do_shortcode( '[oddw_delivery_drivers_dashboard]' );
}
add_action( 'woocommerce_account_driver-dashboard_endpoint', 'oddw_endpoint_content', 99, 1 );

/**
 * Change endpoint title.
 *
 * @param string $title
 * @return string
 */
function oddw_endpoint_title( $title ) {

	if ( is_wc_endpoint_url( 'driver-dashboard' ) && in_the_loop() ) {
		$title = esc_html__( 'Driver Dashboard', 'orders-delivery-drivers-for-woocommerce' );
	}
	return $title;
}
add_filter( 'the_title', 'oddw_endpoint_title', 10, 1 );

/**
 * Add form tag with file upload support for edit account form
 * 
 * @since 1.6
 */
add_action(
	'woocommerce_edit_account_form_tag',
	function() {
		echo ' enctype="multipart/form-data"';
	}
);

/**
 * Add Driver Verification fields to WooCommerce My Account edit account page.
 * Uses woocommerce_form_field() for best practices.
 * 
 * @since 1.6
 */
function oddw_add_to_edit_account_form() {
    $user_id = get_current_user_id();
    $user    = get_userdata( $user_id );

    // Only show for drivers
    if ( ! $user || ! in_array( 'driver', (array) $user->roles ) ) {
        return;
    }

    echo '<div class="oddw-driver-verification-section">';
    echo '<h3>' . esc_html__( 'Driver Verification', 'orders-delivery-drivers-for-woocommerce' ) . '</h3>';

    // Pending Status Badge
    $is_pending = get_user_meta( $user_id, 'oddw_driver_pending_approval', true );
    if ( $is_pending ) {
        echo '<div class="oddw-pending-status-notice">';
        echo '<div class="oddw-pending-badge-wrapper">';
        echo '<span class="oddw-pending-badge"><strong>⚠ ' . esc_html__( 'Pending Admin Approval', 'orders-delivery-drivers-for-woocommerce' ) . '</strong></span>';
        echo '</div>';
        echo '<p class="oddw-pending-message">' . esc_html__( 'Your profile changes are awaiting admin review and approval.', 'orders-delivery-drivers-for-woocommerce' ) . '</p>';
        echo '</div>';
    }

    // Driver Picture (File Upload) - Using woocommerce_form_field for consistency
    $oddw_driver_image_id = get_user_meta( $user_id, 'oddw_driver_image', true );
    $legacy_driver_picture = get_user_meta( $user_id, 'oddw_driver_picture', true );
    $has_driver_picture = ! empty( $oddw_driver_image_id ) || ! empty( $legacy_driver_picture );
    $picture_preview_html = '';
    
    if ( $oddw_driver_image_id ) {
        $image_url = wp_get_attachment_url( $oddw_driver_image_id );
        if ( $image_url ) {
            $picture_preview_html .= '<div class="oddw-driver-picture-preview" id="oddw-picture-preview-' . esc_attr( $user_id ) . '">';
            $picture_preview_html .= '<a href="' . esc_url( $image_url ) . '" target="_blank" class="oddw-picture-link">';
            $picture_preview_html .= '<img src="' . esc_url( $image_url ) . '" width="120" height="120" alt="' . esc_attr__( 'Driver Picture', 'orders-delivery-drivers-for-woocommerce' ) . '" class="oddw-driver-picture-img" />';
            $picture_preview_html .= '</a>';
            $picture_preview_html .= '<button type="button" class="oddw-button-remove-picture" data-image-id="' . esc_attr( $oddw_driver_image_id ) . '" data-preview-id="#oddw-picture-preview-' . esc_attr( $user_id ) . '" data-image-type="driver" onclick="return false;" title="' . esc_attr__( 'Remove picture', 'orders-delivery-drivers-for-woocommerce' ) . '">✕</button>';
            $picture_preview_html .= '</div>';
        }
    } elseif ( get_user_meta( $user_id, 'oddw_driver_picture', true ) ) {
        $oddw_driver_picture = get_user_meta( $user_id, 'oddw_driver_picture', true );
        if ( ! isset( $oddw_driver_picture['error'] ) && ! empty( $oddw_driver_picture ) ) {
            $picture_url = is_array( $oddw_driver_picture ) ? $oddw_driver_picture['url'] : $oddw_driver_picture;
            $picture_preview_html .= '<div class="oddw-driver-picture-preview" id="oddw-picture-preview-' . esc_attr( $user_id ) . '">';
            $picture_preview_html .= '<a href="' . esc_url( $picture_url ) . '" target="_blank" class="oddw-picture-link">';
            $picture_preview_html .= '<img src="' . esc_url( $picture_url ) . '" width="120" height="120" alt="' . esc_attr__( 'Driver Picture', 'orders-delivery-drivers-for-woocommerce' ) . '" class="oddw-driver-picture-img" />';
            $picture_preview_html .= '</a>';
            $picture_preview_html .= '<button type="button" class="oddw-button-remove-picture" data-preview-id="#oddw-picture-preview-' . esc_attr( $user_id ) . '" data-image-type="driver" onclick="return false;" title="' . esc_attr__( 'Remove picture', 'orders-delivery-drivers-for-woocommerce' ) . '">✕</button>';
            $picture_preview_html .= '</div>';
        }
    }
    
    if ( ! empty( $picture_preview_html ) ) {
        echo wp_kses(
            $picture_preview_html,
            array(
                'div'    => array( 'class' => true, 'id' => true ),
                'a'      => array( 'href' => true, 'target' => true, 'class' => true ),
                'img'    => array( 'src' => true, 'width' => true, 'height' => true, 'alt' => true, 'class' => true ),
                'button' => array(
                    'type'            => true,
                    'class'           => true,
                    'data-image-id'   => true,
                    'data-preview-id' => true,
                    'data-image-type' => true,
                    'onclick'         => true,
                    'title'           => true,
                ),
            )
        );
    }
    
    // File upload field - rendered manually since woocommerce_form_field doesn't support file type well
    echo '<div class="form-row form-row-wide">';
    echo '<label for="oddw_driver_picture">' . esc_html__( 'Driver Picture', 'orders-delivery-drivers-for-woocommerce' ) . '&nbsp;<abbr class="required" title="required">*</abbr></label>';
    echo '<input type="file" id="oddw_driver_picture" name="oddw_driver_picture" accept="image/jpeg,image/png,image/gif"' . ( $has_driver_picture ? '' : ' required="required"' ) . ' class="input-text woocommerce-Input woocommerce-Input--file" />';
    echo '<input type="hidden" name="oddw_driver_picture_remove" value="0" />';
    echo '<small class="description">' . esc_html__( 'Supported formats: JPG, PNG, GIF. Maximum size: 5MB', 'orders-delivery-drivers-for-woocommerce' ) . '</small>';
    echo '</div>';

    // Car Image (File Upload)
    $oddw_driver_car_image_id = get_user_meta( $user_id, 'oddw_driver_car_image', true );
    $has_car_image            = ! empty( $oddw_driver_car_image_id );
    $car_preview_html         = '';

    if ( ! empty( $oddw_driver_car_image_id ) ) {
        $car_image_url = is_numeric( $oddw_driver_car_image_id )
            ? wp_get_attachment_url( (int) $oddw_driver_car_image_id )
            : $oddw_driver_car_image_id;

        if ( $car_image_url ) {
            $car_preview_html .= '<div class="oddw-car-picture-preview" id="oddw-car-picture-preview-' . esc_attr( $user_id ) . '">';
            $car_preview_html .= '<a href="' . esc_url( $car_image_url ) . '" target="_blank" class="oddw-picture-link">';
            $car_preview_html .= '<img src="' . esc_url( $car_image_url ) . '" width="120" height="120" alt="' . esc_attr__( 'Car Image', 'orders-delivery-drivers-for-woocommerce' ) . '" class="oddw-driver-picture-img" />';
            $car_preview_html .= '</a>';
            $car_preview_html .= '<button type="button" class="oddw-button-remove-picture" data-image-id="' . esc_attr( $oddw_driver_car_image_id ) . '" data-preview-id="#oddw-car-picture-preview-' . esc_attr( $user_id ) . '" data-image-type="car" onclick="return false;" title="' . esc_attr__( 'Remove car image', 'orders-delivery-drivers-for-woocommerce' ) . '">✕</button>';
            $car_preview_html .= '</div>';
        }
    }

    if ( ! empty( $car_preview_html ) ) {
        echo wp_kses(
            $car_preview_html,
            array(
                'div'    => array( 'class' => true, 'id' => true ),
                'a'      => array( 'href' => true, 'target' => true, 'class' => true ),
                'img'    => array( 'src' => true, 'width' => true, 'height' => true, 'alt' => true, 'class' => true ),
                'button' => array(
                    'type'            => true,
                    'class'           => true,
                    'data-image-id'   => true,
                    'data-preview-id' => true,
                    'data-image-type' => true,
                    'onclick'         => true,
                    'title'           => true,
                ),
            )
        );
    }

    echo '<div class="form-row form-row-wide">';
    echo '<label for="oddw_driver_car_image">' . esc_html__( 'Car Image', 'orders-delivery-drivers-for-woocommerce' ) . '</label>';
    echo '<input type="file" id="oddw_driver_car_image" name="oddw_driver_car_image" accept="image/jpeg,image/png,image/gif"' . ( $has_car_image ? '' : ' required="required"' ) . ' class="input-text woocommerce-Input woocommerce-Input--file" />';
    echo '<input type="hidden" name="oddw_driver_car_image_remove" value="0" />';
    echo '<small class="description">' . esc_html__( 'Supported formats: JPG, PNG, GIF. Maximum size: 5MB', 'orders-delivery-drivers-for-woocommerce' ) . '</small>';
    echo '</div>';

    // License Plate
    woocommerce_form_field(
        'oddw_driver_license_plate',
        array(
            'type'        => 'text',
            'label'       => esc_html__( 'License Plate Number', 'orders-delivery-drivers-for-woocommerce' ),
            'required'    => true,
            'class'       => array( 'form-row-wide' ),
        ),
        get_user_meta( $user_id, 'oddw_driver_license_plate', true )
    );

    // Driver License
    woocommerce_form_field(
        'oddw_driver_license',
        array(
            'type'        => 'text',
            'label'       => esc_html__( 'Driver License Number', 'orders-delivery-drivers-for-woocommerce' ),
            'required'    => true,
            'class'       => array( 'form-row-wide' ),
        ),
        get_user_meta( $user_id, 'oddw_driver_license', true )
    );

    // Phone
    woocommerce_form_field(
        'oddw_driver_phone',
        array(
            'type'        => 'tel',
            'label'       => esc_html__( 'Phone Number', 'orders-delivery-drivers-for-woocommerce' ),
            'required'    => true,
            'class'       => array( 'form-row-wide' ),
        ),
        get_user_meta( $user_id, 'oddw_driver_phone', true )
    );

    // Transportation Type
    $transportation_types = apply_filters(
        'oddw_woocommerce_edit_account_transportation_types',
        array(
            'Bicycle' => esc_html__( 'Bicycle', 'orders-delivery-drivers-for-woocommerce' ),
            'Car'     => esc_html__( 'Car', 'orders-delivery-drivers-for-woocommerce' ),
            'SUV'     => esc_html__( 'SUV', 'orders-delivery-drivers-for-woocommerce' ),
            'Truck'   => esc_html__( 'Truck', 'orders-delivery-drivers-for-woocommerce' ),
        )
    );
    
    woocommerce_form_field(
        'oddw_driver_transportation_type',
        array(
            'type'        => 'select',
            'label'       => esc_html__( 'Transportation Type', 'orders-delivery-drivers-for-woocommerce' ),
            'options'     => array( '' => '-- ' . esc_html__( 'Select', 'orders-delivery-drivers-for-woocommerce' ) . ' --' ) + $transportation_types,
            'required'    => true,
            'class'       => array( 'form-row-wide' ),
        ),
        get_user_meta( $user_id, 'oddw_driver_transportation_type', true )
    );

    // Vehicle Model
    woocommerce_form_field(
        'oddw_driver_vehicle_model',
        array(
            'type'        => 'text',
            'label'       => esc_html__( 'Vehicle Model', 'orders-delivery-drivers-for-woocommerce' ),
            'required'    => true,
            'class'       => array( 'form-row-wide' ),
        ),
        get_user_meta( $user_id, 'oddw_driver_vehicle_model', true )
    );

    // Vehicle Information
    woocommerce_form_field(
        'oddw_driver_vehicle',
        array(
            'type'        => 'text',
            'label'       => esc_html__( 'Vehicle Information', 'orders-delivery-drivers-for-woocommerce' ),
            'required'    => true,
            'class'       => array( 'form-row-wide' ),
        ),
        get_user_meta( $user_id, 'oddw_driver_vehicle', true )
    );

    // Vehicle Color
    woocommerce_form_field(
        'oddw_driver_vehicle_color',
        array(
            'type'        => 'text',
            'label'       => esc_html__( 'Vehicle Color', 'orders-delivery-drivers-for-woocommerce' ),
            'required'    => true,
            'class'       => array( 'form-row-wide' ),
        ),
        get_user_meta( $user_id, 'oddw_driver_vehicle_color', true )
    );

    // Years of Driving Experience
    woocommerce_form_field(
        'oddw_driver_experience',
        array(
            'type'        => 'text',
            'label'       => esc_html__( 'Years of Driving Experience', 'orders-delivery-drivers-for-woocommerce' ),
            'required'    => true,
            'class'       => array( 'form-row-wide' ),
        ),
        get_user_meta( $user_id, 'oddw_driver_experience', true )
    );

    // Available Hours
    woocommerce_form_field(
        'oddw_driver_availability_window',
        array(
            'type'        => 'text',
            'label'       => esc_html__( 'Available Hours', 'orders-delivery-drivers-for-woocommerce' ),
            'required'    => true,
            'class'       => array( 'form-row-wide' ),
        ),
        get_user_meta( $user_id, 'oddw_driver_availability_window', true )
    );

    // Additional Information
    woocommerce_form_field(
        'oddw_driver_message',
        array(
            'type'        => 'textarea',
            'label'       => esc_html__( 'Additional Information', 'orders-delivery-drivers-for-woocommerce' ),
            'required'    => true,
            'class'       => array( 'form-row-wide' ),
        ),
        get_user_meta( $user_id, 'oddw_driver_message', true )
    );

    // Security nonce
    wp_nonce_field( 'oddw_driver_profile_update', 'oddw_driver_profile_update_nonce' );
    
    echo '</div><!-- .oddw-driver-verification-section -->';
}
add_action(
	'woocommerce_edit_account_form',
	'oddw_add_to_edit_account_form'
);



/**
 * Enqueue scripts and styles for edit account form
 *
 * @since 1.6
 */
function oddw_enqueue_edit_account_assets() {
    if ( is_account_page() ) {
        wp_enqueue_script(
            'oddw-edit-account',
            plugin_dir_url( __FILE__ ) . '../js/oddw-edit-account.js',
            array( 'jquery' ),
            defined( 'ODDW_VERSION' ) ? ODDW_VERSION : '1.0.0',
            true
        );
    }
}
add_action( 'wp_enqueue_scripts', 'oddw_enqueue_edit_account_assets' );

/**
 * Save driver account fields.
 *
 * @param int $user_id User ID
 * @since 1.6
 */
function oddw_save_driver_account_fields( $user_id ) {
    // Verify nonce
    if ( ! isset( $_POST['oddw_driver_profile_update_nonce'] ) || 
         ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['oddw_driver_profile_update_nonce'] ) ), 'oddw_driver_profile_update' ) ) {
        return;
    }

    $user = get_userdata( $user_id );
    if ( ! $user || ! in_array( 'driver', (array) $user->roles ) ) {
        return;
    }

    // Fields to save (excluding file upload)
    $fields_to_save = array(
        'oddw_driver_license_plate',
        'oddw_driver_transportation_type',
        'oddw_driver_vehicle_model',
        'oddw_driver_vehicle_color',
        'oddw_driver_license',
        'oddw_driver_vehicle',
        'oddw_driver_experience',
        'oddw_driver_availability_window',
        'oddw_driver_phone',
        'oddw_driver_message',
    );

    $field_changed = false;

    // Save text/select fields
    foreach ( $fields_to_save as $field ) {
        if ( isset( $_POST[ $field ] ) ) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized via wc_clean().
            $value     = wc_clean( wp_unslash( $_POST[ $field ] ) );
            $old_value = get_user_meta( $user_id, $field, true );
            
            if ( $value !== $old_value ) {
                $field_changed = true;
            }
            
            update_user_meta( $user_id, $field, $value );
        }
    }

    // Handle driver picture removal
    if ( isset( $_POST['oddw_driver_picture_remove'] ) && '1' === sanitize_text_field( wp_unslash( $_POST['oddw_driver_picture_remove'] ) ) ) {
        $attach_id = get_user_meta( $user_id, 'oddw_driver_image', true );
        if ( ! empty( $attach_id ) ) {
            wp_delete_attachment( $attach_id, true );
            delete_user_meta( $user_id, 'oddw_driver_image' );
        }
        delete_user_meta( $user_id, 'oddw_driver_picture' );
        $field_changed = true;
    }

    // Handle car image removal
    if ( isset( $_POST['oddw_driver_car_image_remove'] ) && '1' === sanitize_text_field( wp_unslash( $_POST['oddw_driver_car_image_remove'] ) ) ) {
        $attach_id = get_user_meta( $user_id, 'oddw_driver_car_image', true );
        if ( ! empty( $attach_id ) ) {
            wp_delete_attachment( $attach_id, true );
            delete_user_meta( $user_id, 'oddw_driver_car_image' );
        }
        $field_changed = true;
    }

    // Handle file upload
    if ( ! empty( $_FILES['oddw_driver_picture']['name'] ) ) {
        $field_changed = true; // File upload detected
        oddw_handle_driver_picture_upload( $user_id );
    }

    if ( ! empty( $_FILES['oddw_driver_car_image']['name'] ) ) {
        $field_changed = true; // File upload detected
        oddw_handle_driver_car_image_upload( $user_id );
    }

    // Set pending if any field changed
    if ( $field_changed ) {
        update_user_meta( $user_id, 'oddw_driver_pending_approval', 1 );
        oddw_send_driver_profile_update_email( $user_id );
    }
}
add_action( 'woocommerce_save_account_details', 'oddw_save_driver_account_fields' );

/**
 * Handle driver picture upload
 *
 * @param int $user_id User ID
 * @since 1.6
 */
function oddw_handle_driver_picture_upload( $user_id ) {
    // Verify nonce for file upload
    if ( ! isset( $_POST['oddw_driver_profile_update_nonce'] ) || 
         ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['oddw_driver_profile_update_nonce'] ) ), 'oddw_driver_profile_update' ) ) {
        return;
    }

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

    // Check if file exists
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified above in this function.
    if ( empty( $_FILES['oddw_driver_picture'] ) ) {
        return;
    }

    // Validate file upload
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- validated before use.
    $uploaded_file = $_FILES['oddw_driver_picture'];
    
    if ( $uploaded_file['error'] !== UPLOAD_ERR_OK ) {
        return; // Silent fail - file not uploaded
    }

    // Validate file type
    $allowed_types = array( 'image/jpeg', 'image/png', 'image/gif' );
    $file_type     = wp_check_filetype( $uploaded_file['name'] );
    
    if ( ! in_array( $file_type['type'], $allowed_types, true ) ) {
        return; // Silent fail - invalid file type
    }

    // Validate file size (5MB max)
    if ( $uploaded_file['size'] > 5 * 1024 * 1024 ) {
        return; // Silent fail - file too large
    }

    // Handle upload
    $overrides = array( 'test_form' => false );
    $upload    = wp_handle_upload( $uploaded_file, $overrides );

    if ( isset( $upload['error'] ) ) {
        return; // Silent fail - upload error
    }

    if ( ! isset( $upload['file'] ) ) {
        return; // Silent fail - no file uploaded
    }

    // Create attachment
    $attachment = array(
        'post_mime_type' => $upload['type'],
        'post_title'     => 'Driver Picture - ' . $user_id,
        'post_content'   => '',
        'post_status'    => 'inherit',
    );

    $attach_id = wp_insert_attachment( $attachment, $upload['file'] );

    if ( ! is_wp_error( $attach_id ) ) {
        // Generate attachment metadata
        $attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
        wp_update_attachment_metadata( $attach_id, $attach_data );

        // Update user meta
        update_user_meta( $user_id, 'oddw_driver_image', $attach_id );
    }
}

/**
 * Handle driver car image upload
 *
 * @param int $user_id User ID
 * @since 1.6
 */
function oddw_handle_driver_car_image_upload( $user_id ) {
    // Verify nonce for file upload
    if ( ! isset( $_POST['oddw_driver_profile_update_nonce'] ) || 
         ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['oddw_driver_profile_update_nonce'] ) ), 'oddw_driver_profile_update' ) ) {
        return;
    }

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

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified above in this function.
    if ( empty( $_FILES['oddw_driver_car_image'] ) ) {
        return;
    }

    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- validated before use.
    $uploaded_file = $_FILES['oddw_driver_car_image'];

    if ( $uploaded_file['error'] !== UPLOAD_ERR_OK ) {
        return;
    }

    $allowed_types = array( 'image/jpeg', 'image/png', 'image/gif' );
    $file_type     = wp_check_filetype( $uploaded_file['name'] );

    if ( ! in_array( $file_type['type'], $allowed_types, true ) ) {
        return;
    }

    if ( $uploaded_file['size'] > 5 * 1024 * 1024 ) {
        return;
    }

    $overrides = array( 'test_form' => false );
    $upload    = wp_handle_upload( $uploaded_file, $overrides );

    if ( isset( $upload['error'] ) || ! isset( $upload['file'] ) ) {
        return;
    }

    $attachment = array(
        'post_mime_type' => $upload['type'],
        'post_title'     => 'Driver Car Image - ' . $user_id,
        'post_content'   => '',
        'post_status'    => 'inherit',
    );

    $attach_id = wp_insert_attachment( $attachment, $upload['file'] );

    if ( ! is_wp_error( $attach_id ) ) {
        $attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
        wp_update_attachment_metadata( $attach_id, $attach_data );

        update_user_meta( $user_id, 'oddw_driver_car_image', $attach_id );
    }
}

/**
 * Send admin email notification when driver updates profile
 *
 * @param int $user_id User ID
 * @since 1.6
 */
function oddw_send_driver_profile_update_email( $user_id ) {
    $user = get_userdata( $user_id );
    if ( ! $user ) {
        return;
    }

    $admin_email = get_option( 'admin_email' );
    $site_name = get_bloginfo( 'name' );
    
    /* translators: %s: site name */
    $subject = sprintf( __( '[%s] Driver Profile Update - Pending Approval', 'orders-delivery-drivers-for-woocommerce' ), $site_name );
    
    $message = sprintf(
        /* translators: 1: driver full name, 2: driver email, 3: user ID, 4: admin URL, 5: site name */
        __( 'Hello Admin,\n\nA driver has updated their profile and their account is now pending your approval.\n\nDriver Name: %1$s\nDriver Email: %2$s\nUser ID: %3$d\n\nPlease visit the admin panel to review and approve the changes.\n\n%4$s\n\nBest regards,\n%5$s', 'orders-delivery-drivers-for-woocommerce' ),
        $user->first_name . ' ' . $user->last_name,
        $user->user_email,
        $user_id,
        admin_url( 'admin.php?page=oddw-driver-applications' ),
        $site_name
    );

    wp_mail( $admin_email, $subject, $message );
}
