<?php
require_once __DIR__ . '/config.php';
$me    = must_auth();
$since = isset($_GET['since']) ? (int)$_GET['since'] : 0;
$readWith = isset($_GET['readWith']) ? trim($_GET['readWith']) : '';
$receiptAfter = isset($_GET['receiptAfter']) ? trim($_GET['receiptAfter']) : '1970-01-01 00:00:00';
$receiptAfter = str_replace(array('T','Z'), array(' ',''), substr($receiptAfter, 0, 20));
if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $receiptAfter)) $receiptAfter = '1970-01-01 00:00:00';
$end   = time() + 18;

while (time() < $end) {
    $st = db()->prepare("SELECT id,from_user,cipher_text,iv,msg_type,reply_to,file_name,file_size,file_mime,status,forwarded,DATE_FORMAT(sent_at,'%Y-%m-%dT%H:%i:%sZ') AS sent_at FROM messages WHERE to_user=? AND id>? AND (deleted_for IS NULL OR deleted_for NOT LIKE ?) ORDER BY id ASC LIMIT 30");
    $st->execute(array($me,$since,'%"'.$me.'"%'));
    $msgs = $st->fetchAll();

    $ts = db()->prepare("SELECT username FROM presence WHERE is_typing=1 AND typing_to=? AND username<>? AND typing_at>=DATE_SUB(UTC_TIMESTAMP(),INTERVAL 5 SECOND)");
    $ts->execute(array($me, $me));
    $typing = array_column($ts->fetchAll(), 'username');

    if ($msgs) {
        $readIds = array();
        $deliverIds = array();

        foreach ($msgs as &$m) {
            $mid = (int)$m['id'];
            if ($readWith !== '' && $m['from_user'] === $readWith) {
                $readIds[] = $mid;
                $m['status'] = 'read';
            } elseif ($m['status'] === 'sent') {
                $deliverIds[] = $mid;
                $m['status'] = 'delivered';
            }
        }
        unset($m);

        if ($readIds) {
            $ids = implode(',', $readIds);
            $rd = db()->prepare("UPDATE messages SET status='read', status_at=UTC_TIMESTAMP() WHERE id IN($ids) AND to_user=? AND from_user=? AND status!='read'");
            $rd->execute(array($me, $readWith));
        }
        if ($deliverIds) {
            $ids = implode(',', $deliverIds);
            db()->exec("UPDATE messages SET status='delivered', status_at=UTC_TIMESTAMP() WHERE id IN($ids) AND status='sent'");
        }
    }

    $rs = db()->prepare("SELECT id,status,DATE_FORMAT(status_at,'%Y-%m-%dT%H:%i:%sZ') AS status_at FROM messages WHERE from_user=? AND status IN ('delivered','read') AND status_at>? ORDER BY status_at ASC, id ASC LIMIT 200");
    $rs->execute(array($me, $receiptAfter));
    $receipts = $rs->fetchAll();

    if ($msgs || $receipts || $typing) {
        die(json_encode(array('ok'=>true,'messages'=>$msgs,'receipts'=>$receipts,'typing'=>$typing)));
    }
    usleep(800000);
}
die(json_encode(array('ok'=>true,'messages'=>array(),'receipts'=>array(),'typing'=>array())));
