<?php

namespace Elex\MultiVendor\Model;

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

use Elex\MultiVendor\Model\Vendor;

use WP_Post;

class Store { 

	const META_KEY = 'elex_vendor_data';

	public $store;

	public $store_attributes = array();
	
	public $vendor;
	public $vendor_id ; 
	public $store_id ;
	public $title;
	public $address1;
	public $address2;
	public $city;
	public $state;
	public $postal_code;
	public $country;
	public $paypal_email;
	public $is_setup_finished;
	public $image_name;
	public $image_path;
	public $image_type;
	public $phone_number;
	public $dial_code;
	public $country_iso;
	public $user_name;
	public $user_id;
	public $email;
	public $deleted_image;
	public $last_settlement_date;
	public $status;
	public $post_author;
	public $admin_paramsi ;
	public $creation_date ;
	public $edit_vendor_checkbox_button = array();
	public $store_creation_date;
	public $store_commission;
	public $global_capabilities;
	public $apply_vendor_commission_switch;
	public $category_commission_switch_vendor;
	public $product_commission_switch_vendor;

	public $categories_selected_for_commission;
	public $products_selected_for_commission;

	public $category_commission_vendor;
	public $product_commission_vendor;

	public function __construct() {

		$this->admin_paramsi = get_option( 'elex_mv_admin_installation_params', false );

		$this->edit_vendor_checkbox_button = array(
			// 'elex_mv_global_capabilities'                            => false,
			'elex_mv_vendor_to_sell_without_approval' => isset( $this->admin_paramsi['can_vendor_sell_products_without_approval'] ) ? $this->admin_paramsi['can_vendor_sell_products_without_approval'] : false,
			'elex_mv_vendor_to_allow_vendor_shipping' => isset( $this->admin_paramsi['allow_vendor_shipping'] ) ? $this->admin_paramsi['allow_vendor_shipping'] : false,
			'elex_mv_vendor_to_override_creds'        => isset( $this->admin_paramsi['allow_vendor_override_credentials'] ) ? $this->admin_paramsi['allow_vendor_override_credentials'] : false,
			'elex_mv_vendor_to_choose_ship_services'  => isset( $this->admin_paramsi['can_vendor_choose_shipping_services'] ) ? $this->admin_paramsi['can_vendor_choose_shipping_services'] : false,
			'elex_mv_vendor_to_use_flat_rate_service_set_by_admin' => isset( $this->admin_paramsi['allow_vendor_flat_rate'] ) ? $this->admin_paramsi['allow_vendor_flat_rate'] : false,
			'elex_mv_vendor_to_change_order_status'   => isset( $this->admin_paramsi['can_vendor_change_order_status'] ) ? $this->admin_paramsi['can_vendor_change_order_status'] : false,
			'elex_mv_vendor_to_generate_coupons'      => isset( $this->admin_paramsi['allow_vendor_coupon'] ) ? $this->admin_paramsi['allow_vendor_coupon'] : false,
			'elex_mv_vendor_to_create_category'       => isset( $this->admin_paramsi['can_vendor_create_product_category'] ) ? $this->admin_paramsi['can_vendor_create_product_category'] : false,

			'elex_mv_show_vendor_detail_on_woocom_store_page' => isset( $this->admin_paramsi['show_vendor_details_store_page'] ) ? $this->admin_paramsi['show_vendor_details_store_page'] : false,
			'elex_mv_show_vendor_detail_on_woocom_product_page' => isset( $this->admin_paramsi['show_vendor_details_product_page'] ) ? $this->admin_paramsi['show_vendor_details_product_page'] : false,
	
		);
	}
	
