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

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $st = db()->prepare("SELECT peer, DATE_FORMAT(locked_at,'%Y-%m-%dT%H:%i:%sZ') AS locked_at FROM protected_chats WHERE owner=? ORDER BY locked_at DESC");
    $st->execute(array($me));
    ok(array('locked' => $st->fetchAll()));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $b = json_decode(file_get_contents('php://input'), true) ?: array();
    $peer = isset($b['peer']) ? trim($b['peer']) : '';
    $locked = !empty($b['locked']);
    if (!$peer) fail('Missing peer');
    if ($peer === $me) fail('Cannot lock 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);

    if ($locked) {
        db()->prepare('REPLACE INTO protected_chats (owner, peer, locked_at) VALUES (?, ?, UTC_TIMESTAMP())')
            ->execute(array($me, $peer));
    } else {
        db()->prepare('DELETE FROM protected_chats WHERE owner=? AND peer=?')
            ->execute(array($me, $peer));
    }
    ok(array('peer' => $peer, 'locked' => $locked));
}

fail('Method not allowed', 405);
