<?php

namespace App\Paper;

use App\Paper\Interfaces\Cinema;
use DiDom\Document;

class CinemaCinemaCity implements Cinema
{

    private $cinemaId;
    private $day;

    public function setCinemaId($cinemaId)
    {
        $this->cinemaId = $cinemaId;
    }

    public function setDay($day)
    {
        $this->day = $day;
    }

    function fetchRepertorire()
    {
        if (is_null($this->cinemaId) || is_null($this->day))
            throw new \Exception('Day or cinemaid not set.');

        if (!is_array($this->cinemaId)) {
            $this->cinemaId = (array)$this->cinemaId;
        }




        $url = 'https://www.cinema-city.pl/scheduleInfo?locationId=1010308&date=' . $date . '&venueTypeId=0&hideSite=false&openedFromPopup=1';

        $document = new Document($url, true);
        $text = "Repertuar Cinema-City\n";
        $text .= str_replace('/', '-', $date) . "\n\n";

        $movies = $document->find('table tbody tr');
        foreach ($movies as $movie) {
//            dump($movie);
            $text .= $movie->find('.featureLink')[0]->text() . "\n";
            $hours = [];
            foreach ($movie->find('.prsnt a') as $projection) {
                $hours[] = trim($projection->text());
            }
            $text .= implode(', ', $hours) . "\n\n";
        }
        return $text;


    }

    function parseRepertoire()
    {
        $documents = $this->fetchRepertorire();
        $cinemas = [];
        foreach ($documents as $document) {
            $movies = [];
            foreach ($document->find('.seance') as $seans) {
                $movie = [];
                $movie['title'] = trim($seans->find('.movie-title')[0]->text());

                $hours = [];
                foreach ($seans->find('.time li') as $hour) {
                    $hours[] = $hour->text();
                }
                $movie['hours'] = array_unique($hours);
                $movies[] = $movie;
            }
            $cinemas[] = $movies;
        }
        return $cinemas;
    }

    function convertToPrint()
    {
        $cinemas = $this->parseRepertoire();
        $text = '';
        foreach ($cinemas as $cinemaId => $filmy) {
            $text .= "Repertuar " . $this->cinemas[$this->cinemaId[$cinemaId]] . "\n";
            $text .= date_create()->modify("+$this->day day")->format('d-m-Y') . "\n\n";

            foreach ($filmy as $film) {
                $text .= $film['title'] . "\n";
                $text .= implode(', ', array_unique($film['hours'])) . "\n\n";
            }
            $text .= "\n";
        }
        return $text;
    }
}