	public function set_store( WP_Post $store ) {
	

		$store_id       = $store->ID;
		$this->store    = $store;
		$this->store_id = $store_id;

		$this->title                = get_post_meta( $store_id, 'elex_mv_title', true );
		$this->user_id              = get_post_meta( $store_id, 'elex_mv_user_id', true );
		if ( empty( $this->user_id ) && ! empty( $store->post_author ) ) {
			$this->user_id = $store->post_author;
		}
		$this->user_name            = get_post_meta( $store_id, 'elex_mv_user_name', true );
		$this->phone_number         = get_post_meta( $store_id, 'elex_mv_phone_number', true );
		$this->dial_code            = get_post_meta( $store_id, 'elex_mv_dial_code', true );
		$this->country_iso          = get_post_meta( $store_id, 'elex_mv_country_iso', true );
		$this->email                = get_post_meta( $store_id, 'elex_mv_email', true );
		$this->address1             = get_post_meta( $store_id, 'elex_mv_address1', true );
		$this->address2             = get_post_meta( $store_id, 'elex_mv_address2', true );
		$this->city                 = get_post_meta( $store_id, 'elex_mv_city', true );
		$this->state                = get_post_meta( $store_id, 'elex_mv_state', true );
		$this->postal_code          = get_post_meta( $store_id, 'elex_mv_postal_code', true );
		$this->country              = get_post_meta( $store_id, 'elex_mv_country', true );
		$this->paypal_email         = get_post_meta( $store_id, 'elex_mv_paypal_email', true );
		$this->store_commission     = get_post_meta( $store_id, 'elex_mv_store_commission', true );
		$this->is_setup_finished    = get_post_meta( $store_id, 'elex_mv_is_setup_finished', true );
		$this->status               = $store->post_status;
		$this->last_settlement_date = get_post_meta( $store_id, 'elex_mv_last_settlement_date', true );
		$this->store_creation_date  = get_post_meta( $store_id, 'elex_mv_creation_date', true );
		$this->global_capabilities  = get_post_meta( $store_id, 'elex_mv_global_capabilities', true );

	
		$this->apply_vendor_commission_switch    = get_post_meta( $store_id, 'elex_mv_apply_vendor_commission_switch', true );
		$this->category_commission_switch_vendor = get_post_meta( $store_id, 'elex_mv_category_commission_switch_vendor', true );
		$this->product_commission_switch_vendor  = get_post_meta( $store_id, 'elex_mv_product_commission_switch_vendor', true );

		$this->categories_selected_for_commission = get_post_meta( $store_id, 'elex_mv_categories_selected_for_commission', true );
		$this->categories_selected_for_commission = $this->categories_selected_for_commission ;

		$this->products_selected_for_commission = get_post_meta( $store_id, 'elex_mv_products_selected_for_commission', true );
		$this->products_selected_for_commission = $this->products_selected_for_commission ;

		

		$this->category_commission_vendor = get_post_meta( $store_id, 'elex_mv_category_commission_vendor', true );
		$this->product_commission_vendor  = get_post_meta( $store_id, 'elex_mv_product_commission_vendor', true );

		$this->post_author = $store->post_author;

		foreach ( $this->edit_vendor_checkbox_button as $key => $value ) {
			$this->edit_vendor_checkbox_button[ $key ] = get_post_meta( $store_id, $key , true );
		}
	}

	public function set_vendor( Vendor $vendor ) {
		
		$this->vendor = $vendor;

		return $this;
	}

	public static function load_by_vendor( Vendor $vendor ) {
		$args                = array(
			'post_type' => 'elex_vendor',
			'author'    => $vendor->get_id(),
		);  
		$args['post_status'] = array( 'pending', 'private', 'publish', 'draft', 'reject' );

		$posts = get_posts( $args );

		
		if ( count( $posts ) === 0 ) {
			return ;
		}

		$store = new self();

		$store->set_store( $posts[0] );

		$store->set_vendor( $vendor );

		return $store;
	}

	public static function load_by_store( WP_Post $store ) {
	
		$self = new Store();
		$self->set_store( $store );

		$vendor = get_user_by( 'ID', $store->post_author );

		$self->set_vendor( Vendor::load( $vendor ) );

		return $self;
	}

	public function set_categories_selected_for_commission( $value ) {
		$this->categories_selected_for_commission = $value;
	}

