<?php


namespace Elex\MultiVendor\Controller;

if ( ! defined( 'ABSPATH' ) ) {
exit;
}

use Elex\MultiVendor\Model\Store;
use Elex\MultiVendor\Model\Vendor;

use Elex\MultiVendor\Model\SiteSettings;



class SiteSettingsController {
	public static $settings = null;
	const VERSION           = '2.0.0';


	public static function init() {
		$self = new self();
		add_action( 'wp_ajax_elex-multi-vendor-for-woocommerce-admin-intallation-setup', array( $self, 'elex_mv_admin_intallation_setup' ) );
		add_action( 'elex_mv_admin_setup_page_store-setup', array( $self, 'elex_mv_admin_setup_page_store_setup' ) );
		add_action( 'elex_mv_admin_setup_page_vendor-setup', array( $self, 'elex_mv_admin_setup_page_vendor_setup' ) );
		add_action( 'elex_mv_admin_setup_page_payment-setup', array( $self, 'elex_mv_admin_setup_page_pay_settle' ) );
		add_action( 'elex_mv_admin_setup_page_ready-setup', array( $self, 'elex_mv_admin_setup_page_ready_to_use' ) );
	}

  
 


	public function elex_mv_admin_intallation_setup() {
	

		$site_settings = SiteSettings::load();
		if ( ! isset( $_POST['elex-nonce'] ) || 
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['elex-nonce'] ) ), 'elex_mv_add_prod' ) 
			) {
			return;
		}


		$admin_install_array['elex_mv_make_me_vendor_switch'] = isset( $_POST['elex_mv_make_me_vendor_switch'] ) ? true : false;
		$admin_install_array['name']                          = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : $site_settings->get( 'name' );
		$admin_install_array['dial_code']                     = isset( $_POST['dial_code'] ) ? sanitize_text_field( wp_unslash( $_POST['dial_code'] ) ) : $site_settings->get( 'dial_code' );
		$admin_install_array['country_iso']                   = isset( $_POST['country_iso'] ) ? sanitize_text_field( wp_unslash( $_POST['country_iso'] ) ) : $site_settings->get( 'cuntry_iso' );
		$admin_install_array['phone_number']                  = isset( $_POST['phone_number'] ) ? sanitize_text_field( wp_unslash( $_POST['phone_number'] ) ) : $site_settings->get( 'phone_number' );
		$admin_install_array['store_full_addr1']              = isset( $_POST['store_full_addr1'] ) ? sanitize_text_field( wp_unslash( $_POST['store_full_addr1'] ) ) : $site_settings->get( 'store_full_addr1' );
		$admin_install_array['store_full_addr2']              = isset( $_POST['store_full_addr2'] ) ? sanitize_text_field( wp_unslash( $_POST['store_full_addr2'] ) ) : $site_settings->get( 'store_full_addr2' );

		$admin_install_array['city']                                      = isset( $_POST['city'] ) ? sanitize_text_field( wp_unslash( $_POST['city'] ) ) : $site_settings->get( 'city' );
		$admin_install_array['postal_code']                               = isset( $_POST['postal_code'] ) ? sanitize_text_field( wp_unslash( $_POST['postal_code'] ) ) : $site_settings->get( 'postal_code' );
		$admin_install_array['state']                                     = isset( $_POST['state'] ) ? sanitize_text_field( wp_unslash( $_POST['state'] ) ) : $site_settings->get( 'state' );
		$admin_install_array['country']                                   = isset( $_POST['country'] ) ? sanitize_text_field( wp_unslash( $_POST['country'] ) ) : $site_settings->get( 'country' );
		$admin_install_array['ship_fee']                                  = isset( $_POST['elex-multi-vendor-for-woocommerce-shipfee-radios'] ) ? sanitize_text_field( wp_unslash( $_POST['elex-multi-vendor-for-woocommerce-shipfee-radios'] ) ) : $site_settings->get( 'ship_fee' );
		$admin_install_array['tax_fee']                                   = isset( $_POST['elex-multi-vendor-for-woocommerce-taxfee-radios'] ) ? sanitize_text_field( wp_unslash( $_POST['elex-multi-vendor-for-woocommerce-taxfee-radios'] ) ) : $site_settings->get( 'tax_fee' );
		$admin_install_array['can_vendor_sell_products_without_approval'] = isset( $_POST['can_vendor_sell_products_without_approval'] ) ? sanitize_text_field( wp_unslash( $_POST['can_vendor_sell_products_without_approval'] ) ) : '';
		$admin_install_array['can_vendor_choose_shipping_services']       = isset( $_POST['can_vendor_choose_shipping_services'] ) ? sanitize_text_field( wp_unslash( $_POST['can_vendor_choose_shipping_services'] ) ) : '';
		$admin_install_array['can_vendor_create_product_category']        = isset( $_POST['can_vendor_create_product_category'] ) ? sanitize_text_field( wp_unslash( $_POST['can_vendor_create_product_category'] ) ) : '';
		$admin_install_array['allow_vendor_flat_rate']                    = isset( $_POST['allow_vendor_flat_rate'] ) ? sanitize_text_field( wp_unslash( $_POST['allow_vendor_flat_rate'] ) ) : '';

		$admin_install_array['can_vendor_change_order_status']      = isset( $_POST['can_vendor_change_order_status'] ) ? sanitize_text_field( wp_unslash( $_POST['can_vendor_change_order_status'] ) ) : '';
		$admin_install_array['approve_vendor_onboard']              = isset( $_POST['approve_vendor_onboard'] ) ? sanitize_text_field( wp_unslash( $_POST['approve_vendor_onboard'] ) ) : '';
		$admin_install_array['commission_for_each_sale']            = isset( $_POST['commission_for_each_sale'] ) ? sanitize_text_field( wp_unslash( $_POST['commission_for_each_sale'] ) ) : $site_settings->get( 'commission_for_each_sale' );
		$admin_install_array['commission_type_of_sale']             = isset( $_POST['commission_type_of_sale'] ) ? sanitize_text_field( wp_unslash( $_POST['commission_type_of_sale'] ) ) : $site_settings->get( 'commission_type_of_sale' );
		$admin_install_array['include_shipping_cost_in_commission'] = isset( $_POST['include_shipping_cost_in_commission'] ) ? true : $site_settings->get( 'include_shipping_cost_in_commission' );
		$admin_install_array['buffer_time']                         = isset( $_POST['buffer_time'] ) ? sanitize_text_field( wp_unslash( $_POST['buffer_time'] ) ) : 30;
		$admin_install_array['elex_mv_date_of_month_pay_settle']    = isset( $_POST['elex_mv_date_of_month_pay_settle'] ) ? sanitize_text_field( wp_unslash( $_POST['elex_mv_date_of_month_pay_settle'] ) ) : $site_settings->get( 'elex_mv_date_of_month_pay_settle' );
		$admin_install_array['elex_mv_order_status_radios']         = isset( $_POST['elex_mv_order_status_radios'] ) ? map_deep( wp_unslash( $_POST['elex_mv_order_status_radios'] ), 'sanitize_text_field' ) : array();
		$admin_install_array['is_setup_finished']                   = isset( $_POST['is_setup_finished'] ) ? sanitize_text_field( wp_unslash( $_POST['is_setup_finished'] ) ) : $site_settings->get( 'is_setup_finished' );
		$admin_install_array['vendor_onboarding_wizard']            = isset( $_POST['vendor_onboarding_wizard'] ) ? sanitize_text_field( wp_unslash( $_POST['vendor_onboarding_wizard'] ) ) : $site_settings->get( 'vendor_onboarding_wizard' );

	
		
		if ( $admin_install_array['is_setup_finished'] ) {
			update_option( 'elex_mv_admin_onboarding_done', true );
		}
		$validation_errors = $this->elex_mv_form_onboarding_validation( $admin_install_array );
		if ( isset( $validation_errors['errors'] ) && count( $validation_errors['errors'] ) ) {
			wp_send_json_error( $validation_errors['errors'] );
			die;
		}
		foreach ( $admin_install_array as $key => $value ) {
			$site_settings->set( $key, $value );
		}
		/**
		 * Fires a hook for saving settings
		 * 
		 * @since 1.0.0
		 * @param $site_settings
		 */
		$admin_site_options = apply_filters( 'elex_mv_settings_saving', $site_settings );

		$current_user = wp_get_current_user();
	

		if ( $admin_install_array['elex_mv_make_me_vendor_switch'] ) {

			$user_roles = ( isset( $current_user->roles ) ) ? $current_user->roles : null;


			$current_user->add_role( 'elex_mv_vendor' );


			$vendor_settings = Vendor::load( $current_user );
	
		
			$store = new Store();
			$store->set_vendor( $vendor_settings );
	
			if ( $vendor_settings->has_store() ) {
	
				$store = $vendor_settings->get_store();
	
			}

		

			$store->set_user_name( $current_user->display_name );
			$store->set_email( $current_user->user_email );

			if ( isset( $admin_install_array['name'] ) ) {
				$store->set_title( sanitize_text_field( $admin_install_array['name'] ) );
			}

			
			if ( isset( $admin_install_array['store_full_addr1'] ) ) {
				$store->set_address1( sanitize_text_field( $admin_install_array['store_full_addr1'] ) );
			}
			if ( isset( $admin_install_array['store_full_addr2'] ) ) {
				$store->set_address2( sanitize_text_field( $admin_install_array['store_full_addr2'] ) );
			}
			if ( isset( $admin_install_array['city'] ) ) {
				$store->set_city( sanitize_text_field( $admin_install_array['city'] ) );
			}
			if ( isset( $admin_install_array['state'] ) ) {
				$store->set_state( sanitize_text_field( $admin_install_array['state'] ) );
			}
			if ( isset( $admin_install_array['postal_code'] ) ) {
				$store->set_postal_code( sanitize_text_field( $admin_install_array['postal_code'] ) );
			}
			if ( isset( $admin_install_array['country'] ) ) {
				$store->set_country( sanitize_text_field( $admin_install_array['country'] ) );
			}
			if ( isset( $admin_install_array['phone_number'] ) ) {
				$store->set_phone_number( sanitize_text_field( $admin_install_array['phone_number'] ) );
			}
			if ( isset( $admin_install_array['paypal_email'] ) ) {
				$store->set_paypal_email( sanitize_text_field( $admin_install_array['paypal_email'] ) );
			}       
			if ( isset( $admin_install_array['dial_code'] ) ) {
				$store->set_dial_code( sanitize_text_field( $admin_install_array['dial_code'] ) );
			}
			if ( isset( $admin_install_array['country_iso'] ) ) {
				$store->set_country_iso( sanitize_text_field( $admin_install_array['country_iso'] ) );
			}
			if ( isset( $admin_install_array['commission_for_each_sale'] ) ) {
				$store->set_commission( sanitize_text_field( $admin_install_array['commission_for_each_sale'] ) );
			}
			$store->set_is_setup_finished( 'true' );

			$current_timestamp = current_time( 'timestamp' ); // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested
			$formatted_date    = wp_date( 'Y-m-d H:i:s', $current_timestamp );
			$store->set_creation_date( $formatted_date );

			$store->set_status( 'publish' );

			$store->create();
			
			$admin_params = get_option( 'elex_mv_admin_installation_params', false );
		
			//for all products 
			$this->run_query_if_admin_as_vendor( 'product', 'store_id', $store->get_id(), $admin_params );

			//for all orders 
			$this->run_query_if_admin_as_vendor( 'shop_order', 'elex_mv_has_sub_order', false, $admin_params );
			
	
		}

		$site_settings->save();

		$to = $current_user->user_email ;
					  
		$subject = "Welcome to ELEX Multi-Vendor for WooCommerce  - Let's Get Started!";
		$body    = 'Dear' . $current_user->display_name . ",

		We're thrilled to welcome you to ELEX Multi-Vendor for WooCommerce Plugin! 🎉
		
		Thank you for choosing our platform to power your multi-vendor business. We understand that selecting the right software is a significant decision, and we're committed to helping you succeed every step of the way.
		
		Here at ELEXtensions; we're your partners in growth. Our team is dedicated to providing you with the tools and support to streamline your operations, boost sales, and create a seamless shopping experience for your customers.
		
		Now that you're officially part of our community, here are a few things you can do to get started:
		
		1. **Explore Our Features:** Take some time to familiarize yourself with our plugin's features and capabilities. We offer a range of tools to help you manage vendors, track inventory, handle payments, and analyze your sales performance.
		
		2. **Get Support:** If you have any questions or encounter any issues, our customer support team is here to assist you. Reach out to https://support.elextensions.com/ anytime you need assistance.
		
		3. **Stay Informed:** Keep an eye on your email inbox and our blog for tips, updates, and best practices to make the most of our plugins.
		
		We're excited about the journey ahead and can't wait to see your business thrive on our plugin. Once again, welcome aboard! We're here to support you every step of the way as you build and grow your online business.
		
		If you have any questions or need assistance, don't hesitate to get in touch. Here's to a successful partnership!
		
		Best regards,";
	  
			

		$headers   = array();
		$headers[] = 'Content-type: text/html; charset=utf-8';
		$headers[] = 'From:' . get_bloginfo( 'admin_email' );
		// Send email using wp_mail() function
		$result = wp_mail( $to, $subject, $body, $headers );

		wp_send_json_success();
		/**
		 * Filter your settings
		 *
		 * @since 1.0.0
		 */
		do_action( 'elex_mv_settings_saved', $admin_site_options );
	}
	public function elex_mv_form_onboarding_validation( $admin_install_array ) {
		$data = array(
			'message' => __( 'Empty Fields' , 'elex-multi-vendor-for-woocommerce' ),
			'errors'  => array(),
		);

		if ( ! isset( $admin_install_array['elex_mv_order_status_radios'] ) || empty( $admin_install_array['elex_mv_order_status_radios'] ) ) {
			$data['errors']['elex_mv_order_status_radios'][] = __( 'Please select atleast one value', 'elex-multi-vendor-for-woocommerce' );
		}
		if ( ! isset( $admin_install_array['elex_mv_date_of_month_pay_settle'] ) || empty( $admin_install_array['elex_mv_date_of_month_pay_settle'] ) ) {
			$data['errors']['elex_mv_date_of_month_pay_settle'][] = __( 'Please enter number.', 'elex-multi-vendor-for-woocommerce' );
		}
		
		if ( isset( $admin_install_array['elex_mv_date_of_month_pay_settle'] ) && ! preg_match( '/^(2[0-8]|[1-9])$/', $admin_install_array['elex_mv_date_of_month_pay_settle'] ) ) {
			$data['errors']['elex_mv_date_of_month_pay_settle'][] = __( 'Please enter number between 1-28.', 'elex-multi-vendor-for-woocommerce' );
		}
		/**
		 * Fires a hook for validation data
		 * 
		 * @since 1.0.0
		 * @param $data
		 */
		$data = apply_filters( 'elex_mv_form_onboarding_validation', $data );
		return $data;
	}

	public function run_query_if_admin_as_vendor( $post_type, $meta_key, $meta_value, $admin_params ) {

		$per_page = 100; // Number of products per page
		$page     = 1;

		do {
			$args = array(
				'post_type'      => $post_type,
				'post_status'    => 'any',
				'posts_per_page' => $per_page,
				'paged'          => $page,
			);

			$products = get_posts( $args );

			if ( ! empty( $products ) ) {
				foreach ( $products as $producti ) {
					if ( 'shop_order' === $post_type ) {
						$product = wc_get_order( $producti->ID );
					}
					if ( 'product' === $post_type ) {
						$product         = wc_get_product( $producti->ID );
						$commission      = isset( $admin_params['commission_for_each_sale'] ) ? $admin_params['commission_for_each_sale'] : '';
						$commission_type = isset( $admin_params['commission_type_of_sale'] ) ? $admin_params['commission_type_of_sale'] : '';
				
						$product->update_meta_data( 'elex_mv_commission', $commission );
						$product->update_meta_data( 'elex_mv_commission_type', 'percent' );

					}
					$product->update_meta_data( $meta_key, $meta_value );
					$product->save();                   
					++$page;
				}           
			}
		} while ( ! empty( $products ) );
	}
	
	
	public function elex_mv_admin_setup_page_store_setup() {
		$site_settings = SiteSettings::load();
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/admin-site-settings/admin-store-setup.php';
	}

	public function elex_mv_admin_setup_page_vendor_setup() {
		$site_settings = SiteSettings::load();
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/admin-site-settings/admin-vendor-setup.php';
	}

	public function elex_mv_admin_setup_page_pay_settle() {
		$site_settings = SiteSettings::load();
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/admin-site-settings/admin-pay-settle.php';
	}

	public function elex_mv_admin_setup_page_ready_to_use() {
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/admin-site-settings/admin-ready.php';
	}
}
