<?php

namespace App\Http\Controllers;

error_reporting(E_ALL);
ini_set('display_errors', true);

class NewsController extends Controller
{
    // TODO: Include podcast
    private static $BASE_SQL = <<<QUERY
SELECT `news`.`id`, `content`.`title`, `content`.`content`, `news`.`podcast`, `news`.`video`, `news`.`keywords`, `news`.`titlewithdate`, 
       `content`.`publishingdt` AS `published`, `content`.`creator`, `content`.`editingdt` AS `edited`, `content`.`editor`, 
       `content`.`showsource`, `sources`.`title` AS `source`, `sources`.`url` AS `source_url`, 
        `themes`.`title` AS `theme`, `themes`.`thumbnail` AS `theme_thumbnail`, `regions`.`title` AS `region`
    FROM `news`    
        LEFT JOIN `news_target_content` AS `content` ON `content`.`news` = `news`.`id`
        LEFT JOIN `news_regions` AS `regions` ON  `regions`.`id` = `news`.`region`
        LEFT JOIN `news_sources` AS `sources` ON  `sources`.`id` = `news`.`source`
        LEFT JOIN `news_themes` AS `themes` ON  `themes`.`id` = `news`.`theme`
    WHERE `news`.`category` = 1 AND `content`.`target` = 1 AND `news`.`active` = 1 AND `content`.`active` = 1
QUERY;

    private static $LOAD_IMAGES =
        'SELECT `id`, `file`, `description` AS `title` FROM `news_pictures` WHERE `news` = :newsId AND `active` = 1';
 
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
    * Lijst van alle nieuwsberichten
    */
    public function list(int $count = 15, int $page = 1) {
        if((int)$count <= 0) { $count = 15; }
        if((int)$page <= 0) { $page = 1; }
        $start = ($page - 1) * $count;
        $newsItems = app('db')->select(self::$BASE_SQL 
            . ' ORDER BY `published` DESC'
            . ' LIMIT ' . (int)$start . ', ' . (int)$count);

      $result = array();
      foreach($newsItems as $newsItem) {
        $pictures = app('db')->select(self::$LOAD_IMAGES, ['newsId' => $newsItem->id]);
        $result[] = new \Model\NewsItem($newsItem, $pictures);
      }

      return response()->json(['page' => $page, 'count' => $count, 'news' => $result]);
    }

    /**
    * Specifiek bericht ophalen
    */
    public function item(int $id) {
        $newsItem = app('db')->select(self::$BASE_SQL
            . ' AND `news`.`id` = :id LIMIT 0, 1',
            ['id' => $id]);
        
        if(count($newsItem) != 1) {
            return abort(404);
        } else {
            $pictures = app('db')->select(self::$LOAD_IMAGES, ['newsId' => $id]);
            return response()->json(new \Model\NewsItem($newsItem[0]));
        }
    }
}
