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

if (!auth::user()) {
    endrequest("You dont have access to this api");
}

if (!isset($_GET["id"])) {
    endrequest("Invalid request");
} else if (!users::get($_GET["id"])) {
    endrequest("Invalid user ID");
}
$user = users::get($_GET["id"]);

$sql = "SELECT
 LPAD(f.id,3,0) as file_id,
 f.number, 
 f.state,
 f.name, 
 l.lcount,
 IF(l.working > 0, l.working, null) as working,
 l.completed
FROM `mis_files` as f 
LEFT JOIN (select file, count(id) as lcount, sum(state = 50) as completed,sum(state=20 or state = 30) as working from mis_letters where assigned = 13 group by file) as l on l.file = f.id
WHERE f.owner = :user
ORDER BY f.number";

$response = datatable::query($sql, ["user" => $user["id"]]);

echo json_encode($response);
