<?php
/**
 * Fired during plugin activation
 *
 * @link  http://www.powerfulwp.com
 * @since 1.0.0
 *
 * @package    DDFWM
 * @subpackage DDFWM/includes
 */

/**
 * Fired during plugin activation.
 *
 * This class defines all code necessary to run during the plugin's activation.
 *
 * @since      1.0.0
 * @package    DDFWM
 * @subpackage DDFWM/includes
 * @author     powerfulwp <cs@powerfulwp.com>
 */
class DDFWM_Vendor {

	/**
	 * Drivers query
	 *
	 * @since 1.0.0
	 * @return array
	 */
	public static function ddfwm_get_drivers() {
		$args = array(
			'role'           => 'driver',
			'meta_query'     => array(
				'relation' => 'OR',
				array(
					'key'     => 'ddfwm_vendor_availability',
					'compare' => 'NOT EXISTS',
					'value'   => '',
				),
				array(
					'key'     => 'ddfwm_vendor_availability',
					'compare' => 'EXISTS',
				),
			),
			'orderby'        => 'meta_value ASC,display_name ASC',
			'posts_per_page' => -1,
		);
		return get_users( $args );
	}

		/**
		 * Function that return vendor role.
		 *
		 * @param int $vendor vendor user id.
		 * @since 1.6.0
		 * @return string
		 */
	public function ddfwm_vendor_role( $vendor ) {
		$result = '';
		switch ( $vendor ) {
			case 'dokan':
				$result = 'seller';
				break;
			case 'wcmp':
				$result = 'dc_vendor';
				break;
			case 'wcfm':
				$result = 'wcfm_vendor';
				break;
			default:
				$result = '';
				break;
		}
		return $result;
	}

	/**
	 * Store phone.
	 *
	 * @param object $order order object.
	 * @param int    $seller_id seller id.
	 * @return string
	 */
	public function ddfwm_store_phone( $order, $seller_id ) {
		$store_phone = get_option( 'lddfw_dispatch_phone_number', '' );

		if ( '' !== DDFWM_MULTIVENDOR ) {
			if ( '' !== $seller_id ) {
				if ( 'dokan' === DDFWM_MULTIVENDOR ) {
					$vendor     = dokan()->vendor->get( $seller_id );
					$shop_phone = $vendor->get_phone();
					if ( '' !== $shop_phone ) {
						return $shop_phone;
					}
				}
				if ( 'wcmp' === DDFWM_MULTIVENDOR ) {
					$shop_phone = get_user_meta( $seller_id, '_vendor_phone', true );
					if ( '' !== $shop_phone ) {
						return $shop_phone;
					}
				}
				if ( 'wcfm' === DDFWM_MULTIVENDOR ) {
					// Address.
					$vendor_data = get_user_meta( $seller_id, 'wcfmmp_profile_settings', true );
					$shop_phone  = isset( $vendor_data['phone'] ) ? $vendor_data['phone'] : '';
					if ( '' !== $shop_phone ) {
						return $shop_phone;
					}
				}
			}
		}

		return $store_phone;
	}

	/**
	 * Store name.
	 *
	 * @since 1.0.1
	 * @param object $order order object.
	 * @param int    $seller_id seller id.
	 * @return string
	 */
	public function ddfwm_store_name( $order, $seller_id ) {
		$store_name = get_bloginfo( 'name' );

		if ( '' !== DDFWM_MULTIVENDOR ) {
			if ( '' !== $seller_id ) {
				if ( 'dokan' === DDFWM_MULTIVENDOR ) {
					$vendor    = dokan()->vendor->get( $seller_id );
					$shop_name = $vendor->get_shop_name();
					if ( '' !== $shop_name ) {
						return $shop_name;
					}
				}
				if ( 'wcmp' === DDFWM_MULTIVENDOR ) {
					$shop_name = get_user_meta( $seller_id, '_vendor_page_title', true );
					if ( '' !== $shop_name ) {
						return $shop_name;
					}
				}
				if ( 'wcfm' === DDFWM_MULTIVENDOR ) {
					// Address.
					$vendor_data = get_user_meta( $seller_id, 'wcfmmp_profile_settings', true );
					$shop_name   = isset( $vendor_data['store_name'] ) ? $vendor_data['store_name'] : '';
					if ( '' !== $shop_name ) {
						return $shop_name;
					}
				}
			}
		}

		return $store_name;
	}

	/**
	 * Vendors query
	 *
	 * @since 1.0.0
	 * @return array
	 */
	public function ddfwm_get_vendors() {
		$args = array(
			'role'    => ddfwm_vendor_role(),
			'orderby' => 'meta_value ASC,display_name ASC',
		);
		return get_users( $args );
	}

