<?php
/**
 * Fired during plugin activation.
 *
 * This class defines all code necessary to run during the plugin's activation.
 *
 * @since      1.0.0
 * @package    Wcmlim
 * @subpackage Wcmlim/includes
 * @author     techspawn1 <contact@techspawn.com>
 */
class Wcmlim_Activator
{

	/**
	 * Short Description. (use period)
	 *
	 * Long Description.
	 *
	 * @since    1.0.0
	 */
	public static function activate()
	{
		// Handle default location creation and stock migration
		self::handle_default_location_setup();
		
		$locationDistance = get_option('wcmlim_show_location_distance');
       if($locationDistance=="")
       {
       update_option('wcmlim_show_location_distance','miles',false);
       }
		
	   // Check selected view for stock display if is not set then set default view.
		$selected_view = get_option('wcmlim_backend_display_stock_view');
		if (empty($selected_view)) {
			update_option('wcmlim_backend_display_stock_view', 'list_view');
		}

		global $wp_roles;

		if (!isset($wp_roles)) {
			$wp_roles = new WP_Roles(); // @codingStandardsIgnoreLine
		}
		// Location Shop Regional manager role.
		add_role(
			'location_regional_manager',
			'Location Regional Manager',
			array(
				'level_9'                => true,
				'level_8'                => true,
				'level_7'                => true,
				'level_6'                => true,
				'level_5'                => true,
				'level_4'                => true,
				'level_3'                => true,
				'level_2'                => true,
				'level_1'                => true,
				'level_0'                => true,
				'read'                   => true,
				'read_private_pages'     => true,
				'read_private_posts'     => true,
				'edit_posts'             => true,
				'edit_pages'             => true,
				'edit_published_posts'   => true,
				'edit_published_pages'   => true,
				'edit_private_pages'     => true,
				'edit_private_posts'     => true,
				'edit_others_posts'      => true,
				'edit_others_pages'      => true,
				'publish_posts'          => true,
				'publish_pages'          => true,
				'delete_posts'           => true,
				'delete_pages'           => true,
				'delete_private_pages'   => true,
				'delete_private_posts'   => true,
				'delete_published_pages' => true,
				'delete_published_posts' => true,
				'delete_others_posts'    => true,
				'delete_others_pages'    => true,
				'manage_categories'      => true,
				'manage_links'           => true,
				'moderate_comments'      => true,
				'upload_files'           => true,
				'export'                 => true,
				'import'                 => true,
				'list_users'             => true,
				'edit_theme_options'     => true,
			)
		);
		// Location Shop manager role.
		add_role(
			'location_shop_manager',
			'Location Shop manager',
			array(
				'level_9'                => true,
				'level_8'                => true,
				'level_7'                => true,
				'level_6'                => true,
				'level_5'                => true,
				'level_4'                => true,
				'level_3'                => true,
				'level_2'                => true,
				'level_1'                => true,
				'level_0'                => true,
				'read'                   => true,
				'read_private_pages'     => true,
				'read_private_posts'     => true,
				'edit_posts'             => true,
				'edit_pages'             => true,
				'edit_published_posts'   => true,
				'edit_published_pages'   => true,
				'edit_private_pages'     => true,
				'edit_private_posts'     => true,
				'edit_others_posts'      => true,
				'edit_others_pages'      => true,
				'publish_posts'          => true,
				'publish_pages'          => true,
				'delete_posts'           => true,
				'delete_pages'           => true,
				'delete_private_pages'   => true,
				'delete_private_posts'   => true,
				'delete_published_pages' => true,
				'delete_published_posts' => true,
				'delete_others_posts'    => true,
				'delete_others_pages'    => true,
				'manage_categories'      => true,
				'manage_links'           => true,
				'moderate_comments'      => true,
				'upload_files'           => true,
				'export'                 => true,
				'import'                 => true,
				'list_users'             => true,
				'edit_theme_options'     => true,
			)
		);

		$capabilities = self::get_core_capabilities();

		foreach ($capabilities as $cap_group) {
			foreach ($cap_group as $cap) {
				$wp_roles->add_cap('location_shop_manager', $cap);
				$wp_roles->add_cap('location_regional_manager', $cap);			
			}
		}

		// Added Options on plugin activation


global $wpdb;
$options_table = $wpdb->prefix . 'options';                 
$ProductCentralControlOptions = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . $options_table . "` WHERE `option_name`= '%s'", 'ProductCentralControlOptions'));
$PCFO = maybe_unserialize($ProductCentralControlOptions[0]->option_value);
 if(!empty($PCFO)){

	$Values[] = array("id"=>"Show","thumbnail"=>"Show","name"=>"Show" ,"sku"=>"Show" ,"regular_price"=>"Show","sale_price"=>"Show" 
,"stock_quantity"=>"Show" ,"stock_status"=>"Show", "stock_at_location"=>"Show", "categories"=>"" , "tags"=>"" , "short_description"=>"" ,
"description"=>"", "type"=>"", "status"=>"", "parent"=>"", "catalog_visibility"=>"", "tax_status"=>"", "backorders"=>""
,"weight"=>"", "length"=>"", "width"=>"", "height"=>"" , "manage_stock"=>""  );

} else {
$Values[] = array("id"=>"Show","thumbnail"=>"Show","name"=>"Show" ,"sku"=>"Show" ,"regular_price"=>"Show","sale_price"=>"Show" 
,"stock_quantity"=>"Show" ,"stock_status"=>"Show", "stock_at_location"=>"Show", "categories"=>"" , "tags"=>"" , "short_description"=>"" ,
"description"=>"", "type"=>"", "status"=>"", "parent"=>"", "catalog_visibility"=>"", "tax_status"=>"", "backorders"=>""
,"weight"=>"", "length"=>"", "width"=>"", "height"=>"" , "manage_stock"=>""  );
update_option( 'ProductCentralControlOptions', $Values );
} 
	}

	private static function get_core_capabilities()
	{
		$capabilities = array();

		$capabilities['core'] = array(
			'manage_woocommerce',
			// 'view_woocommerce_reports',
		);

		$capability_types = array('product', 'shop_order', 'shop_coupon');

		foreach ($capability_types as $capability_type) {

			$capabilities[$capability_type] = array(
				// Post type.
				"edit_{$capability_type}",
				"read_{$capability_type}",
				"delete_{$capability_type}",
				"edit_{$capability_type}s",
				"edit_others_{$capability_type}s",
				"publish_{$capability_type}s",
				"read_private_{$capability_type}s",
				"delete_{$capability_type}s",
				"delete_private_{$capability_type}s",
				"delete_published_{$capability_type}s",
				"delete_others_{$capability_type}s",
				"edit_private_{$capability_type}s",
				"edit_published_{$capability_type}s",

				// Terms.
				"manage_{$capability_type}_terms",
				"edit_{$capability_type}_terms",
				"delete_{$capability_type}_terms",
				"assign_{$capability_type}_terms",
			);
		}

		return $capabilities;
	}

	/**
	 * Handle default location setup and stock migration on plugin activation
	 * 
	 * This method:
	 * 1. Checks if locations already exist (not first-time activation)
	 * 2. If no locations exist, creates a "Default Online Stock" location
	 * 3. Migrates existing WooCommerce stock to this default location
	 * 4. Stores the default location term ID for future reference
	 *
	 * @since 1.0.0
	 */
	private static function handle_default_location_setup()
	{
		// Ensure the locations taxonomy is registered during activation
		self::ensure_locations_taxonomy_registered();

		// Check if any locations already exist
		$existing_locations = get_terms(array(
			'taxonomy' => 'locations',
			'hide_empty' => false,
			'parent' => 0
		));

		// If locations already exist, this is not a first-time activation
		if (!empty($existing_locations) && !is_wp_error($existing_locations)) {
			return;
		}

		// Check if we've already created the default location during a previous activation
		$default_location_id = get_option('wcmlim_default_location_id');
		if ($default_location_id && term_exists($default_location_id, 'locations')) {
			return;
		}

		// Create the default location
		$default_location = wp_insert_term(
			'Online Store',
			'locations',
			array(
				'description' => 'Default location created automatically to preserve existing WooCommerce stock.',
				'slug' => 'online-store'
			)
		);

		// If location creation failed, return early
		if (is_wp_error($default_location)) {
			error_log('WCMLIM: Failed to create default location - ' . $default_location->get_error_message());
			return;
		}

		$default_location_term_id = $default_location['term_id'];

		// Store the default location ID for future reference
		update_option('wcmlim_default_location_id', $default_location_term_id);

		// Add meta data to identify this as the default location
		update_term_meta($default_location_term_id, 'wcmlim_is_default_location', 'yes');
		update_term_meta($default_location_term_id, 'wcmlim_created_on_activation', current_time('mysql'));

		// Now migrate existing WooCommerce stock to this location
		self::migrate_existing_stock_to_default_location($default_location_term_id);
	}

	/**
	 * Ensure the locations taxonomy is registered during activation
	 * This is needed because the main plugin might not have loaded yet
	 *
	 * @since 1.0.0
	 */
	private static function ensure_locations_taxonomy_registered()
	{
		// Check if taxonomy is already registered
		if (taxonomy_exists('locations')) {
			return;
		}

		// Register the taxonomy temporarily for activation
		$labels = array(
			'name' => 'Locations',
			'singular_name' => 'Location',
		);

		$args = array(
			'labels' => $labels,
			'hierarchical' => true,
			'public' => true,
			'show_ui' => true,
			'show_admin_column' => true,
		);

		register_taxonomy('locations', 'product', $args);
	}

	/**
	 * Migrate existing WooCommerce stock to the default location
	 *
	 * @param int $default_location_term_id The term ID of the default location
	 * @since 1.0.0
	 */
	private static function migrate_existing_stock_to_default_location($default_location_term_id)
	{
		global $wpdb;

		// Get all products with stock
		$products_with_stock = $wpdb->get_results($wpdb->prepare("
			SELECT DISTINCT post_id, meta_value as stock_quantity
			FROM {$wpdb->postmeta} pm
			INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
			WHERE pm.meta_key = %s
			AND pm.meta_value > 0
			AND p.post_type IN ('product', 'product_variation')
			AND p.post_status = 'publish'
		", '_stock'));

		if (empty($products_with_stock)) {
			return;
		}

		$migrated_count = 0;
		$meta_key = "wcmlim_stock_at_{$default_location_term_id}";

		foreach ($products_with_stock as $product) {
			$product_id = intval($product->post_id);
			$stock_quantity = intval($product->stock_quantity);

			// Only migrate if there's no existing location stock for this product
			$existing_location_stock = get_post_meta($product_id, $meta_key, true);
			
			if (empty($existing_location_stock)) {
				// Set the stock for this location
				update_post_meta($product_id, $meta_key, $stock_quantity);
				
				// Link the product to the default location
				wp_set_object_terms($product_id, $default_location_term_id, 'locations', true);
				
				$migrated_count++;
			}
		}

		// After migration, update the main stock to ensure consistency
		self::update_main_stock_for_migrated_products($default_location_term_id);

		// Log the migration result
		if ($migrated_count > 0) {
			error_log("WCMLIM: Successfully migrated stock for {$migrated_count} products to default location (ID: {$default_location_term_id})");
		}
	}

	/**
	 * Update main WooCommerce stock based on location stocks after migration
	 *
	 * @param int $default_location_term_id The term ID of the default location
	 * @since 1.0.0
	 */
	private static function update_main_stock_for_migrated_products($default_location_term_id)
	{
		global $wpdb;

		// Get all products that have stock at the default location
		$products_at_default_location = $wpdb->get_results($wpdb->prepare("
			SELECT post_id, meta_value as location_stock
			FROM {$wpdb->postmeta}
			WHERE meta_key = %s
			AND meta_value > 0
		", "wcmlim_stock_at_{$default_location_term_id}"));

		foreach ($products_at_default_location as $product_data) {
			$product_id = intval($product_data->post_id);
			$location_stock = intval($product_data->location_stock);

			// For newly migrated products, the location stock should equal the main stock
			// Since we only have one location (default), the sum equals the location stock
			update_post_meta($product_id, '_stock', $location_stock);
			
			// Update stock status
			$stock_status = $location_stock > 0 ? 'instock' : 'outofstock';
			update_post_meta($product_id, '_stock_status', $stock_status);
		}
	}
}
