<?php
if ( ! defined( 'ABSPATH' ) ) exit;

use Anbarak\Tables;

function anbarak_enqueue_woocommerce_admin_assets()
{
    $screen = function_exists('get_current_screen') ? get_current_screen() : null;

    wp_register_style('anbarak-woocommerce-admin-inline', false, [], ANBARAK_VERSION);
    wp_enqueue_style('anbarak-woocommerce-admin-inline');
    wp_add_inline_style(
        'anbarak-woocommerce-admin-inline',
        '.wc-order-preview-table__column--quantity{font-size:16px}.qty-1-plus .wc-order-preview-table__column--quantity{background:rgb(255,176,176)!important;font-weight:bold}'
    );

    $inline_scripts = [];

    if ($screen && 'product' === $screen->post_type && '1' !== anbarak_get_option('allow_edit_stock', 0)) {
        $inventory_stock = wp_json_encode(__('Inventory Stock', 'anbarak'));
        $managed_label   = wp_json_encode(__('Managed by Anbarak plugin', 'anbarak'));

        $inline_scripts[] = "jQuery(function($){var inventoryStock={$inventory_stock};var managedLabel={$managed_label};function anbarakDisableStockFields(){\$('#_stock,.wc_input_stock').prop('disabled',true);\$('.wc_input_stock').closest('p,.form-row').find('label').html(inventoryStock+' <b>('+managedLabel+')</b>');}anbarakDisableStockFields();\$(document.body).on('woocommerce_variations_loaded woocommerce_variations_added',anbarakDisableStockFields);});";
    }

    if ($screen && ('shop_order' === $screen->post_type || 'woocommerce_page_wc-orders' === $screen->id)) {
        $placeholder = wp_json_encode(__('Select User...', 'anbarak'));
        $inline_scripts[] = "jQuery(function($){if(!$.fn.select2){return;}\$('.wc-pos-user-select').select2({placeholder:{$placeholder},allowClear:true,ajax:{url:ajaxurl,dataType:'json',delay:250,data:function(params){return{action:'anbarak_pos_user_search',term:params.term};},processResults:function(data){return{results:data};},cache:true},minimumInputLength:1});});";
    }

    if (!$inline_scripts) {
        return;
    }

    wp_register_script('anbarak-woocommerce-admin-inline', false, ['jquery'], ANBARAK_VERSION, true);
    wp_enqueue_script('anbarak-woocommerce-admin-inline');
    wp_add_inline_script('anbarak-woocommerce-admin-inline', implode("\n", $inline_scripts));
}

function anbarak_show_order_item_buy_cost_column()
{
	echo '<th class="item_vendor">' . esc_html__('Buy Price', 'anbarak') . '</th>';
}

function anbarak_populate_buy_cost_column($product, $item)
{
	$buy_cost = wc_price($item->get_meta('_anbarak_buy_cost')) ?? '-';
	echo '<td>' . wp_kses_post($buy_cost) . '</td>';
}

function anbarak_add_order_admin_filter()
{
	global $typenow, $wpdb;

	if ('shop_order' !== $typenow) return;

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$selected = isset($_GET['anbarak_order_filter']) ? sanitize_text_field(wp_unslash($_GET['anbarak_order_filter'])) : '';
?>
	<select name="anbarak_order_filter" id="anbarak_order_filter">
		<option value=""><?php esc_html_e('All Orders', 'anbarak'); ?></option>
		<option value="yes" <?php selected($selected, 'yes'); ?>>
			<?php esc_html_e('Anbarak Manual Orders', 'anbarak'); ?>
		</option>
		<option value="no" <?php selected($selected, 'no'); ?>>
			<?php esc_html_e('Non-Anbarak Orders', 'anbarak'); ?>
		</option>
	</select>
	<?php
}

function anbarak_filter_orders_join($join)
{
	global $typenow, $wpdb;

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin list filter.
    if ('shop_order' === $typenow && isset($_GET['anbarak_order_filter'])) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$join .= " LEFT JOIN {$wpdb->prefix}anbarak_orders ON {$wpdb->posts}.ID = {$wpdb->prefix}anbarak_orders.orderid";
	}

	return $join;
}

function anbarak_filter_orders_where($where)
{
	global $typenow, $wpdb;

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin list filter.
    if ('shop_order' === $typenow && isset($_GET['anbarak_order_filter'])) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$filter = sanitize_text_field(wp_unslash($_GET['anbarak_order_filter']));

		if ($filter === 'yes') {
			$where .= " AND {$wpdb->prefix}anbarak_orders.orderid IS NOT NULL";
		} elseif ($filter === 'no') {
			$where .= " AND {$wpdb->prefix}anbarak_orders.orderid IS NULL";
		}
	}

	return $where;
}