	public function set_products_selected_for_commission( $value ) {
		$this->products_selected_for_commission = $value;
	}

	public function set_category_commission_vendor( $value ) {
		$this->category_commission_vendor = $value;
	}
	public function set_product_commission_vendor( $value ) {
		$this->product_commission_vendor = $value;
	}

	public function set_apply_vendor_commission_switch( $value ) {
		$this->apply_vendor_commission_switch = $value;
	}

	public function set_creation_date( $creation_date ) {
		$this->creation_date = $creation_date;
	}
	public function set_user_id( $user_id ) {
		$this->user_id = $user_id;
	}
	public function set_post_author( $a_id ) {
		$this->post_author = $a_id;
	}
	public function set_status( $status ) {
		$this->status = $status;
	}

	public function set_title( $title ) {
		$this->title = $title;
	}
	public function set_email( $email ) {
		$this->email = $email;
	}
	public function set_phone_number( $phone_number ) {
		$this->phone_number = $phone_number;
	}
	public function set_dial_code( $dial_code ) {
		$this->dial_code = $dial_code;
	}
	public function set_country_iso( $country_iso ) {
		$this->country_iso = $country_iso;
	}
	public function set_user_name( $user_name ) {
		$this->user_name = $user_name;
	}
	public function set_address1( $address1 ) {
		$this->address1 = $address1;
	}
	public function set_address2( $address2 ) {
		$this->address2 = $address2;
	}
	public function set_city( $city ) {
		$this->city = $city;
	}
	public function set_state( $state ) {
		$this->state = $state ;
	}
	public function set_postal_code( $postal_code ) {
		$this->postal_code = $postal_code;
	}
	public function set_country( $country ) {
		$this->country = $country;
	}
	public function set_paypal_email( $paypal_email ) {
		$this->paypal_email = $paypal_email;
	}
	public function set_commission( $commission ) {
		$this->store_commission = $commission;
	}

	public function set_global_capabilities_toggle( $global_capabilities ) {
		$this->global_capabilities = $global_capabilities;
	}
	
	public function set_is_setup_finished( $is_setup_finished ) {
		$this->is_setup_finished = $is_setup_finished;
	}
	public function set_image( $vendor_array ) {
		
		$this->image_name = $vendor_array['image_name'];
		$this->image_path = $vendor_array['image_path'];
		$this->image_type = $vendor_array['image_type'];
	}
	public function set_delete_image( $deleted_image ) {
		$this->deleted_image = $deleted_image;
	}
	public function set_last_settlement_date( $last_settlement_date ) {
		$this->last_settlement_date = $last_settlement_date ;
	}

	public function set_checkbox_list( $checkbox_array ) {
		foreach ( $checkbox_array as $key => $value ) {
			$this->edit_vendor_checkbox_button[ $key ] = $value ;
		}  
	}

	public function set_category_commission_switch_vendor( $value ) {
		$this->category_commission_switch_vendor = $value ;
	}

	public function set_product_commission_switch_vendor( $value ) {
		$this->product_commission_switch_vendor = $value;
	}

	public function get_categories_selected_for_commission() {
		return $this->categories_selected_for_commission;
	}

	public function get_products_selected_for_commission() {
		return $this->products_selected_for_commission;
	}

	public function get_category_commission_vendor() {
		return $this->category_commission_vendor ;
	}
	public function get_product_commission_vendor() {
		return $this->product_commission_vendor;
	}

	public function get_category_commission_switch_vendor() {
		return $this->category_commission_switch_vendor;
	}

	public function get_product_commission_switch_vendor() {
		return $this->product_commission_switch_vendor;
	}

