<?php

namespace Digtective\Repository;

class TokenRepository extends BaseRepository implements TokenRepositoryInterface{
    private $tablePrefix;
    private $databaseName;

    public function __construct(){
        parent::__construct();
        $this->tablePrefix = $this->DB->prefix;
        $this->databaseName = $this->DB->dbname;
    }

    public function create(string $token){
        $queryResponseString = $this->DB->query(
            $this->DB->prepare(
                "INSERT INTO {$this->tablePrefix}digtective_token (digger_token) VALUES (%s)",
                [
                    $token,
                ]
            )
        );

        return $queryResponseString;
    }

    public function tableExists(){
        $queryResponse = $this->DB->get_results(
            "SELECT 1 FROM information_schema.tables WHERE table_schema = '{$this->databaseName}' AND table_name = '{$this->tablePrefix}digtective_token';"
        );

        return count($queryResponse) > 0;
    }

    public function getToken(){
        $queryResponse = $this->DB->get_results(
            "SELECT digger_token FROM {$this->tablePrefix}digtective_token LIMIT 1"
        );

        return $queryResponse[0]->digger_token ?? "";
    }

    public function hasToken(){
        $result = $this->DB->get_results(
            "SELECT digger_token FROM {$this->tablePrefix}digtective_token LIMIT 1"
        );

        return count($result) > 0;
    }

    public function update($token){
        return $this->DB->get_results(
            $this->DB->prepare("UPDATE {$this->tablePrefix}digtective_token SET digger_token = %s WHERE id = 1", $token)
        );
    }
}
