<?php
/**
 * POST /api/productos/eliminar.php
 * Delete a product and all related records
 */
require_once '../../config/database.php';
require_once '../../includes/helpers.php';

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

$pdo = getConnection();
$id = (int)$data['id'];

try {
    $pdo->beginTransaction();

    // Delete related records first
    $pdo->prepare("DELETE FROM producto_lugares_compra WHERE producto_id = ?")->execute([$id]);
    $pdo->prepare("DELETE FROM producto_presentaciones WHERE producto_id = ?")->execute([$id]);

    // Delete product
    $stmt = $pdo->prepare("DELETE FROM productos WHERE id = ?");
    $stmt->execute([$id]);

    if ($stmt->rowCount() === 0) {
        $pdo->rollBack();
        json_error('Producto no encontrado', 404);
    }

    $pdo->commit();
    json_success([], 'Producto eliminado exitosamente');

} catch (Exception $e) {
    $pdo->rollBack();
    json_error('Error al eliminar: ' . $e->getMessage());
}
