<?php declare(strict_types=1);

namespace App\Repository;

use App\Controller\ConfigController;
use App\Controller\DatabaseConnection;
use App\Entity\Domain;
use Monolog\Logger;
use PDO;
use PDOException;

/**
 *
 */
readonly class DomainRepository
{
	public function __construct(
		private DatabaseConnection $databaseConnection,
		private ConfigController   $configController,
		private Logger             $logger)
	{
		$this->logger->debug(message: "DomainRepository::__construct()");
		
	}
	
	
	/**
	 * @return array
	 */
	public function findAll(): array
	{
		$this->logger->debug(message: "findAll()");
		
		$domains = [];
		$sql = "
            SELECT id, name, panel
            FROM " . DatabaseConnection::TABLE_DOMAINS . "
            ORDER BY name";
		
		try {
			$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
			$statement->execute();
			while ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
				$domain = new Domain(name: $result['name'], panel: $result['panel'], id: $result['id']);
				$domains[] = $domain;
			}
			return $domains;
		} catch (PDOException $e) {
			exit($e->getMessage());
		}
	}

    public function findByPanel(string $name): array
    {
        $this->logger->debug(message: "findByPanel($name)");

        $domains = [];
        $sql = "
			SELECT id, name, panel
			FROM . " . DatabaseConnection::TABLE_DOMAINS . "
            WHERE panel = :panel";

        try {
            $statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
            $statement->bindParam(param: ':panel', var: $name);
            $statement->execute();
            while ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
                $domain = new Domain(name: $result['name'], panel: $result['panel'], id: $result['id']);
                $domains[$result['name']] = $domain;
            }
            return $domains;
        } catch (PDOException $e) {
            exit($e->getMessage());
        }
    }

	public function findByID(int $id): bool|Domain
	{
		$this->logger->debug(message: "findById($id)");
		
		$sql = "
			SELECT id, name, panel
			FROM . " . DatabaseConnection::TABLE_DOMAINS . "
            WHERE id = :id";
		
		try {
			$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
			$statement->bindParam(param: ':id', var: $id);
			$statement->execute();
			if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
				
				return new Domain(name: $result['name'], panel: $result['panel'], id: $result['id']);
			} else {
				return false;
			}
		} catch (PDOException $e) {
			exit($e->getMessage());
		}
	}
	
	

	public function findByName(string $name): Domain|bool
	{
		$this->logger->debug(message: "findByName($name)");
		
		$sql = "
			SELECT id, name, panel
			FROM " . DatabaseConnection::TABLE_DOMAINS . "
            WHERE name = :name";
		
		try {
			$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
			$statement->bindParam(param: ':name', var: $name);
			$statement->execute();
			if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
				return new Domain(name: $result['name'], panel: $result['panel'], id: $result['id']);
			} else {
				return false;
			}
		} catch (PDOException $e) {
			exit($e->getMessage());
		}
	}
	

	public function findByHost(string $host): Domain|bool
	{
		$this->logger->debug(message: "findByHost($host)");
		
		$host = strtolower(string: trim(string: $host));
		$count = substr_count(haystack: $host, needle: '.');
		if ($count == 2) {
			if (strlen(string: explode(separator: '.', string: $host)[1]) > 3) {
				$host = explode(separator: '.', string: $host, limit: 2)[1];
			}
		} elseif ($count > 2) {
			$host = $this->findByHost(host: explode(separator: '.', string: $host, limit: 2)[1]);
		}
		
		if ($domain = $this->findByName(name: $host)) {
			return $domain;
		} else {
			return false;
		}
	}
	

	public function insert(Domain $domain): bool|string
	{
		$domainName = $domain->getName();
		$this->logger->info(message: "insert($domainName)");
		
		$sql = "
            INSERT INTO " . DatabaseConnection::TABLE_DOMAINS . " (name, panel)
            VALUES (:name, :panel)";
		
		try {
			$name = $domain->getName();
			$panel = $domain->getPanel();
			$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
			$statement->bindParam(param: ':name', var: $name);
			$statement->bindParam(param: ':panel', var: $panel);
			$statement->execute();
			
			return $this->databaseConnection->getConnection()->lastInsertId();
		} catch (PDOException $e) {
			exit($e->getMessage());
		}
	}
	
	
	/**
	 * @param \App\Entity\Domain $domain
	 *
	 * @return false|int
	 */
	public function update(Domain $domain): bool|int
	{
		$domainName = $domain->getName();
		$this->logger->debug(message: "update($domainName)");
		
		$id = $domain->getId();
		$current = $this->findByID(id: $id);
		
		if (empty($domain->getName())) {
			$name = $current->getName();
		} else {
			$name = $domain->getName();
		}
		if (empty($domain->getPanel())) {
			$panel = $current->getPanel();
		} else {
			$panel = $domain->getPanel();
		}
		
		$sql = "
			UPDATE " . DatabaseConnection::TABLE_DOMAINS . " SET
				name = :name,
				panel = :panel
            WHERE id = :id";
		
		try {
			$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
			$statement->bindParam(param: 'id', var: $id);
			$statement->bindParam(param: 'name', var: $name);
			$statement->bindParam(param: 'panel', var: $panel);
			$statement->execute();
			
			return $statement->rowCount();
		} catch (PDOException $e) {
			echo $e->getMessage();
			return false;
		}
	}
	
    public function delete(Domain $domain): int
	{
		$domainName = $domain->getName();
		$this->logger->debug(message: "delete($domainName)");

        // FIXME, add force parameter, reject deletion if domains left on panel
		$sql = "
            DELETE FROM " . DatabaseConnection::TABLE_DOMAINS . "
            WHERE id = :id";
		
		try {
			$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
			$id = $domain->getId();
			$statement->bindParam(param: 'id', var: $id);
			$statement->execute();
			
			return $statement->rowCount();
		} catch (PDOException $e) {
			exit($e->getMessage());
		}
	}

    // FIXME check for master/slave in config generation
	public function getLongestEntry(string $field): int
	{
		$sql = "
            SELECT MAX(LENGTH(" . $field . ")) as length FROM " . DatabaseConnection::TABLE_DOMAINS;
		
		try {
			$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
			$statement->execute();
			$result = $statement->fetch();
            // if there are not yet any domains, just return 30
			return $result['length'] ?? 30;
		} catch (PDOException $e) {
			exit($e->getMessage());
		}
	}
}
