<?php
// cms/api/tags/list

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out = new stdClass();
    $sessionid = mysqli_real_escape_string($db, $_GET["sessionid"]);
    $filter = '';
    $filterStr = mysqli_real_escape_string($db, $_GET['filter']);
    $out->numofrecords = 0;
    $records = [];
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //En caso de que el filter sea enviado, se construye el query
    if(isset($_GET["filter"]) && $_GET["filter"] != ""){
        $filter = " WHERE tag LIKE '%".mysqli_real_escape_string($db, $_GET['filter'])."%'";
    }
    
    $sql = "SELECT DISTINCT tag FROM users ".
    "       ".$filter;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    while($row = $rs->fetch_assoc()){
        
        // Separamos los tags
        $tagsArr = explode(' ',$row['tag']);
        
        if (strpos($a, 'are') !== false) {
    echo 'true';
}

        foreach($tagsArr as $tag){
            if((count($records) == 0) && $tag != '' && $tag != null && strpos($tag, $filterStr) !== false){
                //$out->testing [] = "soy ceor";
                $out->numofrecords++;
                $records [] = $tag;
            }else{
                // Validamos que no exista en el arreglo
                $exist = false;
                
                foreach($records as $rec){
                    if($rec == $tag){
                        $exist  =true;
                    }
                }
                
                if(!$exist && $tag != '' && $tag != null && strpos($tag, $filterStr) !== false){
                    //$out->testing [] = "no soy cero: ".$tagsArr;
                    $out->numofrecords++;
                    $records [] = $tag;
                }
            }
        }
    }
    
    $out->records = $records;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
