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

if (!auth::user()) {
    endrequest("You dont have access to this api");
}
/*
if (!isset($_GET["newstate"])) {
    endrequest("Invalid Request");
} else {
    $r = validator::letterstate($_GET["newstate"]);
}*/

if (!isset($_GET["id"])) {
    endrequest("Invalid Request : ID not set");
} else if (!letters::get($_GET["id"])) {
    endrequest("Invalid Letter ID");
}

if (!isset($_GET["newstate"])) {
    endrequest("Invalid Request");
} else if (!validator::letterstate($_GET["newstate"])) {
    endrequest("Invalid Letter State");
}

$update = letters::update($_GET["id"], ["state" => $_GET["newstate"]]);

$sql = "SELECT 
    l.id,
    l.state,
    l.title,
    DATE_FORMAT(l.date, '%y %b %d') as year,
    DATE_FORMAT(l.date, '%y %b %d') as date,
    DATE_FORMAT(l.timestamp, '%H:%i') as time,
    DATE_FORMAT(l.received, '%Y') as received_year,
    DATE_FORMAT(l.received, '%b') as received_month,
    DATE_FORMAT(l.received, '%d') as received_date,
    u.name as user_name, 
    u.id as user_id,
    IF(s.name IS NULL, l.sender2, s.name) as sender_name,
    f.number as file_number,
    f.name as file_name,
    src.name as source_name,
    states.name as state_name,
    l.state as state,
    IF(DATEDIFF(CURDATE(),l.received) > 14, DATEDIFF(CURDATE(),l.received), null) as late
FROM 
    mis_letters as l
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 mis_files as f on l.file = f.id
LEFT JOIN mis_letter_states as states on l.state = states.id
WHERE 
    l.id = :id";

$r = datatable::query($sql, ["id" => $_GET["id"]]);

$r["data"][0]["notes"] = notes::byletter($_GET["id"]);


$response = [
    "success" => true,
    "data" => $r["data"][0]
];

echo json_encode($response);
