<?php

class AppleAPIController extends BaseController
{

    public function getSongs($category = null)
    {
        //show top songs based on category
        $genre = isset(Genre::where('is_visible', 1)->where('name', $category)->first()->id) ? Genre::where('is_visible', 1)->where('name', $category)->first() : Genre::where('is_visible', 1)->orderBy('order_id')->first();
        if ($genre) {
            $settings = Setting::first();

            $metaTitle = isset($category) ? Lang::get('words.top') . " " . Lang::get('words.' . $genre->name) . " ". Lang::get('words.songs') : null;

            $songs = array();
            try {
                //get top tracks from apple ituneds in json format
                $jsonData = file_get_contents('https://itunes.apple.com/'.$settings->country_code.'/rss/topsongs/limit='.$settings->max_top.'/genre='.$genre->genre_id.'/json');
                $jsonData = json_decode($jsonData, true);

                foreach ($jsonData['feed']['entry'] as $entry) {
                    $title = $entry['im:name']['label'];
                    $image = $entry['im:image'][2]['label'];

                    $artist = $entry['im:artist']['label'];
                    preg_match("/^(.*?)[^,|&]+/", $artist, $artist);
                    $artist = $artist[0];

                    $songs[] = array('title' => htmlspecialchars($title), 'image' => $image, 'artist' => $artist);

                }
            } catch (ErrorException $ex) {
                //throw new Exception("PHP Error: Function file_get_contents() not working", 1);                
            }
            return View::make('home.index', array('category' => $genre->name, 'songs' => $songs, 'title' => $metaTitle));
        }
    }
}
