<?php

namespace App\Http\Controllers;

use App\Media as mMedia;
use App\General as mGeneral;
use App\Settings as mSetting;
use App\Pagename;
use App\Product;
use Illuminate\Http\Request;
use Vinkla\Instagram\Instagram;
use Cache;

class Home extends Controller
{
    function index(){
    	$data['carousel'] = mMedia::where(['media_page'=>'home','media_section'=>'carousel'])->orderBy('temp_id','asc')->get();
      $data['content'] = mGeneral::where(['general_page'=>'home','general_section'=>'content'])->first();
      $data['cards'] = mMedia::where(['media_page'=>'home','media_section'=>'card'])->orderBy('temp_id','asc')->get();
      $data['divider1'] = mGeneral::where(['general_page'=>'home','general_section'=>'divider1'])->first();
      $data['divider2'] = mGeneral::where(['general_page'=>'home','general_section'=>'divider2'])->first();
    	$data['banner1'] = mMedia::where(['media_page'=>'home','media_section'=>'banner-content1'])->first();
    	$data['banner2'] = mMedia::where(['media_page'=>'home','media_section'=>'banner-content2'])->first();
      $data['page'] = 'home';
      $data['featured'] = Product::where('is_featured', true)->get();
      $data['featured_heading'] = mGeneral::where(['general_page' => 'home', 'general_section' => 'featured-product'])->first();
      $page_id = Pagename::where('key','home')->first()->id;
      $data['meta_tags'] = Pagename::find($page_id)->meta_tags;
    	$data['banner_video'] = mMedia::firstOrCreate(['media_page' => 'home', 'media_section' => 'banner_video']);
      $data['instagram_media'] = $this->getMedia();

      // return $this->getMedia();

      return view('home')->with($data);
    }

    /**
     * Cache the pictures from instagram
     * with 5 that will last for 5 minutes..
     * 
     * @return array
     */
    public function getMedia()
    {
      return $data = Cache::remember('instagram', 5, function(){
        return $this->getInstagramMedia();
      });
    }

    /**
     * Get pictures from instagram.
     * 
     * @return array
     */
    public function getInstagramMedia()
    {
      $key = $this->getInstagramKey();

      if(!$key) return [];

      $ins = new Instagram($key);

      $pictures = $ins->get();

      $data = [];

      // foreach($pictures as $media)
      // {
      //   $data[] = $this->getUrl($media);
      // }

      return $pictures;
    }

    /**
     * Get picture url.
     * 
     * @param array $pirture
     * @return string
     */
    public function getUrl($media)
    {
      return $media->images->standard_resolution->url;
    }

    /**
     * Get instagram key.
     * 
     * @return string 
     */
    public function getInstagramKey()
    {
      return mSetting::firstOrCreate(['setting_name' => 'instagram-key'], ['setting_value' => ''])->setting_value;
    }
}
