<?php
/**
 * ICYLAB OS - Motor de Importación desde FACTO (Solo Nuevos)
 */

ob_start();
set_time_limit(180); 

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../services/crm/FactoService.php';
require_once '../../core/permissions.php'; // Agrega esto en los require

require_login();
require_permission('module.products'); // Agrega este candado

header('Content-Type: application/json; charset=utf-8');
if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    ob_end_clean();
    http_response_code(405);
    header('Allow: POST');
    echo json_encode(['success' => false, 'message' => 'Método no permitido.']);
    exit;
}
csrf_require_valid_request();

try {
    $facto = new FactoService();
    $pdo = db();
    $pdo->beginTransaction();

    // 1. Sincronizar Categorías
    $factoCategories = $facto->getCategories();
    $stmtCatCheck = $pdo->prepare("SELECT id FROM product_categories WHERE facto_id = ?");
    $stmtCatInsert = $pdo->prepare("INSERT INTO product_categories (facto_id, name) VALUES (?, ?)");
    $stmtCatUpdate = $pdo->prepare("UPDATE product_categories SET name = ? WHERE facto_id = ?");

    foreach ($factoCategories as $cat) {
        $catId = $cat['product_category_id'] ?? null;
        if (!$catId) continue;
        
        $stmtCatCheck->execute([$catId]);
        if ($stmtCatCheck->fetchColumn()) {
            $stmtCatUpdate->execute([$cat['name'], $catId]);
        } else {
            $stmtCatInsert->execute([$catId, $cat['name']]);
        }
    }

    // 2. Importar Productos Nuevos
    $factoProducts = $facto->getProducts(); 
    $inserted = 0;

    $stmtProdCheck = $pdo->prepare("SELECT id FROM products WHERE facto_id = ? LIMIT 1");
    $stmtGetLocalCat = $pdo->prepare("SELECT id FROM product_categories WHERE facto_id = ? LIMIT 1");
    $stmtProdInsert = $pdo->prepare("
        INSERT INTO products (facto_id, category_id, name, sku, description, price, stock, is_active) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");

    foreach ($factoProducts as $prod) {
        $factoId = $prod['product_id'] ?? null;
        if (empty($factoId)) continue;

        // Si ya existe localmente, NO LO TOCAMOS (ICYLAB es el master)
        $stmtProdCheck->execute([$factoId]);
        if ($stmtProdCheck->fetchColumn()) continue;

        $details = $facto->getProductDetails($factoId);
        $name = $prod['name'] ?? 'Sin nombre';
        $sku = $prod['sku'] ?? null;
        $isActive = isset($prod['status']) ? (int)$prod['status'] : 1;
        $factoCatId = $prod['product_category_id'] ?? null;
        
        $localCatId = null;
        if ($factoCatId) {
            $stmtGetLocalCat->execute([$factoCatId]);
            $localCatId = $stmtGetLocalCat->fetchColumn() ?: null;
        }

        $price = 0.0; $stock = 0.0; $desc = null;
        if ($details) {
            $desc = $details['additional_details'] ?? null;
            if (isset($details['price'][0]['unit_net'])) $price = (float)$details['price'][0]['unit_net'];
            if (isset($details['inventories']['details'][0]['available_quantity'])) $stock = (float)$details['inventories']['details'][0]['available_quantity'];
        }

        $stmtProdInsert->execute([$factoId, $localCatId, $name, $sku, $desc, $price, $stock, $isActive]);
        $inserted++;
    }

    $pdo->commit();

    ob_end_clean();
    echo json_encode([
        'success' => true,
        'message' => "Categorías actualizadas. Se importaron $inserted productos nuevos."
    ]);

} catch (Throwable $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    ob_end_clean();
    error_log('ICYLAB product_sync failed: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'No fue posible importar el catálogo desde FACTO.']);
}
