<?php



namespace Elex\MultiVendor\Model;

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

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


class Product {

	public $admin_paramsi ;
	
	public function __construct() {

		$admin_paramsi = get_option( 'elex_mv_admin_installation_params', false );
	}




	public function create_product( $args, $all_fields_data = array() ) {
		// Get an empty instance of the product object (defining it's type)
		$product = $this->wc_get_product_object_type( $args );
		

		if ( isset( $args['elex_prod_id'] ) && ! empty( $args['elex_prod_id'] ) ) {
			$product = wc_get_product( $args['elex_prod_id'] );

			if ( isset( $args['product_type'] ) && 'variable' === $args['product_type'] ) {


				$classname = \WC_Product_Factory::get_product_classname( $args['elex_prod_id'], $args['product_type'] );

				$product = new $classname( $args['elex_prod_id'] );

				$product->save();


			} else {

	

				$classname = \WC_Product_Factory::get_product_classname( $args['elex_prod_id'], $args['product_type'] );

				$product = new $classname( $args['elex_prod_id'] );

				$product->save();
			}
			$product = wc_get_product( $args['elex_prod_id'] );



		}
		if ( isset( $args['product_id'] ) && ! empty( $args['product_id'] ) ) {
			$product = wc_get_product( $args['product_id'] );

			if ( isset( $args['product_type'] ) && 'variable' === $args['product_type'] ) {


				
				$classname = \WC_Product_Factory::get_product_classname( $args['product_id'], $args['product_type'] );

				$product = new $classname( $args['product_id'] );

				$product->save();

			
				
			} else {
			

				$classname = \WC_Product_Factory::get_product_classname( $args['product_id'], $args['product_type'] );

				$product = new $classname( $args['product_id'] );

				$product->save();
			
			}

			$product = wc_get_product( $args['product_id'] );

		}


		if ( ! $product ) {
			return false;
		}
				// Product name (Title) and slug
		if ( isset( $args['product_name'] ) ) {
			$product->set_name( $args['product_name'] ); // Name (title).

		}
	


			
		if ( isset( $args['product_description'] ) ) {
			$product->set_description( $args['product_description'] ); // Name (title).411111

		}

				$image_name = isset( $args['image_name'] ) ? $args['image_name'] : ''; // images url array of product
				$image_path = isset( $args['image_path'] ) ? $args['image_path'] : '';
				$image_type = isset( $args['image_type'] ) ? $args['image_type'] : '';
		
		if ( ! empty( $image_path ) ) {
			$mediaID = $this->save_image( $image_name, $image_path, $image_type ); // calling the uploadMedia function and passing image url to get the uploaded media id
			if ( $mediaID ) {
				$product->set_image_id( $mediaID ); // set the first image as primary image of the product
			} 
		}
				$cat_array_to_ins  = array();
				$cat_already_given = 0; 
		
			

		if ( isset( $args['product_category'] ) && ! empty( $args['product_category'] ) ) {

			$product->set_category_ids( $args['product_category'] );
		}


		if ( ! empty( $args['product_category_admin'] ) ) {
		
			$product->set_category_ids( $args['product_category_admin'] );
		}


		if ( isset( $args['regular_price'] ) ) {
			$product->set_regular_price( $args['regular_price'] );
		}
		if ( isset( $args['sale_price'] ) ) {
			if ( $args['sale_price'] <= $args['regular_price'] ) {
				$product->set_sale_price( $args['sale_price'] );
			}
		}
		if ( isset( $args['sale_start_date'] ) ) {
				$product->set_date_on_sale_from( $args['sale_start_date'] );
		}
		if ( isset( $args['sale_end_date'] ) ) {
			$product->set_date_on_sale_to( $args['sale_end_date'] );
		}
		
		if ( isset( $args['stock_value'] ) ) {
			$product->set_stock_quantity( $args['stock_value'] );
		}
		if ( isset( $args['lower_threshold'] ) ) {
			$product->set_low_stock_amount( $args['lower_threshold'] );
		}
		if ( isset( $args['manage_stock_level'] ) && 'on' === $args['manage_stock_level'] ) {
			$product->set_manage_stock( 'yes' );
		} else {
			$product->set_manage_stock( 'no' );

		}

		if ( isset( $args['shipping_class'] ) ) {
			$product->set_shipping_class_id( $args['shipping_class'] );

		}
		if ( isset( $args['download_expiry'] ) ) {
			$product->set_download_expiry( $args['download_expiry'] );

		}   
		if ( isset( $args['download_limit'] ) ) {
			$product->set_download_limit( $args['download_limit'] );

		}
		if ( isset( $args['stock_status'] ) ) {
			$product->set_stock_status( $args['stock_status'] );
		} 
		if ( isset( $args['allow_back_orders'] ) ) {
			$product->set_backorders( $args['allow_back_orders'] );
		}
		if (
			isset( $args['downloadable_product'] ) && 'on' === $args['downloadable_product'] ) {
			$product->set_downloadable( 'yes' );
		} elseif ( isset( $args['downloadable_product'] ) && '' === $args['downloadable_product'] ) {
			$product->set_downloadable( 'no' );
		}

	

		if ( isset( $args['sold_individual_orders'] ) && 'on' === $args['sold_individual_orders'] ) {
			$product->set_sold_individually( 'yes' );
		} elseif ( isset( $args['sold_individual_orders'] ) && '' === $args['sold_individual_orders'] ) {
			$product->set_sold_individually( 'no' );
		}

		if ( isset( $args['stock_value'] ) && 0 < $args['stock_value'] ) {
			$product->set_stock_status( 'instock' );
		}
		if ( isset( $args['sku'] ) ) {
			$product->set_sku( $args['sku'] );
		}
		if ( isset( $args['product_weight'] ) ) {
			$product->set_weight( $args['product_weight'] );
		}
		if ( isset( $args['product_length'] ) ) {
			$product->set_length( $args['product_length'] );
		}
		if ( isset( $args['product_width'] ) ) {
			$product->set_width( $args['product_width'] );
		}
		if ( isset( $args['product_height'] ) ) {
			$product->set_height( $args['product_height'] );
		}



		if ( isset( $args['virtual_product'] ) && 'on' === $args['virtual_product'] ) {
			$product->set_virtual( 'yes' );
		} elseif ( isset( $args['virtual_product'] ) && '' === $args['virtual_product'] ) {
			$product->set_virtual( 'no' );

		}


		$downloadable_files = array();

		if ( isset( $args['_wc_file_urls'] ) && ! empty( $args['_wc_file_urls'] ) ) {
			foreach ( $args['_wc_file_urls'] as $key => $fileUrl ) {
				$downloadable_files[] = array(
					'name' => isset( $args['_wc_file_names'][ $key ] ) ? $args['_wc_file_names'][ $key ] : basename( $fileUrl ),
					'file' => $fileUrl ? $fileUrl : '',
					'id'   => isset( $args['_wc_file_hashes'][ $key ] ) ? $args['_wc_file_hashes'][ $key ] : '',   

				);
			}
		}
		

		$downloads = array();

		// Add downloadable files to the product
		foreach ( $downloadable_files as $file ) {

			$file_name   = $file['name'];
			$file_url    = $file['file'];
			$download_id = md5( $file['file'] );

			if ( isset( $file['id'] ) && ! empty( $file['id'] ) ) {
				$download_id = $file['id'] ;
			}
			$download_id = md5( $file['file'] ); // Or use wp_generate_uuid4()

			$pd_object = new \WC_Product_Download();

			$pd_object->set_id( $download_id );
			$pd_object->set_name( $file_name );
			$pd_object->set_file( $file_url );
			$downloads[ $download_id ] = $pd_object;

		}
		$product->set_downloads( $downloads );



		
		if ( ! isset( $args['edit_page'] ) || empty( $args['edit_page'] ) ) {

			if ( isset( $args['save_as_draft'] ) && ! empty( $args['save_as_draft'] ) ) {
				$product->set_status( 'draft' );
		
			} elseif ( isset( $args['send_for_approval'] ) && 'yes' === $args['send_for_approval'] ) {
						
				$product->set_status( 'pending' );
			} 
		}
		if ( isset( $args['send_for_approval'] ) && 'yes' === $args['send_for_approval'] ) {
						
			$product->set_status( 'pending' );
		} 
		if ( isset( $args['publish'] ) && 'yes' === $args['publish'] ) {
						
			$product->set_status( 'publish' );
		} 
	

		$product->set_catalog_visibility( 'visible' );

	
		
		if ( $product->get_name() ) {
			$product_id = $product->save();
		}

		$vendor = Vendor::load( wp_get_current_user() );
		$store  = $vendor->get_store();
		

		$cat_ids = $product->get_category_ids(); 

		if ( $store->get_apply_vendor_commission_switch() ) {

			if ( $store->get_category_commission_switch_vendor() ) {
				$categories_com          = $store->get_category_commission_vendor();
				$categories_com_selected = $store->get_categories_selected_for_commission();

				$arr_cat = array();

				foreach ( $cat_ids as $cate ) {

					foreach ( $categories_com_selected as $key_cat => $cate_sel ) {
						$falg = 0;
						foreach ( $cate_sel  as $catval ) {

							$catval = explode( ':', $catval );
							if ( (int) $catval[0] === (int) $cate ) {

								$arr_cat[] = $key_cat;
								$falg      = 1;

								break;
							}                       
						}
						if ( 1 === $falg ) {
							break;
						}
					}               
				}
				if ( ! empty( $arr_cat ) ) {
					$min_index = min( $arr_cat );

					$commission = $categories_com[ $min_index ];
				}           
			}

			if ( $store->get_product_commission_switch_vendor() ) {
				$categories_com          = $store->get_product_commission_vendor();
				$categories_com_selected = $store->get_products_selected_for_commission();

				$arr_cat = array();


				foreach ( $categories_com_selected as $key_cat => $cate_sel ) {
					$falg = 0;
					foreach ( $cate_sel  as $catval ) {

						$catval = explode( ':', $catval );
						if ( (int) $catval[0] === (int) $product->get_id() ) {

							$commission = $categories_com[ $key_cat ];
							$falg       = 1;
							break;
							
						}                   
					}
					if ( 1 === $falg ) {
						break;
					}               
				}           
			}       
		}
		if ( empty( $commission ) || 0 === $commission ) {
			$commission = ! empty( get_post_meta( $store->get_id(), 'elex_mv_store_commission', true ) ) ? get_post_meta( $store->get_id(), 'elex_mv_store_commission', true ) : ''; 

		}

		if ( ! $store->get_apply_vendor_commission_switch() ) {
			$admin_params = get_option( 'elex_mv_admin_installation_params', false );
			$commission   = $admin_params['commission_for_each_sale'];

		}

		if ( empty( $product_commission ) ) {
			$product->update_meta_data( 'elex_mv_commission', $commission );
		}
					
		if ( isset( $args['vendor_store'] ) ) {

			$store_post     = get_post( $args['vendor_store'] );
			$store_assigned = new Store();
			$store_assigned->set_store( $store_post );
			$store_post_author = $store_assigned->get_post_author();



			$product_post              = get_post( $product_id );
			$product_post->post_author = $store_post_author;

			wp_update_post( $product_post );



			$product->update_meta_data( 'elex_mv_store_id', $args['vendor_store'] );
			$product_count = get_post_meta( $args['vendor_store'] , 'elex_mv_total_product_count' , true );
			$count_update  = (int) $product_count + 1;

			update_post_meta( $args['vendor_store'] , 'elex_mv_total_product_count' , $count_update );

		} else {
			$product->update_meta_data( 'elex_mv_store_id', $store->get_id() );
			$product_count = get_post_meta( $store->get_id() , 'elex_mv_total_product_count' , true );
			$count_update  = (int) $product_count + 1;

			if ( isset( $args['publish'] ) && 'yes' === $args['publish'] ) {
				update_post_meta( $store->get_id(), 'elex_mv_total_product_count' , $count_update );
			}
		}


		/**
		 * Hook for saving data in related to specific plugin.
		 *
		 * @since 1.0.0
		 */
		$new_product_array = apply_filters( 'elex_mv_products_specific_plugin_fields_to_save', $product_id, $all_fields_data );


		$product->update_meta_data( 'elex_mv_currency_code', get_woocommerce_currency() );
	
		$product->save();

		return $product_id;
	}


