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

function ensure_archive_table() {
    db()->exec("CREATE TABLE IF NOT EXISTS archived_chats (
        owner VARCHAR(50) NOT NULL,
        peer VARCHAR(50) NOT NULL,
        archived_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (owner, peer),
        INDEX idx_archived_owner (owner)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
}

ensure_archive_table();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $b = json_decode(file_get_contents('php://input'), true);
    if (!is_array($b)) fail('Invalid JSON');
    $peer = isset($b['peer']) ? trim($b['peer']) : '';
    $archived = !empty($b['archived']);
    if ($peer === '') fail('Missing peer');
    if ($peer === $me) fail('Cannot archive your own account');

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

    if ($archived) {
        db()->prepare('REPLACE INTO archived_chats (owner, peer, archived_at) VALUES (?, ?, NOW())')
           ->execute(array($me, $peer));
    } else {
        db()->prepare('DELETE FROM archived_chats WHERE owner=? AND peer=?')
           ->execute(array($me, $peer));
    }
    ok(array('peer' => $peer, 'archived' => $archived));
}

fail('Method not allowed', 405);
