<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \Model\NewsItem;

class NewsController extends Controller
{
    public function show(Request $request, $id)
    {
        parent::registerView($request, 'nieuws', $id);
        $apiResult = $this->API('nieuws/bericht/' . $id);
	$newsItem = new \Model\NewsItem($apiResult->news);

	switch($apiResult->version) {
		case 1:
			return view('newsitem', ['news' => $newsItem, 'meta_featuredImage' => count($newsItem->images) ? $newsItem->images[0]->url : null]);
			break;

		case 2:
			$source = $apiResult->source;
			$newsItem->published = new \DateTimeImmutable('@' . $source->created);
			$newsItem->edited = new \DateTimeImmutable('@' . $source->updated);
			$newsItem->author = $source->author;
			$newsItem->images = null; // Images will be embedded
			$newsItem->video = null; // Videos will be embedded
			$newsItem->content = $source->blocks;
			return view('newsitem', ['news' => $newsItem]);
        }
    }

    public function overview(Request $request)
    {
        return $this->listNews($request, 'overzicht');
    }

    public function regionlist(Request $request, $region)
    {
        return $this->listNews($request, 'regio/' . $region, ucfirst($region));
    }

    public function themelist(Request $request, $theme)
    {
        return $this->listNews($request, 'thema/' . $theme, ucfirst($theme));
    }
 
    public function search(Request $request, $query) 
    {
        return $this->listNews($request, 'zoeken/' . $query, 'Zoekresultaat')->with('query', urldecode($query));
    }
       
    private function listNews(Request $request, $url, $title = null)
    {
        $page = (int)$request->get('pagina', 1);
        $apiResult = $this->API('nieuws/' . $url . '?pagina=' . (int)max(1, $page));
        $news = [];
        foreach($apiResult->news as $newsItem)
        {
            $news[] = new \Model\NewsItem($newsItem);
        }

        return view($request->ajax() ? 'partial/newslist_small' : 'newslist', ['title' => $title, 'news' => $news, 'searchURL' => 'nieuws/zoeken']);
    }

    public function popular()
    {
        $apiResult = $this->API('nieuws/populair');
        $news = [];
        foreach($apiResult as $newsItem)
        {
            $news[] = new \Model\NewsItem($newsItem);
        }

        return view('popularnews', ['news' => $news]);
    }

    public function regionieuws() 
    {
        return view('listen', [
            'source' => $this->API_URL . 'nieuws/regionieuws',
            'title' => 'Regionieuws', 
            'content' => 'het laatste nieuws uit de regio',
            'isStream' => false,
            'canDownload' => true ]);
    }
}
