<?php

namespace App\Http\Controllers;

use App\Media as mMedia;
use App\MediaLocale as mMediaLocale;
use App\General as mGeneral;
use App\GeneralLocale as mGeneralLocale;
use App\Http\Services\Uploader; #custom class
use App\Product;
use App\Pagename;
use App\Settings as mSetting;

use Storage;
use Image;
use File;
use Carbon\Carbon;
use Illuminate\Http\Request;

class BackendHome extends Controller
{
    public function getMedia($section)
    {
        return mMedia::firstOrCreate(['media_page' => 'home', 'media_section' => $section]);
    }

    public function getGeneral($section)
    {
        return mGeneral::firstOrCreate(['general_page'=>'home','general_section'=> $section]);
    }
    
    public function __construct()
    {
        $this->middleware('auth');
    }

    function index(Request $req){
    	$data['carousel'] = mMedia::where(['media_page'=>'home','media_section'=>'carousel'])->orderBy('temp_id','asc')->get();
      $data['cards'] = mMedia::where(['media_page'=>'home', 'media_section'=>'card'])->orderBy('temp_id','asc')->get();
      $data['content'] = $this->getGeneral('content');
    	$data['divider1'] = $this->getGeneral('divider1');
    	$data['divider2'] = $this->getGeneral('divider2');
    	$data['banner1'] = $this->getMedia('banner-content1');
    	$data['banner2'] = $this->getMedia('banner-content2');
      $data['featured_product'] = $this->getGeneral('featured-product');
      $data['featured'] = Product::where('is_featured', true)->get();
      $data['page'] = 'home';
      $data['banner_video'] = $this->getMedia('banner_video');
      $data['instagram_key'] = $this->getInstagramKey();

      if((config('corepackage.catalog.activate') == 'yes') && (config('corepackage.article.activate') == 'yes')) {
        $data['pages'] = Pagename::whereNotIn('key',['home'])->get();
      } elseif(config('corepackage.catalog.activate') == 'yes') {
        $data['pages'] = Pagename::whereNotIn('key',['home','article'])->get();
      } else {
        $data['pages'] = Pagename::whereNotIn('key',['home','product'])->get();
      }
      // return Pagename::with('translations')->get();
    	return view('backend.home')->with($data);
    }

    function save_carousel(Request $req){
      $id = $req->carousel_id;
      $title = $req->imagetitle;
      $alt = $req->imagealt;

      if(empty($id)) {
        $this->validate($req, [
            'image' => 'required',
        ]);

        # Make new database model
        $db = new mMedia;

        # Get the total of existing record for order purpose
        $order = mMedia::where(['media_page'=>'home','media_section'=>'carousel'])->count();
        $db->temp_id = $order+1;

      } else {

        # Update existing record
        $db = mMedia::find($id);

      }

      # Get the old image name incase no image uploaded
      $imageName = $db->media_url;

      # If new image uploaded
      if($req->image) {

        # Save new image
        $imageName = Uploader::SaveImage($req->image, 'carousel_', 'img/home/', $alt[app()->getLocale()]);

        # Delete old image if new one uploaded
        if($db->media_url!=''){
          Storage::delete('/img/home/'.$db->media_url);
        }
      }

      # Insert rquired data
      $db->media_url = $imageName;
      $db->media_page = "home";
      $db->media_section = "carousel";

      # Save model into database
      $db->save();

      # Saving translation
      foreach (config('translatable.locales') as $lang => $language) {

        # Check if translation is available
        $data = $db->locales()->where('locale',$lang)->first();
        if(empty($data)){
          # Create new translation model
          $translation = new mMediaLocale;
          $translation->media_id = $db->id;
          $translation->locale = $lang;
        }else{
          # Update existing translation model
          $translation = mMediaLocale::find($data->id);
        }

        # Insert translation data
        $translation->media_title = $title[$lang];
        $translation->media_content = $alt[$lang];
        # Save changes
        $translation->save();
      }

    	$req->session()->flash('message-carousel', 'Uploaded successfully!');
  		$req->session()->flash('alert-class', 'alert-success');
  		$req->session()->flash('anchor', '#message-carousel');

  		return back();
    }

    function order_carousel(Request $req){
      $order = $req->reorder;

      foreach($order as $key => $val){
        $db = mMedia::find($val);
        $db->temp_id = $key+1;
        $db->save();
      }

      $req->session()->flash('message-carousel', 'Carousel rearranged!');
  		$req->session()->flash('alert-class', 'alert-success');
  		$req->session()->flash('anchor', '#message-carousel');

  		return back();
    }

    function delete_carousel(Request $req){
        $db = mMedia::find($req->id);
        # Delete old image if new one uploaded
        if($db->media_url!=''){
          Storage::delete('/img/home/'.$db->media_url);
        }

        $locales = $db->locales;
        # delete the locales
        if(!empty($locales)){
          foreach ($locales as $key => $value) {
            mMediaLocale::find($value->id)->delete();
          }
        }

        # delete the main data
        $db->delete();

        return back();
    }

