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

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

$response['input'] = $_GET;


if (!isset($_GET['year']) || !isset($_GET['month']) || !isset($_GET['day']) || !isset($_GET['forwardedto'])) {
    endrequest("not enough inputs");
}

$institute = institutions::get($_GET["forwardedto"]);
$response["forwarded_name"] = $institute["name"];


$sql = "SELECT 
    @index := @index + 1 as index_no,
    l.*,
    DATE_FORMAT(l.timestamp, '%H:%i') as time,
    DATE_FORMAT(l.date, '%y %b %d') as date,
    u.name as user_name, 
    u.id as user_id,
    IF(s.name IS NULL, l.sender2, s.name) as sender_name,
    f.shortname as forwarded_shortname,
    a.shortname as assigned_shortname,
    a.code as assigned_code,
    src.name as source_name
FROM 
    mis_letters as l
INNER JOIN (SELECT @index:= 0) as t
INNER JOIN users as u on l.user = u.id
INNER JOIN mis_letter_sources as src on l.source = src.id
LEFT JOIN institutions as s on l.sender = s.id
LEFT JOIN institutions as f on l.forwarded = f.id
LEFT JOIN users as a on l.assigned = a.id
WHERE 
    year(l.received) = :y and
    month(l.received) = :m and
    day(l.received) = :d and
    l.forwarded = :forwardedto
    order by l.id";

$data['y'] = $_GET['year'];
$data['m'] = $_GET['month'];
$data['d'] = $_GET['day'];
$data["forwardedto"] = $_GET['forwardedto'];

$query = datatable::query($sql, $data);
if ($query["success"]) {
    $response["data"] = $query["data"];
    $response["count"] = $query["count"];
} else {
}

echo json_encode($response);
