<?php

function add_aps($token, $arr){
    if (!_is_logged($token)) return json_encode(array("STATUS"=>1000));

    include_once("function_library/def_functions/_aps.php");
    $rtn = _add_aps(json_decode($arr, true));


    //se retorna el id del elemento agregado codificado para edicion.
    $rtn['APS']['ID'] = encrypt($rtn['APS']['ID'], $token);

    return json_encode($rtn);
    
}

function update_aps($token, $cod, $arr){
    if (!_is_logged($token)) return json_encode(array("STATUS"=>1000));

    include_once("function_library/def_functions/_aps.php");
    $rtn = _update_aps(json_decode($arr, true), $cod, $token );


    //se retorna el id del elemento agregado codificado para edicion.
    $rtn['APS']['ID'] = encrypt($rtn['APS']['ID'], $token);

    return json_encode($rtn);

}


function upload_media_file($token, $id_aps, $path, $tipo){
    if (!_is_logged($token)) return json_encode(array("STATUS"=>1000));
    include_once("function_library/def_functions/_aps.php");
    $rtn = _add_media_file($path, $tipo, $id_aps, $token);
    return json_encode($rtn);
}

function get_aps($token, $dat){
 
    if (!_is_logged($token)) return json_encode(array("STATUS"=>1000));
    $dat = json_decode($dat, true);
    $sql = new sqldata();

    if ($id=="0"){
        return json_encode(array("STATUS"=>1, "APS"=>array("DESCRIPCION"=>"", "DENOMÏNACON"=>"", "COD"=>0) ) );
    }
    else{
        
        $aps = $sql->get_tabla("aps", "ID = ".  decrypt($dat['ID']));
        
        return json_encode(array(
            "STATUS"=>1,
            "APS"=>array(
                "EDIT_COD"=>encrypt($aps[0]['ID'],$token),
                "DESCRIPCION"=>$aps[0]['Descripcion'],
                "DENOMINACION"=>$aps[0]['Denominacion'])
            ) 
        );
    }
}

function get_media_list($token, $data){
    if (!_is_logged($token)) return json_encode(array("STATUS"=>1000));
    $sql = new sqldata();
    $data = json_decode($data,true);
    $media = $sql->get_tabla("media", "TablaID = ".  decrypt($data['ID']));
    _logthis($sql->last_query());
    for($i = 0 ; $i < count($media) ; $i ++){
        if ($media[$i]['Tipo']==1)
        $media[$i]['Path'] = "http://localhost/pasarela/upload/".$media[$i]['Path'];
    }
    return json_encode(array("STATUS"=>1, "MEDIA"=>$media) );
}

function append_link_media($token, $media){
    if (!_is_logged($token)) return json_encode(array("STATUS"=>1000));
    $sql = new sqldata();
    $media = json_decode($media);
    foreach($media as $link){
        $sql->insert("media", array("Path"=>$link, "Tipo"=>2));
    }
    return json_encode(array("STATUS"=>1));
}

function delete_media($token, $id){
    if (!_is_logged($token)) return json_encode(array("STATUS"=>1000));
    $sql = new sqldata();
    $media = $sql->get_tabla("media", "ID = ".$id);

    if ($media[0]['Tipo']==1)
        unlink("upload/".$media[0]['Path']);

    $sql->delete("media", "ID = ".$id);

    return json_encode(array("STATUS"=>1));
}
?>