<?php

return new class implements Restaurace
{

	public function name(): string
	{
		return 'Slezské uzeniny';
	}

	public function link(): string
	{
		return 'https://www.slezske-uzeniny.cz/prodejny/zlin-2250/';
	}

	public function menu(): ?array
	{
		$html = @file_get_contents($this->link());

		if (!$html) {
			return null;
		}

		if (!preg_match('~<a href="(?<link>[^"]+)" target="_blank" rel="noopener">Denní menu</a>~', $html, $matches)) {
			return null;
		}

		$components = parse_url($this->link());
		$link = sprintf('%s://%s%s', $components['scheme'], $components['host'], $matches['link']);
		$filename = sprintf('%s/JATKA-%s.pdf', sys_get_temp_dir(), date('YmdHis'));

		$content = @file_get_contents($link);

		if ($content === false) {
			return null;
		}

		if (@file_put_contents($filename, $content) === false) {
			return null;
		}

		try {

			$text = `pdftotext -layout $filename -`;

			if (preg_match('~\n\s*(?<od>\d+\.\s*\d+\.(\s*\d+)?)\s*-\s*(?<do>\d+\.\s*\d+\.(\s*\d+)?)\s*\n(?<text>.+)~s', $text, $matches)) {

				$od = self::date($matches['od']);
				$do = self::date($matches['do'], 23);

				if ($od === null || $do === null) {
					return null;
				}

				if ($od > new DateTime || $do < new DateTime) {
					return null;
				}

				$text = $matches['text'];

			}

			$lines = explode("\n", preg_replace('~[\r\n]+~', "\n", $text));

			static $dayNames = ['pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek'];

			$days = [];
			$day  = null;

			foreach ($lines as $line) {

				$line = trim($line);

				if ($line === '') {
					continue;
				}

				$lc = mb_strtolower($line);

				if (in_array($lc, $dayNames, true)) {

					$day = array_search($lc, $dayNames, true) + 1;

					$days[$day] = [
						'soup'  => null,
						'meals' => [],
					];

					continue;

				}

				if ($day === null) {
					continue;
				}

				if (strpos($line, '*') === 0) {

					$line = ltrim($line, ' *');

					if (preg_match('~^(?<meal>.*)\s*/\s*(?<price>\d+),-$~', $line, $matches)) {

						$days[$day]['meals'][] = [
							'name'  => $matches['meal'],
							'price' => $matches['price'],
						];

					} else {

						$days[$day]['meals'][] = [
							'name'  => $line,
							'price' => null,
						];

					}

				} elseif ($days[$day]['soup'] === null) {
					$days[$day]['soup'] = $line;
				}

			}

			$day = (int)date('N');

			if (empty($days[$day]) || empty($days[$day]['meals'])) {
				return null;
			}

			$menu = [];

			if ($days[$day]['soup'] !== null) {
				$menu[] = ['Polévka', $days[$day]['soup']];
			}

			$i = 1;

			foreach ($days[$day]['meals'] as $meal) {

				$title = sprintf('Jídlo #%d', $i++);

				if ($meal['price'] !== null) {
					$title .= sprintf(' *(%d Kč)*', $meal['price']);
				}

				$menu[] = [$title, $meal['name']];

			}

			return $menu;

		} finally {
			@unlink($filename);
		}
	}

	private static function date(string $date, int $h = 0): ?DateTimeInterface
	{
		$date = preg_replace('~\s+~', '', $date);
		$date = preg_replace('~^(\d+\.\d+)\..*$~', '$1', $date);
		$x = DateTime::createFromFormat('j.m', $date);

		if ($x === false) {
			return null;
		}

		$x->setTime($h, $h === 0 ? 0 : 59, $h === 0 ? 0 : 59);

		return $x;
	}

};