	public function get_apply_vendor_commission_switch() {
		return $this->apply_vendor_commission_switch ;
	}   
	public function get_creation_date() {
		return $this->store_creation_date ;
	}
	public function get_checkbox_list() {
		return $this->edit_vendor_checkbox_button;
	}
	public function get_post_author() {
		return $this->post_author;
	}
	public function get_status() {
		return $this->status;
	}
	public function get_image() {
		return esc_url( get_the_post_thumbnail_url( $this->store_id ) );     // Thumbnail
	}
	public function get_title() {
		return $this->title;
	}
	public function get_email() {
		return $this->email;
	}
	public function get_phone_number() {
		return $this->phone_number;
	}
	public function get_dial_code() {
		return $this->dial_code;
	}
	public function get_country_iso() {
		return $this->country_iso;
	}
	public function get_user_name() {
		return $this->user_name;
	}
	public function get_user_id() {
		return $this->user_id;
	}

	public function get_address1() {
		return $this->address1;  
	}
	public function get_address2() {
		return $this->address2;  
	}

	public function get_city() {
		return $this->city ;
	}
	public function get_state() {
		return $this->state ;
	}
	public function get_postal_code() {
		return $this->postal_code;
	}
	public function get_country() {
		return $this->country;
	}
	public function get_paypal_email() {
		return $this->paypal_email ;
	}
	public function get_commission() {
		return $this->store_commission ;
	}
	public function get_is_setup_finished() {
		return $this->is_setup_finished;
	}
	public function get_id() {
		return $this->store->ID;
	}
	public function get_last_settlement_date() {
		return $this->last_settlement_date ;
	}

	public function get_global_capabilities_toggle() {
		return $this->global_capabilities ;
	}

	public function delete() {
		wp_delete_post( $this->store->ID );
	}

