<?php

namespace App\Http\Controllers;

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

class AgendaController extends Controller
{
    // TODO: Include podcast
    private static $BASE_SQL = <<<QUERY
SELECT `news`.`id`, `content`.`title`, `content`.`content`, `news`.`startdt` AS `starts`, `news`.`enddt` AS `ends`, `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`
    WHERE `news`.`category` = 42 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 agendaberichten
    */
    public function list(int $daysAhead = 0) {
        $sql = self::$BASE_SQL;
        if($daysAhead > 0) {
          $until = 'CURRENT_DATE() + INTERVAL ' . $daysAhead . ' DAY';
          $sql .= ' AND (`startdt` <= ' . $until . ' AND `enddt` >= CURRENT_DATE())';
        } else {
          $sql .= ' AND `enddt` >= CURRENT_DATE()';
        }

        $calendarItems = app('db')->select($sql
            . ' ORDER BY `startdt` ASC');

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

      return response()->json($result);
    }

    /**
    * Lijst van alle agendaberichten in de komende 7 dagen
    */
    public function listWeek() { 
      return $this->list(7);
    }

    /**
    * Lijst van alle agendaberichten in de komende 30 dagen
    */
    public function listMonth() { 
      return $this->list(30);
    }

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