<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class KerkdienstController extends Controller
{
    private static $BASE_SQL = <<<QUERY
      SELECT ADDTIME(`zondagdienst`.`datum`, `zondagdienst`.`tijd`) AS `start`, `contacten`.`naam` AS `name` 
     FROM `zondagdienst` LEFT JOIN `contacten` ON `zondagdienst`.`kerk` = `contacten`.`contacten_id`
     WHERE `zondagdienst`.`datum` > DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)
     ORDER BY `zondagdienst`.`datum` ASC
     LIMIT 2
QUERY;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
    * Gegevens over laatste en huidige dienst
    */
    public function get() {

        $isAvailable = ((date('N') % 7) != 0) || (time() > strtotime('today noon'));
        $lastNext = app('db')->select(self::$BASE_SQL);
        foreach($lastNext as $r) {
          $r->start = new \DateTimeImmutable($r->start);
        }

        return response()->json([
          'isRunning' => !$isAvailable,
          'previous' => $lastNext[0],
          'next' => $lastNext[1]]);
    }
 
    /**
    * Download als MP3 bestand
    */
    public function download() {
       $file = '/var/audio/podcast/6fm-kerkdienst.mp3';
       return response()->download($file, "NH_Gooi_Gemist-Kerkdienst.mp3");
    }

    /**
    * Podcast van de laatste kerkdienst
    */
    public function podcast() {
        $file = '/var/audio/podcast/6fm-kerkdienst.mp3';
        $size = filesize($file);

        $headers = [
            'Pragma' => 'public',
            'Expires' => '-1',
            'Cache-Control' => 'public,must-revalidate,post-check=0,pre-check=0',
            'Content-Type' => 'audio/mpeg',
            'Content-Length' => $size,
            'Accept-Ranges' => 'bytes'
        ];

        $range = [];
        if(isset($_SERVER['HTTP_RANGE'])) {
          list($unit, $rangestr) = explode('=', $_SERVER['HTTP_RANGE'], 2);
          if($unit == "bytes") {
            $range = explode('-', $rangestr);
            $range[1] = (empty($range[1])) ? ($size - 1) : min(abs(intval($range[1])), ($size - 1));
            $range[0] = (empty($range[0]) || $range[1] < abs(intval($range[0]))) ? 0 : max(abs(intval($range[0])), 0);
            $range[2] = ($range[1] - $range[0] + 1);

            $headers['Content-Range'] = 'bytes ' . $range[0] . '-' . $range[1] . '/' . $size;
            $headers['Content-Length'] = $range[2];
          }
        }

        if($range === null) {
          response()->abort(416); // Requested Range Not Satisfiable
          return;
        }

        return new StreamedResponse(function() use($file, $range) {
            $output = fopen('php://output', 'w');

            $fp = fopen($file, 'rb');
            if(count($range) && $range[0]) {
              fseek($fp, $range[0]);
              $range[0] = 0;
            }

            $maxToRead = count($range) ? min(1024, $range[2]) : 1024;
            while ($buf = fread($fp, $maxToRead)) {
              fwrite($output, $buf);
              if(count($range)) {
                $maxToRead = min(1024, $range[2]);
                $bufSize = mb_strlen($buf, '8bit');
                if(($range[2] -= $bufSize) == 0) {
                 break;
                }
              }

            }

            fclose($fp);
            fclose($output);
        }, count($range) ? 206 : 200, $headers);
    }
}