	public function create() {
		
		if ( empty( $this->user_id ) ) {
			if ( ! empty( $this->vendor ) && $this->vendor->get_id() ) {
				$this->user_id = $this->vendor->get_id();
			} elseif ( ! empty( $this->post_author ) ) {
				$this->user_id = $this->post_author;
			}
		}

		// only admin and vendor can edit store
		// admin can edit any store
		// vendor can edit only their own store
		// skip security check if we are currently REGISTERING a new user
		$current_user_id  = (int) get_current_user_id();
		$target_vendor_id = (int) $this->vendor->get_id();
		$is_registering = doing_action( 'woocommerce_created_customer' ) || doing_action( 'user_register' );
		if ( ! $is_registering ) {
		    if ( ! current_user_can( 'vendor_settings_manage' ) && $current_user_id !== $target_vendor_id ) {
		        return; 
		    }
		}

		$my_post = array(
			'post_status' => $this->status ? $this->status : 'pending',
			'post_type'   => 'elex_vendor',   
		);
		

		if ( null !== $this->vendor->get_id() && $this->vendor->get_id() ) {
			$my_post['post_author'] = $this->vendor->get_id();

			// This is a multi-vendor plugin, so wp_update_user function call is necessary.
			// This acts as a helper function to sync vendor profile names.
			// Nonce and capability checks are fully verified before calling this.
			wp_update_user(
				array(
					'ID'           => $this->vendor->get_id(),
					'display_name' => $this->user_name,
				)
			);
		}
		$my_post['post_title'] = $this->title;
		$my_post['post_name']  = $this->title;

		if ( $this->store_id ) {
			$my_post['ID'] = $this->store_id;
			wp_update_post( $my_post );
		} else {
			$this->store_id = wp_insert_post( $my_post );
		}

		if ( isset( $this->image_name ) && ! empty( $this->image_name ) ) {
			$thumbnail_id = $this->save_image( $this->image_name, $this->image_path, $this->image_type, $this->store_id );
			set_post_thumbnail( $this->store_id, $thumbnail_id );
		}


		if ( $this->deleted_image ) {
			set_post_thumbnail( $this->store_id, '' );
			wp_delete_attachment( $this->store_id, true );
			delete_post_thumbnail( $this->store_id );

		}
		

			update_post_meta( $this->store_id, 'elex_mv_title', $this->title );
			update_post_meta( $this->store_id, 'elex_mv_address1', $this->address1 );
			update_post_meta( $this->store_id, 'elex_mv_address2', $this->address2 );

			update_post_meta( $this->store_id, 'elex_mv_email', $this->email );
			update_post_meta( $this->store_id, 'elex_mv_city', $this->city );
			update_post_meta( $this->store_id, 'elex_mv_state', $this->state );
			update_post_meta( $this->store_id, 'elex_mv_postal_code', $this->postal_code );
			update_post_meta( $this->store_id, 'elex_mv_country', $this->country );
			update_post_meta( $this->store_id, 'elex_mv_paypal_email', $this->paypal_email );
			update_post_meta( $this->store_id, 'elex_mv_store_commission', $this->store_commission );
			update_post_meta( $this->store_id, 'elex_mv_is_setup_finished', $this->is_setup_finished );
			update_post_meta( $this->store_id, 'elex_mv_phone_number', $this->phone_number );
			update_post_meta( $this->store_id, 'elex_mv_dial_code', $this->dial_code );
			update_post_meta( $this->store_id, 'elex_mv_country_iso', $this->country_iso );
			update_post_meta( $this->store_id, 'elex_mv_user_name', $this->user_name );
			update_post_meta( $this->store_id, 'elex_mv_user_id', $this->user_id );
			update_post_meta( $this->store_id, 'elex_mv_last_settlement_date', gmdate( 'Y-m-d' ) );

			update_post_meta( $this->store_id, 'elex_mv_category_commission_switch_vendor', $this->category_commission_switch_vendor );
			update_post_meta( $this->store_id, 'elex_mv_product_commission_switch_vendor', $this->product_commission_switch_vendor );

			update_post_meta( $this->store_id, 'elex_mv_categories_selected_for_commission', $this->categories_selected_for_commission );
			update_post_meta( $this->store_id, 'elex_mv_products_selected_for_commission', $this->products_selected_for_commission );

			update_post_meta( $this->store_id, 'elex_mv_category_commission_vendor', $this->category_commission_vendor );
			update_post_meta( $this->store_id, 'elex_mv_product_commission_vendor', $this->product_commission_vendor );

		  
			update_post_meta( $this->store_id, 'elex_mv_apply_vendor_commission_switch' , $this->apply_vendor_commission_switch );

			update_post_meta( $this->store_id, 'elex_mv_banner_image_text', 'Welcome to ' . $this->title );

		if ( $this->creation_date ) {
			update_post_meta( $this->store_id, 'elex_mv_creation_date', $this->creation_date );
		}

			$site_settings = get_option( 'elex_mv_admin_installation_params', false );
		if ( empty( $site_settings['vendor_onboarding_wizard'] ) ) {
			update_post_meta( $this->store_id, 'elex_mv_is_setup_finished', true );
		}

		update_post_meta( $this->store_id, 'elex_mv_global_capabilities' , $this->global_capabilities );
		

		if ( true === self::get_global_capabilities_toggle() ) {

			update_post_meta( $this->store_id, 'elex_mv_vendor_to_sell_without_approval' , $site_settings['can_vendor_sell_products_without_approval'] );

			update_post_meta( $this->store_id, 'elex_mv_vendor_to_use_flat_rate_service_set_by_admin' , $site_settings['allow_vendor_flat_rate'] );
			update_post_meta( $this->store_id, 'elex_mv_vendor_to_change_order_status' , $site_settings['can_vendor_change_order_status'] );
			update_post_meta( $this->store_id, 'elex_mv_vendor_to_generate_coupons' , $site_settings['allow_vendor_coupon'] );
			update_post_meta( $this->store_id, 'elex_mv_vendor_to_create_category' , $site_settings['can_vendor_create_product_category'] );
	
			$site_settings['show_vendor_details_store_page']   = isset( $site_settings['show_vendor_details_store_page'] ) ? $site_settings['show_vendor_details_store_page'] : '';
			$site_settings['show_vendor_details_product_page'] = isset( $site_settings['show_vendor_details_product_page'] ) ? $site_settings['show_vendor_details_product_page'] : '';

			update_post_meta( $this->store_id, 'elex_mv_show_vendor_detail_on_woocom_store_page' , $site_settings['show_vendor_details_store_page'] );
			update_post_meta( $this->store_id, 'elex_mv_show_vendor_detail_on_woocom_product_page' , $site_settings['show_vendor_details_product_page'] );

			update_post_meta( $this->store_id, 'elex_mv_vendor_to_allow_vendor_shipping' , $site_settings['allow_vendor_shipping'] );
			update_post_meta( $this->store_id, 'elex_mv_vendor_to_override_creds' , $site_settings['allow_vendor_override_credentials'] );
			update_post_meta( $this->store_id, 'elex_mv_vendor_to_choose_ship_services' , $site_settings['can_vendor_choose_shipping_services'] );
			

		} else {

			foreach ( $this->edit_vendor_checkbox_button as $key => $value ) {
				update_post_meta( $this->store_id, $key, $value );

			}
		}
	

		update_user_meta( $this->vendor->get_id() , 'elex-multi-vendor-for-woocommerce-address-one-vendor', $this->address1 );
		update_user_meta( $this->vendor->get_id() , 'elex-multi-vendor-for-woocommerce-address-two-vendor', $this->address2 );
		update_user_meta( $this->vendor->get_id() , 'elex-multi-vendor-for-woocommerce-city-vendor', $this->city );
		update_user_meta( $this->vendor->get_id() , 'elex-multi-vendor-for-woocommerce-state-vendor', $this->state );
		update_user_meta( $this->vendor->get_id() , 'elex-multi-vendor-for-woocommerce-country-vendor', $this->country );
		update_user_meta( $this->vendor->get_id() , 'elex-multi-vendor-for-woocommerce-phone-vendor', $this->phone_number );
		update_user_meta( $this->vendor->get_id() , 'elex-multi-vendor-for-woocommerce-post-code-vendor', $this->postal_code );
		update_user_meta( $this->vendor->get_id() , 'elex-multi-vendor-for-woocommerce-email-add-vendor', $this->email );
		update_user_meta( $this->vendor->get_id() , 'elex-multi-vendor-for-woocommerce-store-name-vendor', $this->title );
		  
		return new self();
	}
	

