<?php
namespace Melbahja\Seo;

use Melbahja\Seo\Interfaces\SeoInterface;

/**
 * @package Melbahja\Seo
 * @since v2.0
 * @see https://git.io/phpseo
 * @license MIT
 * @copyright 2019-present Mohamed Elabhja
 */
class Robots implements SeoInterface
{

	/**
	 * Robots rules.
	 * @var array
	 */
	protected $rules = [];

	/**
	 * Sitemap urls.
	 * @var array
	 */
	protected $sitemaps = [];


	/**
	 * Add rules for bot by user agent name.
	 *
	 * @param  string $userAgent bot user agent name
	 * @param  array  $rules
	 * @return Robots
	 */
	public function bot(string $userAgent, array $rules): Robots
	{
		$this->rules[$userAgent] = $rules;
		return $this;
	}

	/**
	 * Set sitemap url.
	 *
	 * @param  string $url
	 * @return Robots
	 */
	public function sitemap(string $url): Robots
	{
		$this->sitemaps[] = $url;
		return $this;
	}


	/**
	 * Build robots rules.
	 *
	 * @return string
	 */
	public function __toString(): string
	{
		$out = "# Autogenerated by melbahja/seo\r\n";

		foreach ($this->sitemaps as $url)
		{
			$out .= "Sitemap: {$url}\r\n";
		}

		if ($out !== "") {
			$out .= "\r\n";
		}

		foreach($this->rules as $agent => $rules)
		{
			$out .= "User-agent: {$agent}\r\n";

			if (isset($rules['allow'])) {
				foreach ($rules['allow'] as $v)
				{
					$out .= "Allow: {$v}\r\n";
				}
			}

			if (isset($rules['disallow'])) {
				foreach($rules['disallow'] as $v)
				{
					$out .= "Disallow: {$v}\r\n";
				}
			}

			if (isset($rules['delay'])) {
				$out .= "Crawl-delay: {$rules['delay']}\r\n";
			}

			$out .= "\r\n";
		}

		return $out;
	}

}
