<?php

include 'conexion.php';

$inv_num = $_GET['inv_num'];
//$inv_num = "[BG0009],[BG0004],[BG0003]";
$findReplace = array('[',']'," ");

$replace_cadena = str_replace($findReplace, "", $inv_num);
$array_explode = explode(',',$replace_cadena);

$new_array = array();

for($i = 0; $i < sizeof($array_explode); $i++){
   array_push($new_array, "'$array_explode[$i]'");
}

$in = '(' . implode(',', $new_array) .')';

$query = "SELECT DISTINCT
 CONCAT(
     CASE WHEN LENGTH(activos.descripcion) < 1 THEN '' ELSE CONCAT(activos.descripcion, '\n\n')
 END,
 (
 SELECT
     GROUP_CONCAT(
         CONCAT(
             `campos`.`nombre`,
             ': ',
             IFNULL(
                 (
                 SELECT DISTINCT
                     `campo_activo`.`descripcion`
                 FROM
                     campo_activo
                 WHERE
                     campo_activo.fk_id_campo = campos.id_campo AND campo_activo.fk_id_activo = id_activo
             ),
             ''
             )
         ) SEPARATOR '\n'
     )
 FROM
     categorias
 RIGHT JOIN campos ON campos.fk_id_categoria = categorias.id_categoria
 WHERE
     categorias.id_categoria = activos.fk_id_categoria
 )
 ) AS DESCRIPTION,
activos.estado AS STATE,
categorias.nombre AS CATEGORY,
id_activo AS INVENTORY,
funci_responsable.nom_func_respon AS RESPONSIBLE
 FROM activos
INNER JOIN categorias ON categorias.id_categoria = activos.fk_id_categoria
INNER JOIN funci_responsable ON funci_responsable.id_func_respon = activos.fk_id_func_respon
WHERE id_activo IN $in ORDER BY id_activo";

   $result = $conexion->query($query);

   while($row = $result -> fetch_array()){
         $data[] = $row;
   }
 
   echo json_encode($data, JSON_UNESCAPED_UNICODE);
   $result -> close();

?>