	public function save_image( $image_name, $image_path, $image_type, $post_id ) {
		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'], $post_id );

		return $attach_id;
	}

	public static function get_stores( $args = array() ) {
 
		$args = wp_parse_args(
			$args,
			array(
				'post_type'        => 'elex_vendor',
				'post_status'      => array( 'publish' ),
				'suppress_filters' => false,
				'numberposts'      => -1,
			)
		);

		// remove_action('pre_user_query', array(self::class, 'overdue_filter'));
		add_filter(
			'posts_where',
			function ( $where ) use ( $args ) {
								global $wpdb;

				$site_settings = SiteSettings::load();
				$buffer_time   = $site_settings->get( 'buffer_time' );
				if ( isset( $args['settlement_status'] ) ) {
					if ( 'overdue' === $args['settlement_status'] ) {
						$where .= ' AND ' . $wpdb->posts . '.ID IN( SELECT post_id FROM ' . $wpdb->postmeta . ' where meta_key ="last_settlement_date" AND DATEDIFF(NOW(), ' . $wpdb->postmeta . '.meta_value) > ' . $buffer_time . ')';
					} else {                                                                   
						$where .= ' AND ' . $wpdb->posts . '.ID IN( SELECT post_id FROM ' . $wpdb->postmeta . ' where meta_key ="last_settlement_date" AND DATEDIFF(NOW(), ' . $wpdb->postmeta . '.meta_value) <= ' . $buffer_time . ' )';
				
					}
				}
				return $where;
			}
		);
		/**
		 * Filter the vendor list
		 *
		 * @since 1.0.0
		 */
		$args = apply_filters( 'elex_mv_vendor_list_arguments', $args );
		/**
		 * Filter the vendor store
		 *
		 * @since 1.0.0
		 */
		return apply_filters( 'elex_mv_stores', get_posts( $args ) );
	}
}
