<?php

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/*-------------------------------------------------------------
  1) HELPER: Get location term IDs assigned to the current user.
--------------------------------------------------------------*/
function wcmlim_get_assigned_location_term_ids( $user_id ) {
	$assigned_term_ids = array();
	$locations = get_terms( array(
		'taxonomy'   => 'locations',
		'hide_empty' => false,
		'parent'     => 0,
	) );
	if ( ! is_wp_error( $locations ) && ! empty( $locations ) ) {
		foreach ( $locations as $term ) {
			$shopManagers = maybe_unserialize( get_term_meta( $term->term_id, 'wcmlim_shop_manager', true ) );
			if ( is_array( $shopManagers ) ) {
				$shopManagers = array_map( 'strval', $shopManagers );
				if ( in_array( (string) $user_id, $shopManagers, true ) ) {
					$assigned_term_ids[] = $term->term_id;
				}
			}
		}
	}
	return $assigned_term_ids;
}

/*-------------------------------------------------------------
  2) IMPORT-SIDE: Restrict CSV updates for allowed meta fields.
--------------------------------------------------------------*/
function wcmlim_restrict_csv_import_for_location_shop_manager( $product, $data ) {
	$current_user = wp_get_current_user();
	if ( ! in_array( 'location_shop_manager', (array) $current_user->roles, true ) ) {
		return $product; // Not our target role.
	}
	$current_user_id = $current_user->ID;
	
	// Get assigned location IDs.
	$assigned_term_ids = wcmlim_get_assigned_location_term_ids( $current_user_id );
	
	// For variations, check the parent product's location.
	$is_variation = $product->is_type( 'variation' );
	$product_id   = $product->get_id();
	$parent_id    = $is_variation ? $product->get_parent_id() : $product_id;
	
	$product_terms = get_the_terms( $parent_id, 'locations' );
	$has_assigned_location = false;
	if ( $product_terms && ! is_wp_error( $product_terms ) ) {
		foreach ( $product_terms as $prod_term ) {
			if ( in_array( (string)$prod_term->term_id, array_map('strval', $assigned_term_ids), true ) ) {
				$has_assigned_location = true;
				break;
			}
		}
	} else {
	}
	
	if ( ! $has_assigned_location ) {
		return $product;
	}
	
	// Prevent new product creation.
	if ( ! $product->get_id() ) {
		return null;
	}
	
	$original_product = wc_get_product( $product->get_id() );
	if ( ! $original_product ) {
		return $product;
	}
	
	$base_allowed_meta_keys = array(
		'wcmlim_allow_backorder',
		'wcmlim_allow_specific_location',
		'wcmlim_draft_stock',
		'wcmlim_stock',
		'wcmlim_stock_available',
		'wcmlim_product_availability',
		'wcmlim_regular_price',
		'wcmlim_sale_price',
		'wcmlim_cogs'
	);
	$allowed_meta_keys = array();
	foreach ( $assigned_term_ids as $term_id ) {
		foreach ( $base_allowed_meta_keys as $base_key ) {
			$allowed_meta_keys[] = $base_key . '_at_' . $term_id;
		}
	}
	
	// Lock core fields.
	$product->set_name( $original_product->get_name() );
	$product->set_description( $original_product->get_description() );
	$product->set_short_description( $original_product->get_short_description() );
	$product->set_price( $original_product->get_price() );
	$product->set_regular_price( $original_product->get_regular_price() );
	
	// Revert meta fields not allowed.
	$all_meta = $product->get_meta_data();
	foreach ( $all_meta as $meta_obj ) {
		$meta_key = $meta_obj->key;
		if ( ! in_array( $meta_key, $allowed_meta_keys, true ) ) {
			$original_value = $original_product->get_meta( $meta_key, true );
			$product->update_meta_data( $meta_key, $original_value );
		}
	}
	
	return $product;
}
add_filter( 'woocommerce_product_importer_pre_insert_product_object', 'wcmlim_restrict_csv_import_for_location_shop_manager', 10, 2 );

/*-------------------------------------------------------------
  3) CUSTOM IMPORT PAGE: Form, processing, and success redirect.
--------------------------------------------------------------*/
/** Remove default WooCommerce importer submenu */
function wcmlim_remove_default_wc_import_menu() {
	$current_user = wp_get_current_user();
	if ( in_array( 'location_shop_manager', (array) $current_user->roles, true ) ) {
		remove_submenu_page( 'edit.php?post_type=product', 'product_importer' );
	}
}
add_action( 'admin_menu', 'wcmlim_remove_default_wc_import_menu', 99 );

