<?php

// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// include database and object files
include_once '../../config/database.php';
include_once '../authenticator.php';

/**
 * select all users (name, surname, table) sharing the same table
 */
function getTablePeople($db, $uid) {
    $q = '
        SELECT name, surname, `table`
        FROM `user` u
        WHERE
            u.`table` = (
                SELECT `table` FROM `user` WHERE id = :uid
            ) AND
            u.id  <> :uid
    ';

    // prepare query statement
    $stmt = $db->prepare($q);
    $stmt->bindParam(":uid", $uid);

    // execute query
    $stmt->execute();
    $result = [
        'count' => 0,
        'people' => [],
        'table' => null,
    ];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        $result['count']++;
        $result['people'][] = [
            'name' => $row['name'],
            'surname' => $row['surname'],
        ];
        $result['table'] = $row['table'];
    }
    return $result;
}


/**
 * Method implementation
 */

if ($_SERVER['REQUEST_METHOD'] != 'GET') {
    http_response_code(400);
    echo json_encode(array("error" => "Method not accepted."));
    exit();
}

// instantiate database
$database = new Database();
$db = $database->getConnection();

$auth = new Authenticator($db);
$uid = $auth->authenticate();

$result = getTablePeople($db, $uid);

// set response code - 200 OK
http_response_code(200);

// show products data in json format
echo json_encode($result);
