<?php
require_once __DIR__ . '/config.php';
$me = must_auth();
$b  = json_decode(file_get_contents('php://input'),true) ?: array();
$id     = isset($b['id'])     ? (int)$b['id']       : 0;
$forAll = !empty($b['forAll']);
if (!$id) fail('Missing id');
$st = db()->prepare('SELECT * FROM messages WHERE id=? LIMIT 1');
$st->execute(array($id)); $msg = $st->fetch();
if (!$msg) fail('Not found',404);
if ($forAll && $msg['from_user']===$me) {
    db()->prepare("UPDATE messages SET cipher_text='',iv='',deleted_for='[\"__all__\"]' WHERE id=?")->execute(array($id));
} else {
    $cur = json_decode($msg['deleted_for'] ?: '[]',true) ?: array();
    $cur[] = $me;
    db()->prepare("UPDATE messages SET deleted_for=? WHERE id=?")->execute(array(json_encode($cur),$id));
}
ok();
