<?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['laboratorio']) || !isset($data['margen'])) {
    echo json_encode(['success' => false, 'message' => 'Datos incompletos']);
    exit;
}

try {
    $pdo->beginTransaction();
    $laboratorio = trim($data['laboratorio']);
    $margen = round((float)$data['margen'], 2);
    $updated = 0;

    // Get all products from this lab
    $stmtProds = $pdo->prepare("SELECT p.id, IFNULL(cpp.costo_promedio_unidad_base, 0) as cpp
        FROM productos p
        LEFT JOIN productos_costo_promedio cpp ON cpp.producto_id = p.id
        WHERE p.laboratorio = ?");
    $stmtProds->execute([$laboratorio]);
    $products = $stmtProds->fetchAll(PDO::FETCH_ASSOC);

    foreach ($products as $prod) {
        $cpp = (float)$prod['cpp'];
        if ($cpp <= 0) continue;

        // Update all active presentations for this product
        $stmtPres = $pdo->prepare("SELECT presentacion_id, factor_conversion FROM producto_presentaciones WHERE producto_id = ? AND activo = 1");
        $stmtPres->execute([$prod['id']]);
        $presentaciones = $stmtPres->fetchAll(PDO::FETCH_ASSOC);

        foreach ($presentaciones as $pres) {
            $costo_pres = $cpp * $pres['factor_conversion'];
            $nuevo_precio = round($costo_pres * (1 + ($margen / 100)), 2);

            $pdo->prepare("UPDATE producto_presentaciones 
                SET precio_venta = ?
                WHERE producto_id = ? AND presentacion_id = ?")
                ->execute([$nuevo_precio, $prod['id'], $pres['presentacion_id']]);
        }
        $updated++;
    }

    $pdo->commit();
    echo json_encode([
        'success' => true, 
        'message' => "Margen de $margen% aplicado a $updated productos del laboratorio '$laboratorio'"
    ]);
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
