<?php
require_once __DIR__ . '/config.php';
$me = must_auth();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $peer  = isset($_GET['with'])  ? trim($_GET['with'])   : '';
    $since = isset($_GET['since']) ? (int)$_GET['since']   : 0;
    $fullHistory = !empty($_GET['full']) || $since === 0;
    $limitSql = $fullHistory ? '' : ' LIMIT 150';
    if (!$peer) fail('Missing ?with=');
    $st = db()->prepare("SELECT m.*, DATE_FORMAT(m.sent_at,'%Y-%m-%dT%H:%i:%sZ') AS sent_at
        FROM messages m
        WHERE ((m.from_user=? AND m.to_user=?) OR (m.from_user=? AND m.to_user=?))
          AND m.id > ?
          AND (m.deleted_for IS NULL OR m.deleted_for NOT LIKE ?)
        ORDER BY m.id ASC" . $limitSql);
    $st->execute(array($me,$peer,$peer,$me,$since,'%"'.$me.'"%'));
    $rows = $st->fetchAll();
    // Mark as read
    db()->prepare("UPDATE messages SET status='read', status_at=UTC_TIMESTAMP() WHERE to_user=? AND from_user=? AND status!='read'")
       ->execute(array($me,$peer));
    // Fetch reactions
    if ($rows) {
        $ids = implode(',', array_map(function($r){return (int)$r['id'];}, $rows));
        $rxs = db()->query("SELECT * FROM reactions WHERE message_id IN ($ids)")->fetchAll();
        $rm  = array();
        foreach ($rxs as $r) $rm[$r['message_id']][] = $r;
        foreach ($rows as &$row) $row['reactions'] = isset($rm[$row['id']]) ? $rm[$row['id']] : array();
    }

    // Also return current receipt states for messages I sent in this chat.
    // This refreshes blue/read indicators even when there are no new messages to fetch.
    $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 to_user=?
          AND status IN ('delivered','read')
          AND (deleted_for IS NULL OR deleted_for NOT LIKE ?)
        ORDER BY id DESC LIMIT 200");
    $rs->execute(array($me,$peer,'%"'.$me.'"%'));
    ok(array('messages' => $rows, 'receipts' => $rs->fetchAll()));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $b  = json_decode(file_get_contents('php://input'), true);
    if (!is_array($b)) fail('Invalid JSON');
    $to = isset($b['to'])         ? trim($b['to'])         : '';
    $ct = isset($b['cipherText']) ? trim($b['cipherText']) : '';
    $iv = isset($b['iv'])         ? trim($b['iv'])         : '';
    $tp = isset($b['type'])       ? $b['type']             : 'text';
    $rt = isset($b['replyTo'])    ? (int)$b['replyTo']     : null;
    $fn = isset($b['fileName'])   ? substr($b['fileName'],0,255) : '';
    $fs = isset($b['fileSize'])   ? (int)$b['fileSize']    : 0;
    $fm = isset($b['fileMime'])   ? substr($b['fileMime'],0,100) : '';
    $fw = isset($b['forwarded'])  ? 1                      : 0;
    if (!$to || !$ct || !$iv) fail('Missing to/cipherText/iv');
    $st = db()->prepare('SELECT id FROM users WHERE username=? LIMIT 1');
    $st->execute(array($to));
    if (!$st->fetch()) fail('Recipient not found', 404);
    db()->prepare("INSERT INTO messages (from_user,to_user,cipher_text,iv,msg_type,reply_to,file_name,file_size,file_mime,forwarded,status,sent_at) VALUES (?,?,?,?,?,?,?,?,?,?,'sent',UTC_TIMESTAMP())")
       ->execute(array($me,$to,$ct,$iv,$tp,$rt,$fn,$fs,$fm,$fw));
    $id = db()->lastInsertId();
    // Mark delivered if recipient online
    $ps = db()->prepare("SELECT last_seen FROM presence WHERE username=?");
    $ps->execute(array($to));
    $pr = $ps->fetch();
    if ($pr && strtotime($pr['last_seen'] . ' UTC') > time()-30) {
        db()->prepare("UPDATE messages SET status='delivered', status_at=UTC_TIMESTAMP() WHERE id=?")->execute(array($id));
    }
    ok(array('id' => (int)$id));
}
fail('Method not allowed', 405);
