<?php
/**
 * POST /api/presentaciones/actualizar.php
 * Toggle product presentation and update conversion factor
 */
require_once '../../config/database.php';
require_once '../../includes/helpers.php';

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

$pdo = getConnection();

$productoId = (int)$data['producto_id'];
$presName   = strtolower(trim($data['presentacion']));

// Map names to presentation IDs
$presIds = ['unidad' => 1, 'blister' => 2, 'caja' => 3, 'mayor' => 3, 'mixto' => 4];
$presId = $presIds[$presName] ?? null;
if (!$presId) {
    json_error("Presentación no válida: $presName", 400);
}

try {
    $fields = ['producto_id', 'presentacion_id'];
    $vals = [$productoId, $presId];
    $placeholders = ['?', '?'];
    $updates = [];

    if (isset($data['activo'])) {
        $fields[] = 'activo';
        $vals[] = $data['activo'] ? 1 : 0;
        $placeholders[] = '?';
        $updates[] = 'activo = VALUES(activo)';
    }
    if (isset($data['factor'])) {
        $fields[] = 'factor_conversion';
        $vals[] = (float)$data['factor'];
        $placeholders[] = '?';
        $updates[] = 'factor_conversion = VALUES(factor_conversion)';
    }
    if (isset($data['es_facturable'])) {
        $fields[] = 'es_facturable';
        $vals[] = $data['es_facturable'] ? 1 : 0;
        $placeholders[] = '?';
        $updates[] = 'es_facturable = VALUES(es_facturable)';
    }

    if (empty($updates)) {
        json_error("No hay campos para actualizar", 400);
    }

    $fieldsStr = implode(', ', $fields);
    $placeholdersStr = implode(', ', $placeholders);
    $updatesStr = implode(', ', $updates);

    $sql = "INSERT INTO producto_presentaciones ($fieldsStr) VALUES ($placeholdersStr) 
            ON DUPLICATE KEY UPDATE $updatesStr";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($vals);

    // Since we no longer use `presentaciones_venta` in `productos`, we can just fetch the active ones
    $stmt = $pdo->prepare("SELECT pp.presentacion_id, p.nombre FROM producto_presentaciones pp JOIN presentaciones p ON pp.presentacion_id = p.id WHERE pp.producto_id = ? AND pp.activo = 1");
    $stmt->execute([$productoId]);
    $ventas = [];
    while ($row = $stmt->fetch()) {
        $ventas[] = strtolower($row['nombre']);
    }
    $newVentas = implode(',', $ventas);

    json_success(['presentaciones_venta' => $newVentas], 'Presentación actualizada');
} catch (Exception $e) {
    json_error('Error: ' . $e->getMessage());
}
