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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') fail('POST required', 405);

$b = json_decode(file_get_contents('php://input'), true) ?: array();
$peer = isset($b['peer']) ? trim($b['peer']) : '';
if (!$peer) fail('Missing peer');
if ($peer === $me) fail('Cannot clear your own account chat');

$u = db()->prepare('SELECT id FROM users WHERE username=? LIMIT 1');
$u->execute(array($peer));
if (!$u->fetch()) fail('User not found', 404);

$st = db()->prepare("SELECT id, deleted_for FROM messages
    WHERE ((from_user=? AND to_user=?) OR (from_user=? AND to_user=?))
      AND (deleted_for IS NULL OR deleted_for NOT LIKE ?)
    ORDER BY id ASC");
$st->execute(array($me, $peer, $peer, $me, '%"'.$me.'"%'));
$rows = $st->fetchAll();

$up = db()->prepare('UPDATE messages SET deleted_for=? WHERE id=?');
$count = 0;
foreach ($rows as $row) {
    $deleted = json_decode($row['deleted_for'] ?: '[]', true);
    if (!is_array($deleted)) $deleted = array();
    if (!in_array($me, $deleted, true)) $deleted[] = $me;
    $up->execute(array(json_encode(array_values(array_unique($deleted))), $row['id']));
    $count++;
}

ok(array('cleared' => $count, 'peer' => $peer));
