<?php
header('Content-Type: application/json');

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../../includes/session_control.php';
require_once __DIR__ . '/../../cotizaciones/api/_node.php';
require_once __DIR__ . '/../../includes/user_activity_log.php';

$action = (string)($_REQUEST['action'] ?? '');
// provider: 'marpico' | 'proplasticos' | 'stocksur' | 'botonpromo' | 'promoopcion'
$provider = (string)($_REQUEST['provider'] ?? 'marpico');

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

function bad($msg)
{
    echo json_encode(['ok' => false, 'error' => ['message' => $msg]]);
    exit;
}

function bad_node($defaultMsg, $nodeResp)
{
    $msg = $defaultMsg;
    if (is_array($nodeResp) && isset($nodeResp['error']['message']) && is_string($nodeResp['error']['message'])) {
        $msg = $nodeResp['error']['message'];
    }
    $err = ['message' => $msg];
    if (is_array($nodeResp)) {
        if (isset($nodeResp['_http'])) $err['http'] = $nodeResp['_http'];
        if (isset($nodeResp['error']['raw'])) $err['raw'] = $nodeResp['error']['raw'];
        if (isset($nodeResp['error'])) $err['nodeError'] = $nodeResp['error'];
    }
    echo json_encode(['ok' => false, 'error' => $err]);
    exit;
}

function provider_paths($provider)
{
    $p = strtolower(trim((string)$provider));
    if ($p === 'promoopcion') {
        return [
            'status' => '/api/integrations/promoopcion/status',
            'progress' => '/api/integrations/promoopcion/progress',
            'run' => '/api/integrations/promoopcion/sync?async=1',
        ];
    }
    if ($p === 'proplasticos') {
        return [
            'status' => '/api/integrations/proplasticos/status',
            'progress' => '/api/integrations/proplasticos/progress',
            'run' => '/api/integrations/proplasticos/sync?async=1',
        ];
    }
    if ($p === 'botonpromo') {
        return [
            'status' => '/api/integrations/botonpromo/status',
            'progress' => '/api/integrations/botonpromo/progress',
            'run' => '/api/integrations/botonpromo/sync?async=1',
        ];
    }
    if ($p === 'stocksur') {
        return [
            'status' => '/api/integrations/stocksur/status',
            'progress' => '/api/integrations/stocksur/progress',
            'run' => '/api/integrations/stocksur/sync?async=1',
        ];
    }

    return [
        'status' => '/api/integrations/marpico/status',
        'progress' => '/api/integrations/marpico/progress',
        'run' => '/api/integrations/marpico/sync?async=1',
    ];
}

function provider_id($provider)
{
    $p = strtolower(trim((string)$provider));
    if ($p === 'marpico') return 1;
    if ($p === 'proplasticos') return 2;
    if ($p === 'stocksur') return 3;
    if ($p === 'botonpromo') return 4;
    if ($p === 'promoopcion') return 5;
    return 0;
}

$paths = provider_paths($provider);

// --- Proveedor estado (activo/inactivo) ---
if ($action === 'provider_list') {
    $r = cpn_node_request('GET', $base . '/api/integrations/proveedores', $token);
    if (empty($r['ok'])) {
        bad_node('Error consultando proveedores en Node', $r);
    }
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? []]);
    exit;
}