    function save_content(Request $req){
      $id = $req->id;
      $title = $req->title;
      $text = $req->text;

      foreach (config('translatable.locales') as $lang => $language) {
        $data = mGeneral::find($id)->locales()->where('locale',$lang)->first();
        if(empty($data->id)){
          # create
          $db = new mGeneralLocale;
          $db->general_id = $id;
          $db->locale = $lang;
        }else{
          # update
          $db = mGeneralLocale::find($data->id);
        }

        $db->general_title = $title[$lang];
        $db->general_content = $text[$lang];
        $db->save();
      }

      $req->session()->flash('message-home-content', 'Updated successfully!');
  		$req->session()->flash('alert-class', 'alert-success');
  		$req->session()->flash('anchor', '#message-home-content');

  		return back();
    }

    function save_featured_heading(Request $req){
      $id = $req->id;
      $title = $req->title;

      foreach (config('translatable.locales') as $lang => $language) {
        $data = mGeneral::find($id)->locales()->where('locale',$lang)->first();
        if(empty($data->id)){
          # create
          $db = new mGeneralLocale;
          $db->general_id = $id;
          $db->locale = $lang;
        }else{
          # update
          $db = mGeneralLocale::find($data->id);
        }
        $db->general_title = $title[$lang];
        $db->save();
        // return $db;
      }

      $req->session()->flash('message-home-featured', 'Updated successfully!');
  		$req->session()->flash('alert-class', 'alert-success');
  		$req->session()->flash('anchor', '#message-home-featured');

  		return back();
    }

    function save_divider(Request $req){
    	$id1 = $req->id1;
    	$id2 = $req->id2;
    	$divider1 = $req->divider1;
    	$divider2 = $req->divider2;

      $div1 = mGeneral::findOrFail($id1);
      $div1->general_url = $req->select_divider1;
      $div1->save();
      
      $div2 = mGeneral::findOrFail($id2);
      $div2->general_url = $req->select_divider2;
      $div2->save();


      # DIVIDER 1
      foreach (config('translatable.locales') as $lang => $language) {
        $locale = mGeneralLocale::where(['locale'=>$lang,'general_id'=>$id1])->first();
        if(empty($locale)){
          # DIVIDER 1 CREATE
          $db = new mGeneralLocale;
          $db->locale = $lang;
          $db->general_id = $id1;
          $db->general_content = $divider1[$lang];
          $db->save();
        }else{
          # DIVIDER 1 UPDATE
          $db = mGeneralLocale::find($locale->id);
          $db->general_content = $divider1[$lang];
          $db->save();
        }
      }

      # DIVIDER 2
      foreach (config('translatable.locales') as $lang => $language) {
        $locale = mGeneralLocale::where(['locale'=>$lang,'general_id'=>$id2])->first();
        if(empty($locale)){
          # DIVIDER 2 CREATE
          $db = new mGeneralLocale;
          $db->locale = $lang;
          $db->general_id = $id2;
          $db->general_content = $divider2[$lang];
          $db->save();
        }else{
          # DIVIDER 2 UPDATE
          $db = mGeneralLocale::find($locale->id);
          $db->general_content = $divider2[$lang];
          $db->save();
        }
      }

    	$req->session()->flash('message-divider', 'Updated successfully!');
  		$req->session()->flash('alert-class', 'alert-success');
  		$req->session()->flash('anchor', '#message-divider');

  		return back();
    }

    function save_banner(Request $req){
    	$type = $req->bannertype;
    	$id = $req->bannerid;
      // return $req->all();
    	if($type=='banner1') {

        $title = $req->title_banner1;
        $content = $req->content_banner1;
        $alt = $req->imagealt1;

      } else {

        $title = $req->title_banner2;
        $content = $req->content_banner2;
        $alt = $req->imagealt2;

      }

      # Find the banner model
      $db = mMedia::find($id);
      # Get the old image name incase no image uploaded
      $imageName = $db->media_url;

      # If new image uploaded
      if($req->image) {

        # Save uploaded image
        $imageName = Uploader::SaveImage($req->image, $type.'_', 'img/home/', $alt[app()->getLocale()]);

        # Delete old image if new one uploaded
        if($db->media_url!=''){
          Storage::delete('/img/home/'.$db->media_url);
        }
      }

      # Insert rquired data
      $db->media_url = $imageName;

      # Save model into database
      $db->save();

      # Saving translation
      foreach (config('translatable.locales') as $lang => $language) {

        # Check if translation is available
        $data = $db->locales()->where('locale',$lang)->first();
        if(empty($data)){
          # Create new translation model
          $translation = new mMediaLocale;
          $translation->media_id = $id;
          $translation->locale = $lang;
        }else{
          # Update existing translation model
          $translation = mMediaLocale::find($data->id);
        }

        # Insert translation data
        $translation->media_title = $title[$lang];
        $translation->media_content = $content[$lang];
        $translation->media_desc = $alt[$lang];
        # Save changes
        $translation->save();
      }

    	$req->session()->flash('message-'.$type, 'Updated successfully!');
  		$req->session()->flash('alert-class', 'alert-success');
  		$req->session()->flash('anchor', '#message-'.$type);

      return back();
    }

