<?php

namespace Meliconnect\Meliconnect\Core;

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

use Meliconnect\Meliconnect\Core\Helpers\Helper;
use Meliconnect\Meliconnect\Core\Helpers\MeliconMeli;
use Meliconnect\Meliconnect\Core\Helpers\SyncHashHelper;

class SyncReconciler
{
    private $settings;
    private $log_channel = 'sync-reconciler';

    public function __construct()
    {
        $this->settings = Helper::getMeliconnectOptions('sync');
    }

    public function run()
    {
        Helper::logData('--- SyncReconciler START ---', $this->log_channel);


        if (($this->settings['meliconnect_sync_enabled'] ?? 'false') !== 'true') {
            Helper::logData('Sync not enabled', $this->log_channel);
            return;
        }

        $hours_threshold = (int) ($this->settings['meliconnect_sync_reconcile_hours'] ?? 6);
        Helper::logData("Reconcile interval configured: {$hours_threshold}", $this->log_channel);

        $this->reconcile($hours_threshold);

        Helper::logData('--- SyncReconciler END ---', $this->log_channel);
    }

    private function reconcile(int $hours_threshold)
    {
        global $wpdb;

        $table = $wpdb->prefix . 'meliconnect_sync_state';

        $cutoff = date('Y-m-d H:i:s', strtotime("-{$hours_threshold} hours"));

        $items = $wpdb->get_results($wpdb->prepare("
            SELECT *
            FROM {$table}
            WHERE meli_item_id != ''
            AND needs_sync = 0
            AND locked_at IS NULL
            AND (
                    initialized_at IS NULL
                    OR updated_at <= %s
            )
            AND sync_status IN ('pending','synced','error')
        ", $cutoff));

        foreach ($items as $item) {
            $this->evaluateItem($item);
        }
    }

    /**
     * 🧠 CORE INTELIGENTE
     */
    private function evaluateItem($item)
    {
        global $wpdb;

        if (empty($item->last_hash)) {
            Helper::logData("Skip item {$item->id} - no last_hash", $this->log_channel);
            return;
        }

        if (!empty($item->source) && $item->source === 'meli') {
            Helper::logData("Skip item {$item->id} - source=meli", $this->log_channel);
            return;
        }

        $woo = wc_get_product($item->woo_variation_id ?: $item->woo_product_id);
        if (!$woo) {
            Helper::logData("Skip item {$item->id} - woo not found", $this->log_channel);
            return;
        }

        // ===============================
        // 📊 NORMALIZACIÓN
        // ===============================
        $price_now  = number_format((float)$woo->get_price(), 2, '.', '');
        $stock_now  = (int)$woo->get_stock_quantity();
        $status_now = strtolower(trim(SyncHashHelper::mapStatus($woo->get_status())));

        $price_old  = number_format((float)$item->last_synced_price, 2, '.', '');
        $stock_old  = (int)$item->last_synced_stock;
        $status_old = strtolower(trim($item->last_synced_status));

        Helper::logData(
            "Reconcile CHECK item {$item->id}
            | PRICE {$price_old} → {$price_now}
            | STOCK {$stock_old} → {$stock_now}
            | STATUS {$status_old} → {$status_now}",
            $this->log_channel
        );

        // ===============================
        // 🧠 DETECCIÓN DE CAMBIOS
        // ===============================
        $changes = [];

        if (
            ($this->settings['meliconnect_sync_price'] ?? 'true') === 'true' &&
            $price_now !== $price_old
        ) {
            $changes['price'] = (float)$woo->get_price();
        }

        if (
            ($this->settings['meliconnect_sync_stock'] ?? 'true') === 'true' &&
            $stock_now !== $stock_old
        ) {
            $changes['stock'] = (int)$woo->get_stock_quantity();
        }

        if (
            ($this->settings['meliconnect_sync_status'] ?? 'true') === 'true' &&
            $status_now !== $status_old
        ) {
            $changes['status'] = $status_now;
        }

        if (empty($changes)) {
            Helper::logData("Reconcile → item {$item->id} NO CHANGES", $this->log_channel);
            return;
        }

        // ===============================
        // 🔐 HASH REAL (SIN changes)
        // ===============================
        $current_hash = SyncHashHelper::buildHashFromWoo(
            $woo,
            $item->sync_type ?: 'full'
        );

        Helper::logData(
            "Reconcile HASH item {$item->id} | current={$current_hash} | last={$item->last_hash}",
            $this->log_channel
        );

        if ($current_hash === $item->last_hash) {
            Helper::logData("Reconcile SKIP item {$item->id} - hash identical", $this->log_channel);
            return;
        }

        // ===============================
        // 🔀 DIRECCIÓN
        // ===============================
        $direction = $this->settings['meliconnect_sync_direction'] ?? 'woo_to_meli';

        // ===============================
        // 🔥 MERGE CON CAMBIOS EXISTENTES
        // ===============================
        $existingChanges = json_decode($item->changes, true);
        if (is_array($existingChanges)) {
            $changes = array_merge($existingChanges, $changes);
        }

        // ===============================
        // 🧠 RESOLVER TYPE
        // ===============================
        $type = match (true) {
            count($changes) === 1 && isset($changes['price'])  => 'price',
            count($changes) === 1 && isset($changes['stock'])  => 'stock',
            count($changes) === 1 && isset($changes['status']) => 'status',
            default => 'full'
        };

        // ===============================
        // 🚨 EVITAR DUPLICADO EXACTO
        // ===============================
        if ($item->needs_sync && $item->sync_type === $type) {
            Helper::logData(
                "Skip item {$item->id} type={$type} already pending",
                $this->log_channel
            );
            return;
        }

        // ===============================
        // 💾 UPDATE
        // ===============================
        $wpdb->update($wpdb->prefix . 'meliconnect_sync_state', [
            'sync_status' => 'pending',
            'needs_sync'  => 1,
            'sync_type'   => $type,
            'changes'     => wp_json_encode($changes),
            'direction'   => $direction,
            'priority'    => SyncHashHelper::resolvePriority($type),
            'updated_at'  => current_time('mysql')
        ], ['id' => $item->id]);

        Helper::logData(
            "Reconcile ENQUEUE item {$item->id} | type={$type} | changes=" . json_encode($changes),
            $this->log_channel
        );
    }



    
}
