<?php

namespace App\Http\Controllers;

use App\Settings as mSetting;
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 BackendAbout extends Controller
{
    public function getMedia($section)
    {
        return mMedia::firstOrCreate(['media_page' => 'about', 'media_section' => $section]);
    }

    public function getGeneral($section)
    {
        return mGeneral::firstOrCreate(['general_page'=>'about','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(){
			$data['companyLogo'] = $this->getSetting('companyLogo');
			$data['companyFavicon'] = $this->getSetting('companyFavicon');
    	$data['companyName'] = $this->getSetting('companyName');
    	$data['companyDesc'] = $this->getSetting('companyDesc');

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

    	$data['page'] = "about";
    	return view('backend.about')->with($data);
    }

    function save_banner(Request $req){
      $id = $req->id;
      $alt = $req->imagealt;

      if(empty($id)) { # Make new model if $id is empty

        $this->validate($req, [
            'image' => '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/about/', $alt[app()->getLocale()]);

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

      # Insert rquired data
      $db->media_url = $imageName;
      $db->media_page = 'about';
      $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_desc = $alt[$lang];
        # Save changes
        $translation->save();
      }

      $req->session()->flash('message-banner', 'Uploaded 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;
      $content = $req->text_content;
      $alt = $req->imagealt;
      $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'=>'about','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 new image uploaded
      if ($type=="image") {

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

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

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

      } elseif($type=="video") {
        $mediaUrl = $req->media_url;
        if($db->media_type=="image"&&$db->media_url!=''){
          Storage::delete('/img/about/'.$db->media_url);
        }
      } else {
        $mediaUrl = $req->album;
        if($db->media_type=="image"&&$db->media_url!=''){
          Storage::delete('/img/about/'.$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 = "about";
      $db->media_section = "content";
      $db->media_desc = "About 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{
          # Find 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){
        $id = $req->id;

        $filename = mMedia::where('id',$id)->first();
        $url = '/img/about/'.$filename->media_url;

        if($filename->media_url){
          Storage::delete($url);

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

        mMedia::find($id)->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();
    }
}