if ($action === 'provider_set_estado') {
    $idProveedor = (int)($_REQUEST['idProveedor'] ?? 0);
    $idEstado = (int)($_REQUEST['idEstado'] ?? 0);
    if ($idProveedor <= 0) bad('idProveedor inválido');
    if ($idEstado !== 1 && $idEstado !== 2) bad('idEstado inválido');

    $url = $base . '/api/integrations/proveedores/' . urlencode((string)$idProveedor) . '/estado';
    $r = cpn_node_request('POST', $url, $token, ['idEstado' => $idEstado]);
    if (empty($r['ok'])) {
        bad_node('Error actualizando estado del proveedor en Node', $r);
    }

    cpn_activity_log_event(
        'Inventario',
        'inventario.proveedor_estado_set',
        'Actualizó estado de proveedor (idProveedor #' . $idProveedor . ')',
        'proveedor',
        $idProveedor,
        ['idEstado' => $idEstado]
    );
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

// --- Sync ---
if ($action === 'status') {
    $r = cpn_node_request('GET', $base . $paths['status'], $token);
    if (empty($r['ok'])) {
        bad_node('Error consultando estado en Node', $r);
    }
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'progress') {
    $r = cpn_node_request('GET', $base . $paths['progress'], $token);
    if (empty($r['ok'])) {
        bad_node('Error consultando progreso en Node', $r);
    }
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'run') {
    $r = cpn_node_request('POST', $base . $paths['run'], $token, []);
    if (empty($r['ok'])) {
        bad_node('Error ejecutando sync en Node', $r);
    }

    cpn_activity_log_event(
        'Inventario',
        'inventario.sync_run',
        'Ejecutó sync de inventario (' . $provider . ')',
        'integracion',
        null,
        ['provider' => $provider]
    );
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

// --- Woo sync (stock + prices) ---
if ($action === 'woo_sync') {
    $idProv = provider_id($provider);
    if (!$idProv) bad('Proveedor inválido');

    // async=1 to avoid proxy timeouts; use woo_sync_progress to poll
    $url = $base . '/api/woocommerce/sync/proveedor/' . urlencode((string)$idProv) . '?async=1';
    $r = cpn_node_request('POST', $url, $token, []);
    if (empty($r['ok'])) {
        bad_node('Error sincronizando con WooCommerce en Node', $r);
    }

    cpn_activity_log_event(
        'Inventario',
        'inventario.woo_sync',
        'Ejecutó Woo sync (' . $provider . ')',
        'proveedor',
        $idProv,
        ['provider' => $provider]
    );
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'woo_sync_progress') {
    $idProv = provider_id($provider);
    if (!$idProv) bad('Proveedor inválido');

    $r = cpn_node_request('GET', $base . '/api/woocommerce/sync/proveedor/' . urlencode((string)$idProv) . '/progress', $token);
    if (empty($r['ok'])) {
        bad_node('Error consultando progreso Woo sync en Node', $r);
    }

    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

// --- Woo audit ---
if ($action === 'woo_audit') {
    $idProv = provider_id($provider);
    if (!$idProv) bad('Proveedor inválido');

    $maxParents = (int)($_REQUEST['maxParents'] ?? 0);
    $url = $base . '/api/woocommerce/audit/proveedor/' . urlencode((string)$idProv);
    if ($maxParents > 0) {
        $url .= '?maxParents=' . urlencode((string)$maxParents);
    }

    // Also repair stale mappings in Compranet DB where possible
    $url .= (strpos($url, '?') === false ? '?' : '&') . 'fixMappings=1';

    // async=1 to avoid proxy timeouts; use woo_audit_progress to poll
    $url .= (strpos($url, '?') === false ? '?' : '&') . 'async=1';
    $r = cpn_node_request('POST', $url, $token, []);
    if (empty($r['ok'])) {
        bad_node('Error auditando WooCommerce en Node', $r);
    }

    cpn_activity_log_event(
        'Inventario',
        'inventario.woo_audit',
        'Ejecutó Woo audit (' . $provider . ')',
        'proveedor',
        $idProv,
        ['provider' => $provider, 'fixMappings' => 1]
    );
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'woo_audit_progress') {
    $idProv = provider_id($provider);
    if (!$idProv) bad('Proveedor inválido');

    $r = cpn_node_request('GET', $base . '/api/woocommerce/audit/proveedor/' . urlencode((string)$idProv) . '/progress', $token);
    if (empty($r['ok'])) {
        bad_node('Error consultando progreso auditoría WooCommerce en Node', $r);
    }

    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

// --- Woo cleanup (trash duplicates) ---
if ($action === 'woo_cleanup') {
    $idProv = provider_id($provider);
    if (!$idProv) bad('Proveedor inválido');

    $confirm = (string)($_REQUEST['confirm'] ?? '');
    $maxActions = (int)($_REQUEST['maxActions'] ?? 0);

    $qs = [];
    if ($confirm !== '') $qs[] = 'confirm=' . urlencode($confirm);
    if ($maxActions > 0) $qs[] = 'maxActions=' . urlencode((string)$maxActions);
    $qs[] = 'fixMappings=1';
    $url = $base . '/api/woocommerce/cleanup/proveedor/' . urlencode((string)$idProv) . (count($qs) ? ('?' . implode('&', $qs)) : '');

    // async=1 to avoid proxy timeouts; use woo_cleanup_progress to poll
    $url .= (strpos($url, '?') === false ? '?' : '&') . 'async=1';
    $r = cpn_node_request('POST', $url, $token, []);
    if (empty($r['ok'])) {
        bad_node('Error limpiando WooCommerce en Node', $r);
    }

    cpn_activity_log_event(
        'Inventario',
        'inventario.woo_cleanup',
        'Ejecutó Woo cleanup (' . $provider . ')',
        'proveedor',
        $idProv,
        ['provider' => $provider]
    );
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'woo_cleanup_progress') {
    $idProv = provider_id($provider);
    if (!$idProv) bad('Proveedor inválido');

    $r = cpn_node_request('GET', $base . '/api/woocommerce/cleanup/proveedor/' . urlencode((string)$idProv) . '/progress', $token);
    if (empty($r['ok'])) {
        bad_node('Error consultando progreso limpieza WooCommerce en Node', $r);
    }

    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

// --- Woo audit GLOBAL ---
if ($action === 'woo_audit_global') {
    $maxProducts = (int)($_REQUEST['maxProducts'] ?? 0);
    $url = $base . '/api/woocommerce/audit/global';
    $qs = [];
    if ($maxProducts > 0) $qs[] = 'maxProducts=' . urlencode((string)$maxProducts);
    $qs[] = 'async=1';
    $url .= '?' . implode('&', $qs);

    $r = cpn_node_request('POST', $url, $token, []);
    if (empty($r['ok'])) {
        bad_node('Error auditando WooCommerce global en Node', $r);
    }

    cpn_activity_log_event(
        'Inventario',
        'inventario.woo_audit_global',
        'Ejecutó Woo audit global',
        'integracion',
        null,
        ['maxProducts' => $maxProducts]
    );
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'woo_audit_global_progress') {
    $r = cpn_node_request('GET', $base . '/api/woocommerce/audit/global/progress', $token);
    if (empty($r['ok'])) {
        bad_node('Error consultando progreso auditoría global WooCommerce en Node', $r);
    }

    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

// --- Woo cleanup GLOBAL ---
if ($action === 'woo_cleanup_global') {
    $confirm = (string)($_REQUEST['confirm'] ?? '');
    $maxActions = (int)($_REQUEST['maxActions'] ?? 0);
    $maxProducts = (int)($_REQUEST['maxProducts'] ?? 0);

    $qs = ['async=1'];
    if ($confirm !== '') $qs[] = 'confirm=' . urlencode($confirm);
    if ($maxActions > 0) $qs[] = 'maxActions=' . urlencode((string)$maxActions);
    if ($maxProducts > 0) $qs[] = 'maxProducts=' . urlencode((string)$maxProducts);

    $url = $base . '/api/woocommerce/cleanup/global?' . implode('&', $qs);
    $r = cpn_node_request('POST', $url, $token, []);
    if (empty($r['ok'])) {
        bad_node('Error limpiando WooCommerce global en Node', $r);
    }

    cpn_activity_log_event(
        'Inventario',
        'inventario.woo_cleanup_global',
        'Ejecutó Woo cleanup global',
        'integracion',
        null,
        ['maxActions' => $maxActions, 'maxProducts' => $maxProducts]
    );
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'woo_cleanup_global_progress') {
    $r = cpn_node_request('GET', $base . '/api/woocommerce/cleanup/global/progress', $token);
    if (empty($r['ok'])) {
        bad_node('Error consultando progreso limpieza global WooCommerce en Node', $r);
    }

    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

// --- Woo sync GLOBAL (stock + prices + parents reconciliation) ---
if ($action === 'woo_sync_global') {
    $fullRaw = strtolower(trim((string)($_REQUEST['full'] ?? '1')));
    $full = ($fullRaw === '1' || $fullRaw === 'true' || $fullRaw === 'yes');

    $syncImagesRaw = strtolower(trim((string)($_REQUEST['syncImages'] ?? '0')));
    $syncImages = ($syncImagesRaw === '1' || $syncImagesRaw === 'true' || $syncImagesRaw === 'yes');

    $qs = ['async=1'];
    if ($full) {
        $qs[] = 'full=1';
        $qs[] = 'syncImages=' . ($syncImages ? '1' : '0');
    }

    $url = $base . '/api/woocommerce/sync/global?' . implode('&', $qs);
    $r = cpn_node_request('POST', $url, $token, []);
    if (empty($r['ok'])) {
        bad_node('Error sincronizando WooCommerce global en Node', $r);
    }

    cpn_activity_log_event(
        'Inventario',
        'inventario.woo_sync_global',
        'Ejecutó Woo sync global',
        'integracion',
        null,
        ['full' => $full ? 1 : 0, 'syncImages' => $syncImages ? 1 : 0]
    );
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'woo_sync_global_progress') {
    $r = cpn_node_request('GET', $base . '/api/woocommerce/sync/global/progress', $token);
    if (empty($r['ok'])) {
        bad_node('Error consultando progreso sync global WooCommerce en Node', $r);
    }

    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

// --- Woo images sync GLOBAL (external attachments via WP API) ---
if ($action === 'woo_images_sync_global') {
    $maxProducts = (int)($_REQUEST['maxProducts'] ?? 0);

    $qs = ['async=1'];
    if ($maxProducts > 0) $qs[] = 'maxProducts=' . urlencode((string)$maxProducts);

    $url = $base . '/api/woocommerce/images/sync/global?' . implode('&', $qs);
    $r = cpn_node_request('POST', $url, $token, []);
    if (empty($r['ok'])) {
        bad_node('Error sincronizando imágenes global en Node', $r);
    }

    cpn_activity_log_event(
        'Inventario',
        'inventario.woo_images_sync_global',
        'Ejecutó sync global de imágenes Woo',
        'integracion',
        null,
        ['maxProducts' => $maxProducts]
    );
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'woo_images_sync_global_progress') {
    $r = cpn_node_request('GET', $base . '/api/woocommerce/images/sync/global/progress', $token);
    if (empty($r['ok'])) {
        bad_node('Error consultando progreso imágenes global WooCommerce en Node', $r);
    }

    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

// --- Scheduler CRUD ---
if ($action === 'schedule_list') {
    $r = cpn_node_request('GET', $base . '/api/integrations/inventarios/scheduler', $token);
    if (empty($r['ok'])) {
        $msg = $r['error']['message'] ?? 'Error consultando scheduler en Node';
        bad($msg);
    }
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? []]);
    exit;
}

if ($action === 'schedule_save') {
    // Expect fields: id (optional), idProveedor, nombreProceso, activo(0/1), horaInicio(HH:MM), horaFin(HH:MM), frecuenciaMin
    $payload = [
        'idProveedor' => $_POST['idProveedor'] ?? null,
        'nombreProceso' => $_POST['nombreProceso'] ?? null,
        'activo' => $_POST['activo'] ?? 0,
        'horaInicio' => $_POST['horaInicio'] ?? null,
        'horaFin' => $_POST['horaFin'] ?? null,
        'frecuenciaMin' => $_POST['frecuenciaMin'] ?? null,
    ];

    $idRaw = $_POST['id'] ?? null;
    if ($idRaw !== null && $idRaw !== '') {
        $payload['id'] = $idRaw;
    }

    $r = cpn_node_request('POST', $base . '/api/integrations/inventarios/scheduler', $token, $payload);
    if (empty($r['ok'])) {
        $msg = $r['error']['message'] ?? 'Error guardando scheduler en Node';
        echo json_encode(['ok' => false, 'error' => ['message' => $msg, 'details' => $r['error']['details'] ?? null]]);
        exit;
    }

    cpn_activity_log_event(
        'Inventario',
        'inventario.scheduler_save',
        'Guardó programación de inventarios',
        'scheduler',
        isset($payload['id']) ? (int)$payload['id'] : null,
        ['idProveedor' => $payload['idProveedor'] ?? null, 'activo' => $payload['activo'] ?? 0]
    );
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'schedule_delete') {
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) bad('ID inválido');

    $r = cpn_node_request('DELETE', $base . '/api/integrations/inventarios/scheduler/' . urlencode((string)$id), $token, null);
    if (empty($r['ok'])) {
        $msg = $r['error']['message'] ?? 'Error eliminando scheduler en Node';
        bad($msg);
    }

    cpn_activity_log_event(
        'Inventario',
        'inventario.scheduler_delete',
        'Eliminó programación de inventarios #' . $id,
        'scheduler',
        $id
    );
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

// --- Historial de ejecuciones (tb_importaciones_proveedores) ---
if ($action === 'history_list') {
    $limit = (int)($_REQUEST['limit'] ?? 50);
    if ($limit <= 0) $limit = 50;
    if ($limit > 200) $limit = 200;

    $idProveedor = (int)($_REQUEST['idProveedor'] ?? 0);

    $qs = ['limit=' . urlencode((string)$limit)];
    if ($idProveedor > 0) $qs[] = 'idProveedor=' . urlencode((string)$idProveedor);

    $url = $base . '/api/integrations/importaciones/historial?' . implode('&', $qs);
    $r = cpn_node_request('GET', $url, $token);
    if (empty($r['ok'])) {
        bad_node('Error consultando historial en Node', $r);
    }
    echo json_encode(['ok' => true, 'data' => $r['data'] ?? null]);
    exit;
}

bad('Acción no válida');