    function save_card(Request $req){
      $id = $req->card_id;
      $title = $req->cardtitle;
      $content = $req->cardcontent;
      $alt = $req->imagealt;

      // return $req->all();

      if(empty($id)) {
        $this->validate($req, [
            'image' => 'required',
        ]);

        # Make new database model
        $db = new mMedia;

        # Get the total of existing record for order purpose
        $order = mMedia::where(['media_page'=>'home','media_section'=>'card'])->count();
        $db->temp_id = $order+1;

      } else {

        # Update existing record
        $db = mMedia::find($id);

      }

      # Get the old image name incase no image uploaded
      $imageName = $db->media_url;

      # If new image uploaded
      if($req->image) {

        # Save uploaded image
        $imageName = Uploader::SaveImage($req->image, 'card_', 'img/home/', $alt[app()->getLocale()]);

        # Delete old image if new one uploaded
        if($db->media_url!=''){
          Storage::delete('/img/home/'.$db->media_url);
        }
      }

      # Insert rquired data
      $db->media_url = $imageName;
      $db->media_page = "home";
      $db->media_section = "card";

      # Save model into database
      $db->save();

      # Saving translation
      foreach (config('translatable.locales') as $lang => $language) {

        # Check if translation is available
        $data = $db->locales()->where('locale',$lang)->first();
        if(empty($data)){
          # Create new translation model
          $translation = new mMediaLocale;
          $translation->media_id = $db->id;
          $translation->locale = $lang;
        }else{
          # Update existing translation model
          $translation = $data;
        }

        # Insert translation data
        $translation->media_title = $title[$lang];
        $translation->media_content = $content[$lang];
        $translation->media_desc = $alt[$lang];
        # Save changes
        $translation->save();
      }

    	$req->session()->flash('message-card', 'Uploaded successfully!');
  		$req->session()->flash('alert-class', 'alert-success');
  		$req->session()->flash('anchor', '#message-card');

      // return mMedia::with('translations')->find($id);

  		return back();
    }

    function order_card(Request $req){
      $order = $req->reorder;

      foreach($order as $key => $val){
        $db = mMedia::find($val);
        $db->temp_id = $key+1;
        $db->save();
      }

      $req->session()->flash('message-card', 'Cards rearranged!');
  		$req->session()->flash('alert-class', 'alert-success');
  		$req->session()->flash('anchor', '#message-card');

  		return back();
    }

    function delete_card(Request $req){
      $db = mMedia::find($req->id);

      # Delete old image
      if($db->media_url!=''){
        Storage::delete('/img/home/'.$db->media_url);
      }

      # locales
      $db->locales;
      if(!empty($locales)){ # check if there's locales data
        foreach ($locales as $key => $value) {
          # deleting locales data
          mMediaLocale::find($value->id)->delete();
        }
      }

      # deleting main data
      $db->delete();

      $req->session()->flash('anchor', '#message-card');
      return back();
    }

    public function updateHomeBanner(Request $req)
    {
      $db = mSetting::firstOrCreate(['setting_name' => 'home-banner']);
      $db->setting_value = $req->home_banner;
      $db->save();

      return redirect()->route('backendHome');
    }

    public function saveVideo(Request $request) 
    {
        if($request->media) {
          $db = mMedia::updateOrCreate(['media_page'=>'home','media_section'=>'banner_video']);
          $request->file('media')->storeAs('video', 'video.mp4');
          
          $file = storage_path() . '/app/public/img/home/' . $db->media_url;
  
          if(File::isFile($file)) {
              File::delete($file);
          }
  
          $ext = array_last(explode('.',$request->media->getClientOriginalName()));
          $uni = uniqid();
          $name = "video_$uni.$ext";
  
          #### SAVE IMAGE
          $request->file('media')->storeAs(
              '/img/home/', $name
          );

          $db->media_url = $name;
          $db->save();
        }

        
        return redirect()->route('backendHome');
    }

    /**
     * Save instagram options.
     * 
     * @param Request $request
     */
    public function saveInstagram(Request $request)
    {
      mSetting::updateOrCreate(['setting_name' => 'instagram-key'], ['setting_value' => $request->token]);
      mSetting::updateOrCreate(['setting_name' => 'home-instagram-limit'], ['setting_value' => $request->limit]);

      if($request->show === 'on') {
        mSetting::updateOrCreate(['setting_name' => 'home-instagram'], ['setting_value' => 1]);
      } else {
        mSetting::updateOrCreate(['setting_name' => 'home-instagram'], ['setting_value' => 0]);
      }

      return redirect()->route('backendHome');
      
    }

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

}
