<?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
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();
    header('Content-Type: application/json');
    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();
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}