<?php
    require_once('../../../server/api-adodb/config.php');
    require_once(LIB_PATH.DS.'loggedin.php');

    if(!empty($_POST['tableName'])){
        $tableName = $_POST['tableName'];
    }else{
        die("Please select a table!");
    }

    $table = new Table($tableName);
    $foreignKey = (string) $_POST['foreignKey'];
    $foreignKeyId = intval($_POST['foreignKeyId']);

    $sql = " `$foreignKey` = '$foreignKeyId' ";


    if(!empty($_POST['order_by'])){
        $orderBy = $_POST['order_by'];
        $orderBy = (string) $orderBy;

        $sql .= " ORDER BY {$orderBy} ASC ";
    }

    if(!empty($_POST['count'])){
        $limit = intval($_POST['count']);
        $sql .= " LIMIT {$limit} ";
    }

    $displayField = $table->getDisplayField();

    $displayField = $displayField === false ?  'name' : $displayField;

    $results = $table->findWhere($sql, array ('id', $displayField) );
    $json = array();
    foreach($results as $result){
        $append ['id'] = $result['id'];
        $append ['displayField'] = displayInSitemap($tableName, $result[$displayField] );
        $append ['link'] = pageLink("generate.php?table={$tableName}&id={$result['id']}");
        $json [] = $append;
    }
    echo json_encode($json);

?>