/** Add custom import submenu page */
function wcmlim_add_custom_import_page() {
	$current_user = wp_get_current_user();
	if ( ! in_array( 'location_shop_manager', (array) $current_user->roles, true ) ) {
		return;
	}
	add_submenu_page(
		'woocommerce',
		'Product Import',
		'Product Import',
		'manage_woocommerce',
		'wc-custom-import',
		'wcmlim_custom_import_page_callback'
	);
}
add_action( 'admin_menu', 'wcmlim_add_custom_import_page' );

/** Display the custom import form with potential success message */
function wcmlim_custom_import_page_callback() {
	$current_user = wp_get_current_user();
	if ( ! in_array( 'location_shop_manager', (array) $current_user->roles, true ) ) {
		echo '<p>You do not have permission to access this page.</p>';
		return;
	}
	if ( isset( $_GET['wcmlim_import_msg'] ) && $_GET['wcmlim_import_msg'] === 'success' ) {
		$count = isset( $_GET['updated_count'] ) ? intval( $_GET['updated_count'] ) : 0;
		echo '<div class="notice notice-success"><p>Import completed successfully. Updated ' . $count . ' products/variations.</p></div>';
	}
	?>
	<div class="wrap">
		<h1>Custom Product Import</h1>
		<p>Upload a CSV file with columns for Product ID (or Variation ID) and the allowed meta fields.
		Only items assigned to your location(s) will be updated.</p>
		<form method="post" enctype="multipart/form-data">
			<?php wp_nonce_field( 'wcmlim_custom_import', 'wcmlim_import_nonce' ); ?>
			<input type="hidden" name="wcmlim_import" value="1" />
			<table class="form-table">
				<tr>
					<th><label for="wcmlim_csv_file">CSV File</label></th>
					<td><input type="file" name="wcmlim_csv_file" id="wcmlim_csv_file" accept=".csv" /></td>
				</tr>
			</table>
			<?php submit_button( 'Import Now' ); ?>
		</form>
	</div>
	<?php
}

/** Process the CSV upload early on admin_init */
add_action( 'admin_init', 'wcmlim_maybe_handle_custom_import', 1 );
function wcmlim_maybe_handle_custom_import() {
	if ( ! isset( $_POST['wcmlim_import'] ) ) {
		return;
	}
	if ( ! check_admin_referer( 'wcmlim_custom_import', 'wcmlim_import_nonce' ) ) {
		return;
	}
	$current_user = wp_get_current_user();
	if ( ! in_array( 'location_shop_manager', (array) $current_user->roles, true ) ) {
		return;
	}
	if ( ! isset( $_FILES['wcmlim_csv_file'] ) || $_FILES['wcmlim_csv_file']['error'] !== UPLOAD_ERR_OK ) {
		wp_die( 'No CSV file uploaded or an upload error occurred.' );
	}
	ob_end_clean();
	wcmlim_handle_custom_import();
}

