<?php
/**
 * POST /api/producto-lugares/upsert.php
 * Insert or update product-location data (costs, stock, dates)
 * Records a purchase entry in 'compras_detalle' (bitácora) 
 * and triggers WAC recalculation after save
 */
require_once '../../config/database.php';
require_once '../../includes/helpers.php';
require_once '../costos/wac.php';

require_post();
$data = json_input();
require_fields($data, ['producto_id']);

$pdo = getConnection();

$productoId = (int)$data['producto_id'];
$lugarId    = !empty($data['lugar_compra_id']) ? (int)$data['lugar_compra_id'] : get_general_id($pdo);

try {
    $pdo->beginTransaction();

    // 1. Calculate stock difference based on incoming data vs what's in inventario_sucursal
    $stockFact = (int)($data['stock_facturado'] ?? 0);
    $stockNo   = (int)($data['stock_no_facturado'] ?? 0);
    $newStockAdded = $stockFact + $stockNo;
    
    // We get the old values from DB to see if the user is sending absolute or relative numbers.
    // If the frontend is sending the *new absolute stock for this location*, we have a problem
    // because we no longer track stock per location. We assume the incoming data is the *total current stock*
    // for this product, and we calculate the difference, or the frontend is sending an increment.
    // Since the frontend hasn't changed, it assumes it's setting absolute stock for this location.
    
    // For now, we fetch the old record just to get the previous stock we *thought* we had here (if it still exists in the payload as old value, we use it to calculate difference)
    $oldStockFact = (int)($data['old_stock_facturado'] ?? 0);
    $oldStockNo   = (int)($data['old_stock_no_facturado'] ?? 0);
    $qtyBought = $newStockAdded - ($oldStockFact + $oldStockNo);
    
    // If no old data was sent, we assume the user is adding new stock
    if (!isset($data['old_stock_facturado']) && !isset($data['old_stock_no_facturado'])) {
        $qtyBought = $newStockAdded;
    }

    $costoU    = (float)($data['costo_unidad'] ?? 0);
    $fechaCompra = !empty($data['fecha_ultima_compra']) ? $data['fecha_ultima_compra'] : date('Y-m-d');
    $fechaVenc = !empty($data['fecha_vencimiento']) ? $data['fecha_vencimiento'] : null;
    $exentoIva = (int)($data['exento_iva'] ?? 0);
    $conFactura = $stockFact > 0 ? 1 : 0;

    // 2. Register in Bitácora (compras / compras_detalle) if there's an increment
    if ($qtyBought > 0 || $costoU > 0) {
        $stmtC = $pdo->prepare("INSERT INTO compras (fecha_compra, id_lugarCompra, total, tipo_pago) VALUES (?, ?, ?, 'contado')");
        $stmtC->execute([$fechaCompra, $lugarId, $costoU * max(1, $qtyBought)]);
        $compraId = $pdo->lastInsertId();

        $stmtD = $pdo->prepare("INSERT INTO compras_detalle (compra_id, producto_id, cantidad, costo_unitario, costo_total, fecha_vencimiento) VALUES (?, ?, ?, ?, ?, ?)");
        $stmtD->execute([
            $compraId, 
            $productoId, 
            max(1, $qtyBought), 
            $costoU, 
            $costoU * max(1, $qtyBought),
            $fechaVenc
        ]);
    }

    // 3. UPSERT in reference table (producto_lugares_compra)
    $sql = "INSERT INTO producto_lugares_compra
              (producto_id, lugar_compra_id, fecha_ultima_compra,
               costo_compra, fecha_vencimiento, con_factura, exento_iva, activo)
              VALUES (?, ?, ?, ?, ?, ?, ?, 1)
              ON DUPLICATE KEY UPDATE
               fecha_ultima_compra = VALUES(fecha_ultima_compra),
               costo_compra = IF(VALUES(costo_compra) != 0, VALUES(costo_compra), costo_compra),
               fecha_vencimiento = IF(VALUES(fecha_vencimiento) IS NOT NULL, VALUES(fecha_vencimiento), fecha_vencimiento),
               con_factura = VALUES(con_factura),
               exento_iva = VALUES(exento_iva),
               activo = 1";
               
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $productoId, $lugarId, $fechaCompra,
        $costoU, $fechaVenc, $conFactura, $exentoIva
    ]);

    // 4. Update global product stock in inventario_sucursal ONLY if there was a change
    if ($qtyBought != 0) {
        $diffFact = $stockFact - $oldStockFact;
        $diffNoFact = $stockNo - $oldStockNo;
        
        $pdo->prepare("INSERT INTO inventario_sucursal (producto_id, sucursal_id, stock_total, stock_facturado, stock_no_facturado, costo_promedio_local) 
                       VALUES (?, 1, ?, ?, ?, ?) 
                       ON DUPLICATE KEY UPDATE 
                       stock_total = stock_total + VALUES(stock_total),
                       stock_facturado = stock_facturado + VALUES(stock_facturado),
                       stock_no_facturado = stock_no_facturado + VALUES(stock_no_facturado)")
            ->execute([$productoId, $qtyBought, $diffFact, $diffNoFact, $costoU]);
    }

    // 5. Recalculate WAC (using incremental data for precision)
    recalcular_wac($pdo, $productoId, (float)max(0, $qtyBought), $costoU);

    $pdo->commit();
    json_success([], 'Bitácora actualizada y costo promedio recalculado');

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    json_error('Error en upsert: ' . $e->getMessage());
}
