<?php
/**
 * ICYLAB OS - Actualizar Producto (Push a FACTO)
 */
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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') die('Método no permitido.');

$pdo = db();

function product_update_clean_unit($unit)
{
    $allowed = array('unidad', 'mL', 'L', 'g', 'kg', 'pack', 'caja', 'servicio');
    $unit = trim((string)$unit);
    return in_array($unit, $allowed, true) ? $unit : 'unidad';
}

$id = (int)($_POST['id'] ?? 0);
$name = trim($_POST['name'] ?? '');
$sku = trim($_POST['sku'] ?? '');
$category_id = isset($_POST['category_id']) && $_POST['category_id'] !== '' ? (int)$_POST['category_id'] : null;
$price = (float)($_POST['price'] ?? 0.0);
$stock = (float)($_POST['stock'] ?? 0.0);
$unit = product_update_clean_unit($_POST['unit'] ?? 'unidad');
$is_active = (int)($_POST['is_active'] ?? 1);
$description = trim($_POST['description'] ?? '');
$cost = (float)($_POST['cost'] ?? 0.0);

$errors = array();
if ($id <= 0) die('ID inválido.');
if ($name === '') $errors['name'] = 'El nombre es obligatorio.';
if ($price < 0) $errors['price'] = 'El precio no puede ser negativo.';

if (!empty($errors)) {
    $_SESSION['form_errors'] = $errors;
    $_SESSION['form_old'] = $_POST;
    header("Location: /modules/products/product_edit.php?id=$id");
    exit;
}

try {
    // 1. Obtener ID original de FACTO (Si existe)
    $stmtOld = $pdo->prepare("SELECT facto_id FROM products WHERE id = ?");
    $stmtOld->execute([$id]);
    $factoId = $stmtOld->fetchColumn();

    // 2. Actualizar Maestro Local
    $stmt = $pdo->prepare("UPDATE products SET category_id = ?, name = ?, sku = ?, price = ?, cost = ?, stock = ?, unit = ?, is_active = ?, description = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$category_id, $name, $sku, $price, $cost, $stock, $unit, $is_active, $description, $id]);

    // 3. Empujar a FACTO (Koywe restringe la edición vía PUT solo a Name y SKU)
    if ($factoId) {
        try {
            $facto = new FactoService();
            $facto->updateProduct($factoId, ['name' => $name, 'sku' => $sku]);
        } catch (Exception $e) {
            // Ignorar y preservar en el maestro local
        }
    }

    header('Location: /modules/products/index.php');
    exit;

} catch (Throwable $e) {
    die("Error crítico al actualizar: " . $e->getMessage());
}