<?php

namespace AC_SYNC\Includes\Classes\Async\Handlers;

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

use AC_SYNC\Includes\Classes\Async\Action_Wear_Job_Handler_Interface;
use AC_SYNC\Includes\Classes\Async\Action_Wear_Job_Result as JobResult;
use AC_SYNC\Includes\Classes\Async\Action_Wear_Job_Queue as JobQueue;
use AC_SYNC\Includes\Classes\Logger\Action_Wear_Log as Log;

class Action_Wear_Bulk_Quantity_Batch_Handler implements Action_Wear_Job_Handler_Interface
{
    public function handle(object $job, array $payload): JobResult
    {
        global $wpdb;

        $batch = $payload['items'] ?? [];
        if (empty($batch)) {
            return JobResult::success();
        }

        // 1. Collect all SKUs from the batch
        $skuStockMap = [];
        foreach ($batch as $stockItem) {
            $sku = $stockItem['sku'] ?? null;
            if ($sku) {
                $skuStockMap[$sku] = $stockItem;
            }
        }

        if (empty($skuStockMap)) {
            return JobResult::success();
        }

        $allSkus = array_keys($skuStockMap);
        $placeholders = implode(',', array_fill(0, count($allSkus), '%s'));

        // 2. Batch SKU -> post_id lookup
        $skuToPostId = [];
        $results = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT pm.meta_value AS sku, pm.post_id
                FROM {$wpdb->postmeta} pm
                INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
                WHERE pm.meta_key = '_sku'
                AND p.post_type = 'product_variation'
                AND pm.meta_value IN ($placeholders)",
                ...$allSkus
            )
        );
        foreach ($results as $row) {
            $skuToPostId[$row->sku] = (int) $row->post_id;
        }

        if (empty($skuToPostId)) {
            return JobResult::success();
        }

        // 3. Process each item
        $updatedIds = [];
        $stockData = [];
        foreach ($skuToPostId as $sku => $postId) {
            try {
                $stockItem = $skuStockMap[$sku];
                $available = isset($stockItem['available']) ? (int) $stockItem['available'] : 0;
                $totalArrivals = isset($stockItem['total_arrivals']) ? (float) $stockItem['total_arrivals'] : 0;
                $supplier1 = isset($stockItem['supplier_1']) ? (float) $stockItem['supplier_1'] : 0;
                $supplier2 = isset($stockItem['supplier_2']) ? (float) $stockItem['supplier_2'] : 0;

                update_post_meta($postId, '_manage_stock', 'yes');
                update_post_meta($postId, '_stock', $available);
                update_post_meta($postId, '_stock_status', $available > 0 ? 'instock' : 'outofstock');

                update_post_meta($postId, 'total_arrivals', $totalArrivals);
                update_post_meta($postId, 'quantity_supplier', $supplier1 + $supplier2);
                update_post_meta($postId, 'supplier_1', $supplier1);
                update_post_meta($postId, 'supplier_2', $supplier2);

                delete_post_meta($postId, '_needs_quantity_sync');
                $updatedIds[] = $postId;
                $stockData[$postId] = $available;
            } catch (\Throwable $e) {
                Log::write("BulkQuantityBatch: Error processing SKU {$sku}: " . $e->getMessage(), Log::ERROR, Log::CONTEXT_CRONJOB);
            }
        }

        // 4. Update wc_product_meta_lookup + sync parent stock status
        if (!empty($updatedIds)) {
            $lookupTable = $wpdb->prefix . 'wc_product_meta_lookup';
            foreach ($updatedIds as $postId) {
                $available = $stockData[$postId];
                $wpdb->update(
                    $lookupTable,
                    [
                        'stock_quantity' => $available,
                        'stock_status' => $available > 0 ? 'instock' : 'outofstock',
                    ],
                    ['product_id' => $postId],
                    ['%d', '%s'],
                    ['%d']
                );
            }

            $parentIds = [];
            foreach ($updatedIds as $variationId) {
                $parentId = wp_get_post_parent_id($variationId);
                if ($parentId) {
                    $parentIds[$parentId] = true;
                }
            }

            foreach (array_keys($parentIds) as $parentId) {
                $parentProduct = wc_get_product($parentId);
                if ($parentProduct && $parentProduct->is_type('variable')) {
                    $parentProduct->save();
                }
            }

            foreach ($updatedIds as $id) {
                wc_delete_product_transients($id);
            }
        }

        // On final batch, update timestamp
        if (!JobQueue::hasPending('bulk_quantity_batch')) {
            update_option('_ACTIONWEAR_LAST_BULK_QUANTITY_SYNC_COMPLETED', time());
            Log::write("BulkQuantityBatch: All batches completed", Log::INFO, Log::CONTEXT_CRONJOB);
        }

        return JobResult::success();
    }
}
