<?php

namespace App\Http\Controllers;

use App\Media as mMedia;
use App\MediaLocale as mMediaLocale;
use Storage;
use Image;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Services\Uploader; #custom class

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

    public function getGeneral($page, $section)
    {
        return mGeneral::firstOrCreate(['general_page'=> $page,'general_section'=> $section]);
    }

    public function getSetting($name, $default = '')
    {
        return mSetting::firstOrCreate(['setting_name' => $name], ['setting_value' => $default]);
    }

    public function __construct()
    {
        $this->middleware('auth');
    }

    function index($section){
    	$data['page'] = $section;

    	$data['banner'] = $this->getMedia($section, 'banner-header');
    	$data['contents'] = mMedia::where(['media_page'=>$section,'media_section'=>'content'])->orderBy('temp_id','asc')->get();

    	return view('backend.sections')->with($data);
    }

    function save_banner(Request $req){
    	$section = $req->section_name;
    	$id = $req->id;
      $caption = $req->banner_caption;
      $alt = $req->imagealt;

      if(empty($id)) { # Make new model if $id is empty
        $this->validate($req, [
            'image' => 'required',
            'banner_caption' => 'required'
        ]);

        # Make new database model
        $db = new mMedia;

      } 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, 'banner_', 'img/sections/', $alt[app()->getLocale()]);

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

      # Insert rquired data
      $db->media_url = $imageName;
      $db->media_page = $section;
      $db->media_section = "banner-header";

      # 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 = $caption[$lang];
        $translation->media_desc = $alt[$lang];
        # Save changes
        $translation->save();
      }

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

  		return back();
    }

    function save_content(Request $req){
    	$id = $req->id;
    	$title = $req->title_content;
      $alt = $req->imagealt;
    	$content = $req->text_content;
    	$section = $req->section;
      $type = $req->media_type;

    	if(empty($id)) { # Make new model if $id is empty
        $this->validate($req, [
            'text_content' => 'required',
        ]);

        # Make new database model
        $db = new mMedia;

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

      } else {

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

      }

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

      # If media type is image
      if ($type=="image") {

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

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

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

      } elseif($type=="video") {
        $mediaUrl = $req->media_url;
        if($db->media_type=="image"&&$db->media_url!=''){
          Storage::delete('/img/sections/'.$db->media_url);
        }
      } else {
        $mediaUrl = $req->album;
        if($db->media_type=="image"&&$db->media_url!=''){
          Storage::delete('/img/sections/'.$db->media_url);
        }
      }


      # Insert rquired data
      $db->media_type = $type;
      $db->media_url = $mediaUrl;
      $db->media_title = $title[config('app.locale')];
      $db->media_content = $content[config('app.locale')];
      $db->media_page = $section;
      $db->media_section = "content";
      $db->media_desc = ucfirst($section)." Content";

      # 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 = $content[$lang];
        $translation->media_desc = $alt[$lang];
        # Save changes
        $translation->save();
      }

  	if(empty($id)){
    		$req->session()->flash('message-content', 'Added successfully!');
    	}else{
    		$req->session()->flash('message-content', 'Updated successfully!');
  	}

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

		return back();
    }

    function delete_content(Request $req){

      # Find model
      $db = mMedia::find($req->id);
      # Delete image if exists
      if($db->media_url!=''){
        Storage::delete('/img/sections/'.$db->media_url);
      }

      # Delete translations
      foreach(config('translatable.locales') as $lang => $language){
        $db->locales()->where('locale',$lang)->first();
        if(!empty($get)){
          mMediaLocale::find($get->id)->delete();
        }
      }

      # Delete model
      $db->delete();

      return back();
    }

    function order_content(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-content', 'Content rearranged!');
  		$req->session()->flash('alert-class', 'alert-success');
  		$req->session()->flash('anchor', '#message-content');

  		return back();
    }
}
