<?php
/**
 * POST /api/pos/verificar_contraindicaciones.php
 */
require_once '../config/database.php';
require_once '../includes/helpers.php';

require_post();
$data = json_input();

$genericos = [];
$ids = [];

if (isset($data['genericos']) && is_array($data['genericos'])) {
    $genericos = array_filter(array_map(function ($g) {
        return strtolower(trim($g));
    }, $data['genericos']), function ($g) {
        return $g !== '';
    });
    $genericos = array_values(array_unique($genericos));
}

if (isset($data['productos_ids']) && is_array($data['productos_ids'])) {
    $ids = array_filter(array_map('intval', $data['productos_ids']));
    $ids = array_values(array_unique($ids));
}

if (count($genericos) < 2 && count($ids) < 2) {
    // Si no hay suficientes productos ni genéricos, no puede haber contraindicaciones.
    json_success([]);
}

$pdo = getConnection();

try {
    $alertas = [];

    if (count($genericos) >= 2) {
        $placeholders = implode(',', array_fill(0, count($genericos), '?'));
        $sql = "
            SELECT id, generico_1, generico_2, gravedad, descripcion
            FROM contraindicaciones
            WHERE LOWER(generico_1) IN ($placeholders)
              AND LOWER(generico_2) IN ($placeholders)
        ";

        $stmt = $pdo->prepare($sql);
        $paramIndex = 1;
        foreach ($genericos as $g) {
            $stmt->bindValue($paramIndex++, $g, PDO::PARAM_STR);
        }
        foreach ($genericos as $g) {
            $stmt->bindValue($paramIndex++, $g, PDO::PARAM_STR);
        }
        $stmt->execute();
        $alertas = array_merge($alertas, $stmt->fetchAll(PDO::FETCH_ASSOC));
    }

    if (count($ids) >= 2) {
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $sql = "
            SELECT 
                c.id,
                p1.NombreComercial as producto_1,
                p2.NombreComercial as producto_2,
                c.gravedad,
                c.descripcion
            FROM contraindicaciones c
            JOIN productos p1 ON c.producto_id_1 = p1.id
            JOIN productos p2 ON c.producto_id_2 = p2.id
            WHERE c.producto_id_1 IN ($placeholders)
              AND c.producto_id_2 IN ($placeholders)
        ";

        $params = array_merge($ids, $ids);
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $alertas = array_merge($alertas, $stmt->fetchAll(PDO::FETCH_ASSOC));
    }

    // Normalizar alertas únicas
    $unique = [];
    $filtered = [];
    foreach ($alertas as $alerta) {
        $key = $alerta['id'] . '|' . ($alerta['generico_1'] ?? '') . '|' . ($alerta['generico_2'] ?? '');
        if (!isset($unique[$key])) {
            $unique[$key] = true;
            $filtered[] = $alerta;
        }
    }

    json_success($filtered);
} catch (Exception $e) {
    json_error('Error: ' . $e->getMessage());
}
?>