/** Process the CSV file and update products/variations */
function wcmlim_handle_custom_import() {
	$current_user_id = get_current_user_id();
	$assigned_term_ids = wcmlim_get_assigned_location_term_ids( $current_user_id );
	if ( empty( $assigned_term_ids ) ) {
		wp_die( 'No assigned locations found for your user.' );
	}
	
	$base_allowed_meta_keys = array(
		'wcmlim_allow_backorder',
		'wcmlim_allow_specific_location',
		'wcmlim_draft_stock',
		'wcmlim_stock',
		'wcmlim_stock_available',
		'wcmlim_product_availability',
		'wcmlim_regular_price',
		'wcmlim_sale_price',
		'wcmlim_cogs'
	);
	$allowed_meta_keys = array();
	foreach ( $assigned_term_ids as $term_id ) {
		foreach ( $base_allowed_meta_keys as $base_key ) {
			$allowed_meta_keys[] = $base_key . '_at_' . $term_id;
		}
	}
	
	$csv_path = $_FILES['wcmlim_csv_file']['tmp_name'];
	$handle = fopen( $csv_path, 'r' );
	if ( ! $handle ) {
		wp_die( 'Failed to open CSV file.' );
	}
	$headers = fgetcsv( $handle );
	if ( empty( $headers ) ) {
		wp_die( 'CSV appears empty or invalid.' );
	}
	
	// Map columns to allowed meta keys (skip column 0 which is ID)
	$meta_columns = array();
	foreach ( $headers as $col_index => $col_name ) {
		$col_name = trim( $col_name );
		if ( $col_index > 0 && in_array( $col_name, $allowed_meta_keys, true ) ) {
			$meta_columns[ $col_index ] = $col_name;
		}
	}
	
	$updated_count = 0;
	while ( ( $row = fgetcsv( $handle ) ) !== false ) {
		if ( empty( $row ) ) {
			continue;
		}
		$maybe_id = trim( $row[0] );
		if ( ! $maybe_id ) {
			continue;
		}
		$product_id = intval( $maybe_id );
		if ( ! $product_id ) {
			continue;
		}
		$product = wc_get_product( $product_id );
		if ( ! $product ) {
			continue;
		}
		// For variations, check parent's location
		$is_variation = $product->is_type( 'variation' );
		$parent_id = $is_variation ? $product->get_parent_id() : $product_id;
		
		$product_terms = get_the_terms( $parent_id, 'locations' );
		$has_assigned_location = false;
		if ( $product_terms && ! is_wp_error( $product_terms ) ) {
			foreach ( $product_terms as $prod_term ) {
				if ( in_array( $prod_term->term_id, $assigned_term_ids, true ) ) {
					$has_assigned_location = true;
					break;
				}
			}
		}
		if ( ! $has_assigned_location ) {
			continue;
		}
		
		// Update meta fields: only update if the CSV value is not empty.
		foreach ( $meta_columns as $col_index => $meta_key ) {
			if ( isset( $row[ $col_index ] ) ) {
				$new_value = trim( $row[ $col_index ] );
				if ( $new_value !== '' ) {
					update_post_meta( $product_id, $meta_key, $new_value );
				}
			}
		}
		$updated_count++;
	}
	fclose( $handle );
	
	// Redirect back with success message.
	$redirect_url = add_query_arg( array(
		'page'              => 'wc-custom-import',
		'wcmlim_import_msg' => 'success',
		'updated_count'     => $updated_count,
	), admin_url( 'admin.php' ) );
	wp_redirect( $redirect_url );
	exit;
}

/*---------------------------------------------------------------------
  4) CUSTOM EXPORT: With Variations Handling
-----------------------------------------------------------------------*/
/** Remove default WooCommerce export submenu */
function wcmlim_remove_default_wc_export_menu() {
	$current_user = wp_get_current_user();
	if ( in_array( 'location_shop_manager', (array) $current_user->roles, true ) ) {
		remove_submenu_page( 'woocommerce', 'wc-admin&path=/export/products' );
	}
}
add_action( 'admin_menu', 'wcmlim_remove_default_wc_export_menu', 98 );

/** Add a custom export submenu page */
function wcmlim_add_custom_export_page() {
	$current_user = wp_get_current_user();
	if ( ! in_array( 'location_shop_manager', (array) $current_user->roles, true ) ) {
		return;
	}
	add_submenu_page(
		'woocommerce',
		'Product Export',
		'Product Export',
		'manage_woocommerce',
		'wc-custom-export',
		'wcmlim_custom_export_page_callback'
	);
}
add_action( 'admin_menu', 'wcmlim_add_custom_export_page' );

/** Display the custom export form */
function wcmlim_custom_export_page_callback() {
	$current_user = wp_get_current_user();
	if ( ! in_array( 'location_shop_manager', (array) $current_user->roles, true ) ) {
		echo '<p>You do not have permission to access this page.</p>';
		return;
	}
	?>
	<div class="wrap">
		<h1>Custom Product Export (Including Variations)</h1>
		<p>Only products/variations linked to a location assigned to you will be exported, along with only the allowed meta fields.</p>
		<form method="post" action="">
			<?php wp_nonce_field( 'wcmlim_custom_export', 'wcmlim_export_nonce' ); ?>
			<input type="hidden" name="wcmlim_export" value="1" />
			<?php submit_button( 'Export Products Now' ); ?>
		</form>
	</div>
	<?php
	
	if ( isset( $_POST['wcmlim_export'] ) && check_admin_referer( 'wcmlim_custom_export', 'wcmlim_export_nonce' ) ) {
		ob_end_clean();
		wcmlim_handle_custom_export();
	}
}