	// Utility function that returns the correct product object instance
	public function wc_get_product_object_type( $type ) {
		// Get an instance of the WC_Product object (depending on his type)
		if ( isset( $args['product_type'] ) && 'variable' === $args['product_type'] ) {
			$product = new \WC_Product_Variable();
		} else {
			$product = new \WC_Product_Simple(); // "simple" By default
		}

		if ( ! is_a( $product, 'WC_Product' ) ) {
			return false;
		} else {
			return $product;
		}
	}

	public function uploadMedia( $image_url ) {
		require_once ABSPATH . 'wp-admin/includes/image.php' ;
		require_once ABSPATH . 'wp-admin/includes/file.php' ;
		require_once ABSPATH . 'wp-admin/includes/media.php' ;
		$media       = media_sideload_image( $image_url, 0 );
		$attachments = get_posts(
			array(
				'post_type'   => 'attachment',
				'post_status' => null,
				'post_parent' => 0,
				'orderby'     => 'post_date',
				'order'       => 'DESC',
			)
		);
		return $attachments[0]->ID;
	}

	// Utility function that prepare product attributes before saving
	public function wc_prepare_product_attributes( $attributes ) {
		global $woocommerce;

		$data     = array();
		$position = 0;

		foreach ( $attributes as $taxonomy => $values ) {
			if ( ! taxonomy_exists( $taxonomy ) ) {
				continue;
			}

			// Get an instance of the WC_Product_Attribute Object
			$attribute = new WC_Product_Attribute();

			$term_ids = array();

			// Loop through the term names
			foreach ( $values['term_names'] as $term_name ) {
				if ( term_exists( $term_name, $taxonomy ) ) {
					// Get and set the term ID in the array from the term name
					$term_ids[] = get_term_by( 'name', $term_name, $taxonomy )->term_id;
				} else {
					continue;
				}
			}

			$taxonomy_id = wc_attribute_taxonomy_id_by_name( $taxonomy ); // Get taxonomy ID

			$attribute->set_id( $taxonomy_id );
			$attribute->set_name( $taxonomy );
			$attribute->set_options( $term_ids );
			$attribute->set_position( $position );
			$attribute->set_visible( $values['is_visible'] );
			$attribute->set_variation( $values['for_variation'] );

			$data[ $taxonomy ] = $attribute; // Set in an array

			++$position; // Increase position
		}
		return $data;
	}


