<?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/pgm-list-byfeat?si=' . $this->cinemaId . '&sort=cin&bd=' . $this->day;

        return file_get_contents($url);

    }

    function parseRepertoire()
    {
        $document = $this->fetchRepertorire();
        $document = json_decode($document);


//        $cinemaData = [];
//        $text = "Repertuar Cinema-City\n";
//        $text .= str_replace('/', '-', $this->day) . "\n\n";
        $movies = [];

        $date = date('d/m/Y', strtotime($this->day));
        foreach ($document as $movieData) {
            $movie = [];
            $movie['title'] = $movieData->n;
            $movie['hours'] = [];

            foreach ($movieData->BD as $projections) {
                if ($projections->date == $date) {
                    foreach ($projections->P as $projection) {

//                        var_dump($projection);
//                        die();
                        $movie['hours'][] = $projection->time;
                    }
                }
            }
            if (count($movie['hours']) > 0) {
                $movies[] = $movie;
            }

        }


        return $movies;
    }

    function convertToPrint()
    {
        $cinemas = $this->parseRepertoire();

        $text = "Repertuar Cinema-City\n";
        $text .= $this->day . "\n\n";

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