<?php
include "../../src/config.php";

if (!isset($_GET["institution"])) {
    endrequest("Invalid request");
}

$query = "SELECT 
    u.id,
    u.name,
    u.shortname,
    u.institution,
    i.codename as institution_codename,
    u.designation,
    u.code,
    u.state,
    u.lastseen,
    s.name as employee_state,
    IF(u.state = 1,true, null) as is_active,
    IF(u.state >= 10,true, null) as is_ex,
    DATE_FORMAT(u.lastseen, '%y.%m.%d') as lastseen_date,
    DATE_FORMAT(u.lastseen, '%H:%i') as lastseen_time,
    IF(u.lastseen > :now - INTERVAL 15 MINUTE, 'true', null) as isonline,
    TIMEDIFF(u.lastseen, :now) as timediff,
    NOW() as now
FROM 
    users as u
INNER JOIN mis_user_states as s on u.state = s.id
INNER JOIN institutions as i on u.institution = i.id 
WHERE 
    u.institution = :institution AND
    u.state = s.id
ORDER BY 
    u.state, u.code";

$response = datatable::query($query, ["institution" => $_GET["institution"], "now" => timestamp()]);

foreach ($response["data"] as $key => $value) {
    $response["data"][$key]["roles"] = userroles::assigned($response["data"][$key]["id"]);
}


echo json_encode($response);