/** Export handler: Query parent products and export them along with all their variations. */
function wcmlim_handle_custom_export() {
	$current_user    = wp_get_current_user();
	$current_user_id = $current_user->ID;
	$assigned_term_ids = wcmlim_get_assigned_location_term_ids( $current_user_id );
	
	if ( empty( $assigned_term_ids ) ) {
		wp_die( 'No assigned locations found.' );
	}
	
	// Build query: Query parent products (post_type = product) that are linked to assigned locations.
	$query_args = array(
		'post_type'      => 'product',
		'posts_per_page' => -1,
		'post_status'    => 'publish',
		'tax_query'      => array(
			array(
				'taxonomy' => 'locations',
				'field'    => 'term_id',
				'terms'    => $assigned_term_ids,
				'operator' => 'IN',
			),
		),
	);
	$query = new WP_Query( $query_args );
	if ( ! $query->have_posts() ) {
		wp_die( 'No products found to export for your assigned location(s).' );
	}
	
	// Base allowed meta keys.
	$base_allowed_meta_keys = array(
		'wcmlim_allow_backorder',
		'wcmlim_allow_specific_location',
		'wcmlim_draft_stock',
		'wcmlim_stock',
		'wcmlim_stock_available',
		'wcmlim_product_availability',
		'wcmlim_regular_price',
		'wcmlim_sale_price',
		'wcmlim_cogs'
	);
	$allowed_meta_keys = array();
	foreach ( $assigned_term_ids as $term_id ) {
		foreach ( $base_allowed_meta_keys as $base_key ) {
			$allowed_meta_keys[] = $base_key . '_at_' . $term_id;
		}
	}
	
	// CSV headers: ID, Type, ParentID, Name, plus allowed meta keys.
	$headers = array( 'ID', 'Type', 'ParentID', 'Name' );
	foreach ( $allowed_meta_keys as $key ) {
		$headers[] = $key;
	}
	
	$filename = 'custom-product-export-' . date( 'Y-m-d' ) . '.csv';
	header( 'Content-Type: text/csv; charset=utf-8' );
	header( 'Content-Disposition: attachment; filename=' . $filename );
	$output = fopen( 'php://output', 'w' );
	fputcsv( $output, $headers );
	
	// Loop through parent products.
	while ( $query->have_posts() ) {
		$query->the_post();
		$parent_id   = get_the_ID();
		$parent_prod = wc_get_product( $parent_id );
		if ( ! $parent_prod ) {
			continue;
		}
		
		// Export parent product row.
		$row = array();
		$row[] = $parent_id;
		$row[] = 'product';
		$row[] = '';
		$row[] = $parent_prod->get_name();
		foreach ( $allowed_meta_keys as $meta_key ) {
			$row[] = get_post_meta( $parent_id, $meta_key, true );
		}
		fputcsv( $output, $row );
		
		// If variable product, export each variation.
		if ( $parent_prod->is_type( 'variable' ) ) {
			$variation_ids = $parent_prod->get_children();
			foreach ( $variation_ids as $variation_id ) {
				$variation = wc_get_product( $variation_id );
				if ( ! $variation ) {
					continue;
				}
				$row = array();
				$row[] = $variation_id;
				$row[] = 'variation';
				$row[] = $parent_id;
				$row[] = $variation->get_name();
				foreach ( $allowed_meta_keys as $meta_key ) {
					$row[] = get_post_meta( $variation_id, $meta_key, true );
				}
				fputcsv( $output, $row );
			}
		}
	}
	fclose( $output );
	wp_reset_postdata();
	exit;
}


add_filter('manage_edit-product_columns', function ($columns) {
    if (current_user_can('location_shop_manager')) {  
        unset($columns['is_in_stock']); // Correct column key based on your HTML
    }
    return $columns;
}, 99);
 
 
function wcmlim_remove_import_export_caps_from_location_shop_manager() {
    $role = get_role( 'location_shop_manager' );
    if ( $role ) {
        // Remove WooCommerce import/export capabilities.
        $role->remove_cap( 'import' );
        $role->remove_cap( 'export' );
    }
}
add_action( 'init', 'wcmlim_remove_import_export_caps_from_location_shop_manager' );