/**
 * add pos user order filter
 */
function anbarak_add_order_admin_user_filter()
{
	global $typenow;
	if ($typenow === 'shop_order') {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$selected = isset($_GET['_anbarak_author']) ? sanitize_text_field(wp_unslash($_GET['_anbarak_author'])) : '';
		echo '<select name="_anbarak_author" class="wc-pos-user-select" style="width:200px;">';
		if ($selected) {
			$user = get_user_by('ID', $selected);
			if ($user) {
				printf(
					'<option value="%s" selected>%s</option>',
					esc_attr($user->ID),
					esc_html($user->display_name)
				);
			}
			}
			echo '</select>';
		}
	}

add_action('pre_get_posts', function ($query) {
    global $pagenow;
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin list filter.
    $post_type = isset($_GET['post_type']) ? sanitize_key(wp_unslash($_GET['post_type'])) : '';
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin list filter.
    $author_id = isset($_GET['_anbarak_author']) ? (int) sanitize_text_field(wp_unslash($_GET['_anbarak_author'])) : 0;

    if ($pagenow === 'edit.php' && 'shop_order' === $post_type && $author_id) {
        $meta_query = $query->get('meta_query', []);
        $meta_query[] = [
            'key' => '_anbarak_author',
            'value' => $author_id,
            'compare' => '='
        ];
        $query->set('meta_query', $meta_query);
    }
});




function anbarak_order_item_quantity_html($html, $item, $order)
{
	return $item->get_quantity() > 1 ? 'qty-1-plus' : '';
}

function anbarak_custom_product_data_tab($tabs)
{
	$tabs['inventory']['callback'] = 'anbarak_custom_inventory_options';
	return $tabs;
}


function anbarak_add_order_total_buy_costs($order_id)
{
	$order = wc_get_order($order_id);
	$total = $order->get_total();
	$shipping_total = $order->get_shipping_total();
	$total = $total - $shipping_total;
	$total_buy = $order->get_meta('_anbarak_total_buy_cost', true);
	$total_buy = !empty($total_buy) ? $total_buy : 1;
	$total_profit = (int)$total - (int)$total_buy;
	$total_profit_percent = ((int)$total_profit / (int)$total_buy) * 100;
	?>
	<tr>
		<td class="label"><?php echo esc_html__('Total Buy Price:', 'anbarak'); ?></td>
		<td width="1%"></td>
		<td><?php echo wp_kses_post(wc_price($total_buy)) ?></td>
	</tr>
	<tr>
		<td class="label"><?php echo esc_html__('Order Profit:', 'anbarak'); ?></td>
		<td width="1%"></td>
		<td><?php echo wp_kses_post(wc_price($total_profit)) ?> (<?php echo esc_html(round($total_profit_percent)) ?>%)</td>
	</tr>
<?php
}

function anbarak_exclude_anbarak_buy_cost_from_order($hidden_meta_keys)
{
	$hidden_meta_keys[] = '_anbarak_buy_cost';
	return $hidden_meta_keys;
}


function anbarak_recalculate_order_items_buy_cost($order_id, $items)
{

	foreach ($items['order_item_qty'] as $item_id => $item) {
		$order_item = new WC_Order_Item_Product($item_id);
		$product_id = $order_item->get_variation_id();

		// Get the original quantity before saving
		$original_quantity = wc_get_order_item_meta($item_id, '_qty', true);

		// Compare original quantity with current quantity
		if ($items['order_item_qty'][$item_id] != $original_quantity) {
			$qtyChange = $items['order_item_qty'][$item_id] - $original_quantity;
			$last_buy_cost = wc_get_order_item_meta($item_id, '_anbarak_buy_cost');

			// get buy cost for new quantity
			if (0 < $qtyChange) {
				$expense = anbarak_get_total_buy_cost($product_id, $qtyChange);
				// add another meta for new quantity items.
				// we will save it in separate meta to know buy costs at different times.
				wc_update_order_item_meta($item_id, '_anbarak_buy_cost', (int)$last_buy_cost + (int)$expense);
			} else {
				$unit_cost = $last_buy_cost / $original_quantity;
				$buy_cost = $items['order_item_qty'][$item_id] * $unit_cost;
				wc_update_order_item_meta($item_id, '_anbarak_buy_cost', $buy_cost);
			}
		}
	}
}
