<?php
include_once 'config.php';

if ($_GET['get'] == 'shows' && $_GET['limit'] && isset($_GET['offset'])) {

  $output = array();
  $shows = querySB('shows');
  uasort($shows, function($a, $b) {
    return strcmp($a['show_name'], $b['show_name']);
  });
  $shows = array_slice($shows, $_GET['offset'], $_GET['limit'], true);
  foreach($shows as $key => $show) {
    $dataShow = querySB('show', $key);    
    $dataSeasons = querySB('show.seasons', $key);
    $seasons = array();
    foreach($dataSeasons as $season => $episodes) {
      array_push($seasons, array("season" => $season, "count" => count($episodes)));
    }
    array_push($output, array(
      "id" => $key,
      "name" => $show['show_name'],
      "folder" => str_replace($showsPath.'/', '', $dataShow['location']),
      "seasons" => $seasons
    ));
    unset($seasons);
  }
  header('Content-Type: application/json');
  echo json_encode($output);
  die;

}


if ($_GET['get'] == 'movies' && $_GET['limit'] && isset($_GET['offset'])) {

  $movies = queryCP('media.list', 'type=movie&status=done&release_status=done&status_or=1');
  $movies = array_slice($movies, $_GET['offset'], $_GET['limit'], true);
  $output = array();
  foreach ($movies as $movie) {
    array_push($output, array(
      "imdb" => $movie['info']['imdb'],
      "title" => $movie['title'],
      "year" => $movie['info']['year'],
      "tagline" => $movie['info']['tagline'], 
      "plot" => $movie['info']['plot'],
      "rating" => $movie['info']['rating']['imdb'][0].' ('.$movie['info']['rating']['imdb'][1].')',
      "status" => $movie['status'],
      "folder" => current(explode('/', current(str_replace($moviesPath.'/', '', $movie['releases'][release_with_file($movie['releases'])]['files']['movie']))))
    ));
  }
  header('Content-Type: application/json');
  echo json_encode($output);
  die;

}


if ($_GET['get'] == 'comics' && $_GET['limit'] && isset($_GET['offset'])) {

  $comics = queryML('getIndex');
  $comics = array_slice($comics, $_GET['offset'], $_GET['limit'], true);
  $output = array();
  foreach ($comics as $comic) {
    $issues = queryML('getComic', $comic['ComicID']);
    array_push($output, array(
      "id" => $comic['ComicID'],
      "title" => $comic['ComicName'],
      "year" => $comic['ComicYear'],
      "publisher" => $comic['ComicPublisher'],
      "have" => $comic['Have'],
      "total" => $comic['Total'],
      "status" => $comic['Status'],
      "folder" => str_replace($comicsPath.'/', '', $comic['ComicLocation']),
      "issues" => $issues['issues']
    ));
  }
  header('Content-Type: application/json');
  echo json_encode($output);
  die;

}


if ($_GET['get'] == 'poster' && (!empty($_GET['show']) || !empty($_GET['movie']) || !empty($_GET['comic']))) {

  if(isset($_GET['show'])) {
    $type = 'show';
  }elseif(isset($_GET['movie'])) {
    $type = 'movie';
  }elseif(isset($_GET['comic'])) {
    $type = 'comic';
  }

  if($_GET['show'] && $_GET['season'])
    $poster = get_absolute_path('cache/poster/'.$type.'/'.cleanName($_GET[$type]).'-S'.$_GET['season'].'.jpg');
  else
    $poster = get_absolute_path('cache/poster/'.$type.'/'.cleanName($_GET[$type]).'.jpg');

  if(!file_exists($poster)) {

    if ($_GET['show']) {
      $path = '/'.get_absolute_path($showsPath.'/'.cleanName($_GET[$type], false));
      if($_GET['season']) {
        $filenames = array(
          'season'.$_GET['season'].'-poster.jpg'
        );
      }else {
        $filenames = array(
          'poster.jpg',
        );
      }
    } elseif ($_GET['movie']) {
      $path = '/'.get_absolute_path($moviesPath.'/'.cleanName($_GET[$type], false));
      $filenames = array(
        cleanName($_GET['movie'], false).'-poster.jpg',
        'poster.jpg',
      );
    } elseif ($_GET['comic']) {
      $path = '/'.get_absolute_path($comicsPath.'/'.cleanName($_GET[$type], false));
      $filenames = array(
        'cover.jpg',
      );
    }

    foreach($filenames as $filename) {
      if(file_exists($path.'/'.$filename)) {
        $source = $path.'/'.$filename;
        break;
      }
    }

    if($source) {
      $img = new Imagick();
      $img->setOption('jpeg:size', '800x532');
      $img->readImage($source);
      $img->thumbnailImage(0, 220);
      $img->setImageCompression(Imagick::COMPRESSION_JPEG);
      $img->setImageCompressionQuality(70);
      $img->writeImage($poster);
    }elseif($_GET['season'] != '') {
      header("HTTP/1.0 404 Not Found");
      die;
    }else{
      //$poster = 'img/no_poster.jpg';
      header("Location: ../../img/no_poster.jpg");
    }
  }

  header('Content-type: image/jpeg');
  header('Content-length: '.filesize($poster));
  readfile($poster);
  die;
}