	/**
	 * Vendors selectbox.
	 *
	 * @param  mixed $vendor_id .
	 * @param  mixed $name .
	 */
	public function ddfwm_vendor_selectbox( $vendor_id, $name ) {
			echo '<select name="' . esc_attr( $name ) . '" id="' . esc_attr( $name ) . '" class="widefat">';
			echo '<option value="">' . esc_html( __( 'Select a vendor', 'ddfwm' ) ) . '</option>';
			$vendors = $this->ddfwm_get_vendors();
		foreach ( $vendors as $vendor ) {
			$vendor_name = $vendor->display_name;
			$selected    = ( intval( $vendor_id ) === $vendor->ID ) ? 'selected' : '';
			echo '<option ' . esc_attr( $selected ) . ' value="' . esc_attr( $vendor->ID ) . '">' . esc_html( $vendor_name ) . '</option>';
		}
			echo '</optgroup></select>';
	}





	/**
	 * Edit driver form
	 *
	 * @param mixed $seller_id .
	 * @since 1.0.0
	 * @return array
	 */
	public function ddfwm_settings_form( $seller_id ) {
		$ddfwm_driver_commission_type  = get_user_meta( $seller_id, 'ddfwm_driver_commission_type', true );
		$ddfwm_driver_commission_value = get_user_meta( $seller_id, 'ddfwm_driver_commission_value', true );
		$html                          = '<div class="container">
			<div class="row">
				<div class="col-12">';
					$html             .= '<form service="ddfwm_edit_settings" class="ddfwm_form">
						<div class="ddfwm_alert_wrap"></div>
						<div class="ddfwm_wrap">
						';
					$html             .= '<div class="form-group row">
							<label class="col-sm-2 col-form-label" for="exampleInputEmail1">' . esc_html( __( 'Driver Commissions', 'ddfwm' ) ) . '</label>
							<div class="col-sm-8">
								<select name="ddfwm_driver_commission_type" class="form-control" id="ddfwm_driver_commission_type">
									<option value="" >' . esc_html( __( 'Select' ) ) . '</option>
									<option value="fixed" ' . selected( esc_attr( $ddfwm_driver_commission_type ), 'fixed', false ) . '">' . esc_html( __( 'Fixed Price' ) ) . '</option>
									<option value="delivery_percentage" ' . selected( esc_attr( $ddfwm_driver_commission_type ), 'delivery_percentage', false ) . '">' . esc_html( __( 'Delivery total percentage' ) ) . '</option>
									<option value="order_percentage" ' . selected( esc_attr( $ddfwm_driver_commission_type ), 'order_percentage', false ) . '">' . esc_html( __( 'Order total percentage' ) ) . '</option>
								</select>
							</div>
							<div class="col-sm-2">
								<div id="ddfwm_driver_commission_div" style="display:inline-block;position: relative">
									<div id="ddfwm_driver_commission_value_wrap" style="display: none;">
										<span id="ddfwm_driver_commission_symbol_currency" style="display:none">' . lddfw_currency_symbol() . '</span>
										<span id="ddfwm_driver_commission_symbol_percentage" style="display:none">%</span>
										<input class="form-control" type="text" size="5" name="ddfwm_driver_commission_value" id="ddfwm_driver_commission_value" value="' . $ddfwm_driver_commission_value . '">
									</div>
								</div>
							</div>
							</div>
						</div>';

						// buttons.
						$html .= '<br><br><br>
						<div class="d-grid gap-2 col-12 col-md-6 mx-auto">
								<button style="margin:0px;" class="ddfwm_submit_btn btn btn-lg btn-primary btn-block" type="submit">
								' . esc_html( __( 'Update', 'ddfwm' ) ) . '
								</button>
								<button style="display:none;margin:0px;" class="ddfwm_loading_btn btn-lg btn btn-block btn-primary" type="button" disabled>
								<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
								' . esc_html( __( 'Loading', 'ddfwm' ) ) . '
								</button>
								</div>
						</form>';

						$html .= '</div>
						</div>
			</div>
		</div>';
		return $html;
	}




