<?php
// cms/api/departments/list

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("order","offset","numofrec","sessionid");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    
    //Definimos las variables que usaremos y las inicializamos
    $out= new stdClass;
    $sessionid = mysqli_real_escape_string($db, $_GET["sessionid"]);
    $order = determinateOrder(intval(mysqli_real_escape_string($db, $_GET["order"])));
    $offset = mysqli_real_escape_string($db, $_GET["offset"]);
    $numofrec = mysqli_real_escape_string($db, $_GET["numofrec"]);
    $filter = '';
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 77))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    //En caso de que el filter sea enviado, se construye el query
    if(isset($_GET["filter"]) && $_GET["filter"] != ""){
        // Iniciamos la cadena del query
        $filter = " WHERE ( ";
        
        //Separamos el filtro por el simbolo +
        $filterEl = separateFilter(mysqli_real_escape_string($db, $_GET["filter"]));
        
        //Recorremos cada elemento
        foreach($filterEl as $index => $el){
            
            if($index == 0){
                $filter .= " dsc LIKE '%".$el."%' ".
                "       OR email LIKE '%".$el."%'".
                "       OR phone1 LIKE '%".$el."%'".
                "       OR phone2 LIKE '%".$el."%'".
                "       OR phone3 LIKE '%".$el."%'";
            }else{
                $filter .= " OR dsc LIKE '%".$el."%' ".
                "       OR email LIKE '%".$el."%'".
                "       OR phone1 LIKE '%".$el."%'".
                "       OR phone2 LIKE '%".$el."%'".
                "       OR phone3 LIKE '%".$el."%'";
            }
        }
        
        $filter .= " ) ";
    }
    
    // Obtenemos la cantidad de mensajes
    $sql = "SELECT COUNT(*) AS qty ".
    "       FROM departments ".
    "       ".$filter;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $row = $rs->fetch_assoc();
    $out->numofrecords = (int)$row['qty'];
    
    // Obtenemos los detalles de los mensajes
    $sql = "SELECT * ".
    "       FROM departments".
    "       ".$filter.
    "       ".$order.
    "       LIMIT ".$offset.", ".$numofrec;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    while($row = $rs->fetch_assoc()){
        $record= new stdClass();
        
        $record->id = (int)$row['id'];
        $record->dsc = $row['dsc'];
        $record->email = $row['email'];
        $record->phone1 = $row['phone1'];
        $record->phone2 = $row['phone2'];
        $record->phone3 = $row['phone3'];
        
        $record->helpdesk = $row['helpdesk'];
        
        $records [] = $record;
    }
    
    $out->records = $records;
    
    $privileges = new stdClass();
    $privileges->read = tienePrivilegio($db, $sessionid, 77);
    $privileges->create = tienePrivilegio($db, $sessionid, 74);
    $privileges->delete = tienePrivilegio($db, $sessionid, 76);
    $privileges->update = tienePrivilegio($db, $sessionid, 75);
    
    $out->privileges = $privileges;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /* Con esta funcion determinamos el orden, donde:
    *   1 =  ASC
    *   -1 =  DESC
    */    
    function determinateOrder($id){
        $str = "";
        
        switch($id){
            case 1:
                $str = " ORDER BY dsc ASC";
                break;
            case 2:
                $str = " ORDER BY email ASC";
                break; 
            case 3:
                $str = " ORDER BY phone1 ASC";
                break;
            case 4:
                $str = " ORDER BY phone2 ASC";
                break; 
            case 5:
                $str = " ORDER BY phone3 ASC";
                break;
            case 6:
                $str = " ORDER BY id ASC";
                break;
            case -1:
                $str = " ORDER BY dsc DESC";
                break;
            case -2:
                $str = " ORDER BY email DESC";
                break; 
            case -3:
                $str = " ORDER BY phone1 DESC";
                break;
            case -4:
                $str = " ORDER BY phone2 DESC";
                break; 
            case -5:
                $str = " ORDER BY phone3 DESC";
                break;
            case -6:
                $str = " ORDER BY id DESC";
                break;
        }
        
        return $str;
    }
?>