if ($_GET['get'] == 'fanart' && (!empty($_GET['show']) || !empty($_GET['movie']) || !empty($_GET['comic']))) {

  if(isset($_GET['show'])) {
    $type = 'show';
  }elseif(isset($_GET['movie'])) {
    $type = 'movie';
  }elseif(isset($_GET['comic'])) {
    $type = 'comic';
  }
  
  $fanart = get_absolute_path('cache/fanart/'.$type.'/'. cleanName($_GET[$type]).'.jpg');

  if(!file_exists($fanart)) {

    if($_GET['show']) {
      $path = '/'.get_absolute_path($showsPath.'/'.cleanName($_GET[$type], false));
      $filenames = array(
      'fanart.jpg',
      );
    } elseif($_GET['movie']) {
      $path = '/'.get_absolute_path($moviesPath.'/'.cleanName($_GET[$type], false));
      $filenames = array(
        cleanName($_GET['movie'], false).'-fanart.jpg',
        'fanart.jpg',
      );
    } elseif($_GET['comic']) {
      $path = '/'.get_absolute_path($comicsPath.'/'.cleanName($_GET[$type], false));
      $filenames = array(
        'cover.jpg',
      );
    }

    foreach($filenames as $filename) {
      if(file_exists($path.'/'.$filename)) {
        $source = $path.'/'.$filename;
        break;
      }
    }

    if($source) {
      $img = new Imagick();
      $overlay = new Imagick();
      $img->setOption('jpeg:size', '1024x576');
      $img->readImage($source);
      $res = $img->getImageGeometry();
      if($res['width'] >= $res['height']) {
        $ar = $res['height'] / $res['width'];
        $img->thumbnailImage(1024, 0);
        $overlay->newImage(1024, ceil(1024*$ar), new ImagickPixel('white'));
        $overlay->setOption('jpeg:size', '1024x'.ceil(1024*$ar));
      } else {
        $ar = $res['width'] / $res['height'];
        $img->thumbnailImage(0, 1024);
        $overlay->newImage(ceil(1024*$ar), 1024, new ImagickPixel('white'));
        $overlay->setOption('jpeg:size', ceil(1024*$ar).'x1024');
      }      
      $overlay->setImageOpacity(0.50);
      $img->compositeImage($overlay, imagick::COMPOSITE_OVER, 0, 0);
      $img->setImageCompression(Imagick::COMPRESSION_JPEG);
      $img->setImageCompressionQuality(50);
      $img->writeImage($fanart);
    }else{
      //$fanart = 'img/no_fanart.jpg';
      header("Location: ../../img/no_fanart.jpg");
    }
  }

  header('Content-type: image/jpeg');
  header('Content-length: '.filesize($fanart));
  readfile($fanart);
  die;
}


if ($_GET['get'] == 'logo' && (!empty($_GET['show']) || !empty($_GET['movie']))) {

  if(isset($_GET['show'])) {
    $type = 'show';
  }else{
    $type = 'movie';
  }
  
  $logo = get_absolute_path('cache/logo/'.$type.'/'.cleanName($_GET[$type]).'.png');

  if(!file_exists($logo)) {

    if($_GET['show']) {
      $path = '/'.get_absolute_path($showsPath.'/'.cleanName($_GET[$type], false));
      $filenames = array(
      'clearlogo.png',
      'logo.png',
      );
    } else {
      $path = '/'.get_absolute_path($moviesPath.'/'.cleanName($_GET[$type], false));
      $filenames = array(
        cleanName($_GET['movie'], false).'-clearlogo.png',
        'clearlogo.png',
        cleanName($_GET['movie'], false).'-logo.png',
        'logo.png',
      );
    }

    foreach($filenames as $filename) {
      if(file_exists($path.'/'.$filename)) {
        $source = $path.'/'.$filename;
        break;
      }
    }

    if($source) {
      $img = new Imagick();
      $img->readImage($source);
      $img->thumbnailImage(0, 50);
      $img->writeImage($logo);
    }else{
      header("HTTP/1.0 404 Not Found");
      die;
    }
  }

  header('Content-type: image/png');
  header('Content-length: '.filesize($logo));
  readfile($logo);
  die;
}