	/**
	 * Edit settings service.
	 *
	 * @since 1.0.0
	 */
	public function ddfwm_edit_settings_service() {
		$error  = '';
		$result = '0';
		// Security check.
		if ( isset( $_POST['ddfwm_wpnonce'] ) ) {
			$nonce = sanitize_text_field( wp_unslash( $_POST['ddfwm_wpnonce'] ) );
			if ( ! wp_verify_nonce( $nonce, 'ddfwm-nonce' ) ) {
				$error = __( 'Security Check Failure - This alert may occur when you are logged in as an administrator and as a vendor on the same browser and the same device. If you want to work on both panels please try to work with two different browsers.', 'ddfwm' );
			} else {
				// Check vendor.
				$vendor = wp_get_current_user();
				if ( ! in_array( ddfwm_vendor_role(), (array) $vendor->roles, true ) ) {
					// No vendor.
					$error = __( 'You are not a vendor.', 'ddfwm' );
				} else {
					$vendor_id                     = $vendor->ID;
					$ddfwm_driver_commission_type  = ( isset( $_POST['ddfwm_driver_commission_type'] ) ) ? sanitize_text_field( wp_unslash( $_POST['ddfwm_driver_commission_type'] ) ) : '';
					$ddfwm_driver_commission_value = ( isset( $_POST['ddfwm_driver_commission_value'] ) && '' !== $ddfwm_driver_commission_type ) ? sanitize_text_field( wp_unslash( $_POST['ddfwm_driver_commission_value'] ) ) : '';

					update_user_meta( $vendor_id, 'ddfwm_driver_commission_type', $ddfwm_driver_commission_type );
					update_user_meta( $vendor_id, 'ddfwm_driver_commission_value', $ddfwm_driver_commission_value );
					$result = '1';
					$error  = __( 'The settings successfully updated.', 'ddfwm' );
				}
			}
		}
		echo '{"result":"' . esc_attr( $result ) . '", "error":"' . esc_attr( $error ) . '"}';
	}

	/**
	 * Function that return order seller id.
	 *
	 * @since 1.6.0
	 * @param object $order order.
	 * @return string
	 */
	public function order_seller( $order ) {
		$result = '';
		global $wpdb;
		$order_id = $order->get_id();
		switch ( DDFWM_MULTIVENDOR ) {
			case 'dokan':
				$result = $order->get_meta( '_dokan_vendor_id' );
				break;
			case 'wcmp':
				$result = $order->get_meta( '_vendor_id' );
				break;
			case 'wcfm':
				$query = $wpdb->get_results(
					$wpdb->prepare(
						'select vendor_id from ' . $wpdb->prefix . 'wcfm_marketplace_orders where order_id=%s',
						array( $order_id )
					)
				);
				if ( ! empty( $query ) ) {
					$result = $query[0]->vendor_id;
				}
				break;
			default:
				$result = '';
				break;
		}
		return $result;
	}


		/**
		 * Pickup address.
		 *
		 * @since 1.0.0
		 * @param string $format address format.
		 * @param object $order order object.
		 * @param int    $seller_id seller id.
		 * @return string
		 */
	public function ddfwm_pickup_address( $format, $order, $seller_id ) {
		$store_address = '';

		if ( '' !== DDFWM_MULTIVENDOR ) {
			// store address.
			if ( '' !== $seller_id ) {
				if ( 'dokan' === DDFWM_MULTIVENDOR ) {
					if ( function_exists( 'dokan_get_seller_address' ) ) {
						$array = dokan_get_seller_address( $seller_id, true );
						if ( is_array( $array ) ) {
							$store_address_1 = $array['street_1'];
							$store_address_2 = $array['street_2'];
							$store_city      = $array['city'];
							$store_postcode  = $array['zip'];
							$store_country   = $array['country'];
							$store_state     = $array['state'];
							if ( '' !== $array['street_1'] ) {
								return lddfw_format_address( $format, $array );
							}
						}
					}
				}
				if ( 'wcmp' === DDFWM_MULTIVENDOR ) {
					$array['street_1'] = get_user_meta( $seller_id, '_vendor_address_1', true );
					$array['street_2'] = get_user_meta( $seller_id, '_vendor_address_2', true );
					$array['city']     = get_user_meta( $seller_id, '_vendor_city', true );
					$array['zip']      = get_user_meta( $seller_id, '_vendor_postcode', true );
					$array['country']  = get_user_meta( $seller_id, '_vendor_country', true );
					$array['state']    = get_user_meta( $seller_id, '_vendor_state', true );
					if ( '' !== $array['street_1'] ) {
						return lddfw_format_address( $format, $array );
					}
				}
				if ( 'wcfm' === DDFWM_MULTIVENDOR ) {
					// Address.
					$vendor_data       = get_user_meta( $seller_id, 'wcfmmp_profile_settings', true );
					$array['street_1'] = ! empty( $vendor_data['address']['street_1'] ) ? $vendor_data['address']['street_1'] : '';
					$array['street_2'] = ! empty( $vendor_data['address']['street_2'] ) ? $vendor_data['address']['street_2'] : '';
					$array['city']     = ! empty( $vendor_data['address']['city'] ) ? $vendor_data['address']['city'] : '';
					$array['zip']      = ! empty( $vendor_data['address']['zip'] ) ? $vendor_data['address']['zip'] : '';
					$array['country']  = ! empty( $vendor_data['address']['country'] ) ? WC()->countries->countries[ $vendor_data['address']['country'] ] : '';
					$array['state']    = ! empty( $vendor_data['address']['state'] ) ? $vendor_data['address']['state'] : '';
					if ( '' !== $array['street_1'] ) {
						return lddfw_format_address( $format, $array );
					}
				}
			}
		}

		return $store_address;
	}
}
