<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';
$pdo = getDBConnection();

$data = json_decode(file_get_contents('php://input'), true);

if (!$data || (!isset($data['updates']) && !isset($data['total_update']))) {
    echo json_encode(['success' => false, 'message' => 'Datos incompletos']);
    exit;
}

try {
    $pdo->beginTransaction();

    // STEP 1: Actualizar Total de Ingreso (Bodega Central)
    if (isset($data['total_update'])) {
        $ingreso_id = $data['total_update']['ingreso_id'] ?? null;
        $new_total = (int)$data['total_update']['cantidad'];
        $sefactura = (int)($data['total_update']['sefactura'] ?? 1);

        // Buscar el ingreso por ingreso_id o por producto_id+fecha
        $curr = null;
        if ($ingreso_id) {
            $stmtCurr = $pdo->prepare("SELECT id, cantidad_ingresada, producto_id, presentacion_id 
                                        FROM ingresos_sucursal WHERE id = ? AND sucursal_id = 1");
            $stmtCurr->execute([$ingreso_id]);
            $curr = $stmtCurr->fetch(PDO::FETCH_ASSOC);
        }

        if ($curr) {
            $old_total = (int)$curr['cantidad_ingresada'];
            $producto_id = $curr['producto_id'];
            $pres_id = $curr['presentacion_id'] ?? 1;

            $stmtFactor = $pdo->prepare("SELECT factor_conversion FROM producto_presentaciones WHERE producto_id = ? AND presentacion_id = ? LIMIT 1");
            $stmtFactor->execute([$producto_id, $pres_id]);
            $fRow = $stmtFactor->fetch(PDO::FETCH_ASSOC);
            $factor = $fRow ? max(1, (int)$fRow['factor_conversion']) : 1;

            $diff = $new_total - $old_total;

            if ($diff !== 0) {
                $diff_base = $diff * $factor;
                $stockCol = ($sefactura == 1) ? 'stock_facturado' : 'stock_no_facturado';
                
                // Ajustar Bodega (inventario_sucursal)
                $pdo->prepare("UPDATE inventario_sucursal SET 
                    stock_total = GREATEST(0, CAST(stock_total AS SIGNED) + ?),
                    $stockCol = GREATEST(0, CAST($stockCol AS SIGNED) + ?)
                    WHERE producto_id = ? AND sucursal_id = 1")->execute([$diff_base, $diff_base, $producto_id]);

                // Actualizar registro de ingreso
                $pdo->prepare("UPDATE ingresos_sucursal SET 
                    cantidad_ingresada = ?, cantidad_unidades_base = ? 
                    WHERE id = ?")->execute([$new_total, $new_total * $factor, $ingreso_id]);
            }
        }
    }

    // STEP 2: Actualizar Distribución por Sucursal
    if (isset($data['updates']) && is_array($data['updates'])) {
        foreach ($data['updates'] as $upd) {
            $traslado_id = $upd['traslado_id'];
            $new_qty = (int)$upd['cantidad'];
            $sefactura = (int)($upd['sefactura'] ?? 1);

            // Buscar en detalle_traslados_v2
            $stmtOld = $pdo->prepare("SELECT dt.cantidad_unidades_base as cantidad, dt.producto_id, dt.presentacion_id, t.sucursal_destino 
                                     FROM detalle_traslados_v2 dt 
                                     JOIN traslados t ON t.id = dt.traslado_id 
                                     WHERE t.id = ? LIMIT 1");
            $stmtOld->execute([$traslado_id]);
            $old = $stmtOld->fetch(PDO::FETCH_ASSOC);

            if (!$old) continue;

            $old_qty = (int)$old['cantidad'];
            $sucursal_dest = $old['sucursal_destino'];
            $producto_id = $old['producto_id'];
            $pres_id = $old['presentacion_id'] ?? 1;

            if ($new_qty === $old_qty) continue;

            // Resolver factor
            $stmtFactor = $pdo->prepare("SELECT factor_conversion FROM producto_presentaciones 
                WHERE producto_id = ? AND presentacion_id = ? LIMIT 1");
            $stmtFactor->execute([$producto_id, $pres_id]);
            $fRow = $stmtFactor->fetch(PDO::FETCH_ASSOC);
            $factor = $fRow ? max(1, (int)$fRow['factor_conversion']) : 1;

            $diff = $new_qty - $old_qty;
            $diff_base = $diff * $factor;
            $stockCol = ($sefactura == 1) ? 'stock_facturado' : 'stock_no_facturado';

            // Ajustar Destino (inventario_sucursal)
            $sf = ($sefactura == 1) ? $diff_base : 0;
            $snf = ($sefactura == 0) ? $diff_base : 0;
            $pdo->prepare("INSERT INTO inventario_sucursal 
                (producto_id, sucursal_id, stock_total, stock_facturado, stock_no_facturado)
                VALUES (?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE 
                    stock_total = GREATEST(0, CAST(stock_total AS SIGNED) + ?),
                    $stockCol = GREATEST(0, CAST($stockCol AS SIGNED) + ?)")
                ->execute([$producto_id, $sucursal_dest, max(0, $diff_base), max(0, $sf), max(0, $snf), $diff_base, $diff_base]);

            // Ajustar Bodega (inverso)
            $pdo->prepare("UPDATE inventario_sucursal SET 
                stock_total = GREATEST(0, CAST(stock_total AS SIGNED) - ?),
                $stockCol = GREATEST(0, CAST($stockCol AS SIGNED) - ?)
                WHERE producto_id = ? AND sucursal_id = 1")->execute([$diff_base, $diff_base, $producto_id]);

            // Actualizar detalle_traslados_v2
            $pdo->prepare("UPDATE detalle_traslados_v2 SET 
                cantidad = ?, cantidad_unidades_base = ? 
                WHERE traslado_id = ? AND producto_id = ?")->execute([$new_qty, $new_qty * $factor, $traslado_id, $producto_id]);
        }
    }

    $pdo->commit();
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => 'Error DB: ' . $e->getMessage()]);
}
?>