if ($_GET['get'] == 'episodes' && !empty($_GET['show']) && isset($_GET['season'])) {
  $output = array();
  if($json = file_get_contents('http://'.$sb['host'].':'.$sb['port'].$sb['path'].'/api/'.$sb['key'].'/?cmd=show.seasons&tvdbid='.$_GET['show'].'&season='.$_GET['season'])) {
    $data = current(json_decode($json, true));
    foreach ($data as $key => $episode) {
      array_push($output, array("episode" => $key, "name" => $episode['name'], "status" => $episode['status'], "airdate" => $episode['airdate']));
    }
  }
  echo json_encode($output);
  die;
}

if ($_GET['get'] == 'latest' && $_GET['type'] == 'shows') {
  
  $eps = querySB('history');
  $output = array();
  foreach ($eps as $ep) {
    if($ep['status'] == 'Downloaded') {
      array_push($output, array("show" => $ep['show_name'], "episode" => "S".str_pad($ep['season'], 2, '0', STR_PAD_LEFT)."E".str_pad($ep['episode'], 2, '0', STR_PAD_LEFT), "airdate" => $ep['date']));
    }
  }
  $output = array_slice($output, 0, 10);
  echo json_encode($output);
  die;
  
}

if ($_GET['get'] == 'latest' && $_GET['type'] == 'movies') {

  $movies = queryCP('media.list', 'type=movie&status=done&release_status=done&status_or=1');
  uasort($movies, function($a, $b) {
    return $b['releases'][0]['last_edit'] - $a['releases'][0]['last_edit'];
  });
  $output = array();
  foreach ($movies as $movie) {
    array_push($output, array("movie" => $movie['title'].' ('.$movie['info']['year'].')'));
  }
  $output = array_slice($output, 0, 10);
  echo json_encode($output);
  die;
  
}


function cleanName($name, $strict = true) {
  if($strict == true)
    return preg_replace("/[^a-zA-Z0-9]/", "_", $name);
  else
    return preg_replace("/:/", "", $name);
}


function get_absolute_path($path) {
  $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
  $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
  $absolutes = array();
  foreach ($parts as $part) {
    if ('.' == $part) continue;
    if ('..' == $part) {
      array_pop($absolutes);
    } else {
      $absolutes[] = $part;
    }
  }
  return implode(DIRECTORY_SEPARATOR, $absolutes);
}

function querySB($cmd, $id = '', $season = '') {
  
  global $sb, $cacheTTL;
  if($id == '') {
    $cache = './cache/json/sb_'.$cmd.'.json';
  }else{
    $cache = './cache/json/sb_'.$cmd.'-'.$id.'.json';
  }
  if (!file_exists($cache) || filemtime($cache) < time()-$cacheTTL) {
    file_put_contents($cache, file_get_contents('http://'.$sb['host'].':'.$sb['port'].$sb['path'].'/api/'.$sb['key'].'/?cmd='.$cmd.'&tvdbid='.$id.'&season='.$season));
  }
  $json = file_get_contents($cache);
  $data = current(json_decode($json, true));
  return $data;
  
}

function queryCP($cmd, $params = '') {
  
  global $cp, $cacheTTL;
  if($params != '') {
    $params = '?'.$params;
  }
  $cache = './cache/json/cp_'.$cmd.'.json';
  if (!file_exists($cache) || filemtime($cache) < time()-$cacheTTL) {
    file_put_contents($cache, file_get_contents('http://'.$cp['host'].':'.$cp['port'].$cp['path'].'/api/'.$cp['key'].'/'.$cmd.'/'.$params));
  }
  $json = file_get_contents($cache);
  $data = current(json_decode($json, true));
  return $data;
  
}

function queryML($cmd, $id = '') {
  
  global $ml, $cacheTTL;
  if($id == '') {
    $cache = './cache/json/ml_'.$cmd.'.json';
  }else{
    $cache = './cache/json/ml_'.$cmd.'-'.$id.'.json';
  }
  if (!file_exists($cache) || filemtime($cache) < time()-$cacheTTL) {
    file_put_contents($cache, file_get_contents('http://'.$ml['host'].':'.$ml['port'].$ml['path'].'/api?apikey='.$ml['key'].'&cmd='.$cmd.'&id='.$id));
  }
  $json = file_get_contents($cache);
  $data = json_decode($json, true);
  return $data;  
}

function release_with_file($releases) {
    foreach($releases as $release => $value) {
        if($releases[$release]['status'] == 'done' && count($releases[$release]['files']['movie']) > 0) {
            return $release;
        }
    }
    return false;
}

?>