<?php


class CfDeletedHost
{
    /**
     * @var PDO
     */
    private $pdo;


    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function getHosts($limit = null, $offset = 0): array
    {
        $sth = $this->pdo->prepare('SELECT * FROM __hosts WHERE deleted IS NOT NULL OFFSET :offset LIMIT :limit');
        $sth->execute(array(':offset' => $offset, ':limit' => $limit));
        $hosts = $sth->fetchAll(PDO::FETCH_ASSOC);

        return [
            'data' => $hosts,
            'meta' => [
                'total' => $this->getDeletedHostCount(),
                'page' => $offset + 1,
                'count' => sizeof($hosts),
                'timestamp' => time(),
            ]
        ];
    }

    private function getDeletedHostCount(): int
    {
        return intval(
            (
                $this->pdo
                ->query('SELECT COUNT(*) as count FROM __hosts WHERE deleted IS NOT NULL')
                ->fetch(PDO::FETCH_ASSOC)
            )['count']
        );
    }

    public function getDeletedHost($hostkey): false|array
    {
        $statement = $this->pdo->prepare('SELECT * FROM __hosts WHERE deleted IS NOT NULL AND hostkey = :hostkey');
        $statement->execute([':hostkey' => $hostkey]);
        return $statement->fetchAll(PDO::FETCH_ASSOC);
    }

    public function permanentlyDelete($hostkey): bool
    {
        $statement = $this->pdo->prepare('DELETE FROM __hosts WHERE deleted IS NOT NULL AND hostkey = :hostkey');
        return $statement->execute([':hostkey' => $hostkey]);
    }

    public function restoreDeletedHost(string $hostkey): bool
    {
        $statement = $this->pdo->prepare('UPDATE __hosts SET deleted = NULL WHERE deleted IS NOT NULL AND hostkey = :hostkey');
        return $statement->execute([':hostkey' => $hostkey]);
    }

}