	public function save_image( $image_name, $image_path, $image_type ) {
		if ( ! function_exists( 'wp_handle_upload' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}

		$file = array(
			'name'     => $image_name,
			'type'     => $image_type,
			'tmp_name' => $image_path,
			'error'    => UPLOAD_ERR_OK,
			'size'     => filesize( $image_path ),
		);

		$uploaded = wp_handle_upload( $file, array( 'test_form' => false ) );

		if ( isset( $uploaded['error'] ) || empty( $uploaded['file'] ) ) {
			return 0;
		}

		$attachment = array(
			'post_mime_type' => $uploaded['type'],
			'post_title'     => basename( $uploaded['file'] ),
			'post_content'   => '',
			'post_status'    => 'inherit',
			'guid'           => $uploaded['url'],
		);

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

		return $attach_id;
	}

	public static function product_status_count( $store_id ) {
		$status = array( 'publish', 'pending', 'reject' );
		foreach ( $status as $value ) {
			$product_status = get_posts(
				array(
					'post_type'   => 'product',
					'post_status' => $value,
					'meta_key'    => 'elex_mv_store_id',
					'meta_value'  => $store_id,
				)
			);
			update_post_meta( $store_id, 'elex_mv_product_status_' . $value, count( $product_status ) );
		}
	}
}
