<?php

namespace App\Http\Controllers;

use App\Settings as mSetting;
use App\Media as mMedia;
use App\Pagename;
use App\PagenameLocale;
use Storage;
use Image;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Services\Uploader; #custom class

class BackendSettings extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    function index(){
      $data['companyLogo'] = mSetting::where(['setting_name'=>'companyLogo'])->first();
			$data['companyFavicon'] = mSetting::where(['setting_name'=>'companyFavicon'])->first();
    	$data['companyName'] = mSetting::where(['setting_name'=>'companyName'])->first();
    	$data['companyDesc'] = mSetting::where(['setting_name'=>'companyDesc'])->first();

    	$data['companyName'] = mSetting::where(['setting_name'=>'companyName'])->first();
    	$data['companyDesc'] = mSetting::where(['setting_name'=>'companyDesc'])->first();
    	$data['companyEmail'] = mSetting::where(['setting_name'=>'companyEmail'])->first();
    	$data['companyPhone'] = mSetting::where(['setting_name'=>'companyPhone'])->first();
    	$data['companyAddress'] = mSetting::where(['setting_name'=>'companyAddress'])->first();
      $data['compressionLevel'] = mSetting::where(['setting_name'=>'image-compression'])->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();

      $key = ['home'];

      if(!config('corepackage.lowcost.article')) {
        array_push($key, 'article');
      }
      if(!config('corepackage.catalog.activate')) {
        array_push($key, 'product');
      }
      if(!config('corepackage.lowcost.mentionsLegales')) {
        array_push($key, 'mentionsLegales');
      }
      $data['pageName'] = Pagename::whereNotIn('key',$key)->get();
    	$data['page'] = "settings";
    	return view('backend.settings')->with($data);
    }

    function saveprofile(Request $req){
      $nameId = $req->companyNameId;
      $descId = $req->companyDescId;
      $logoId = $req->companyLogoId;
      $faviconId = $req->companyFaviconId;
      $faviconVersion = $req->faviconVersion;
      $companyName = $req->companyName;
      $companyDesc = $req->companyDesc;

      $this->validate($req, [
        'companyFavicon'=> 'mimes:ico|max:50|dimensions:min_width=32,min_height=32',
        'companyLogo'=> 'mimes:png,jpeg,jpg|max:500|dimensions:min_width=200,min_height=200',
        'companyName' => 'required',
        'companyDesc' => 'required',
      ]);

      $timestamp = str_replace([' ', ':', '-'], '', Carbon::now()->toDateTimeString());

      # If new image uploaded
      if($req->companyLogo) {
        $x = explode('.',$req->companyLogo->getClientOriginalName());
        $ext = array_last($x);
        $imageName = 'logo'.$timestamp.'.'.$ext;

        #### SAVE IMAGE
        $req->file('companyLogo')->storeAs(
            'img/', $imageName
        );

        $db = mSetting::where('setting_name','companyLogo')->first();
        $url = 'img/'.$db->setting_value;
        Storage::delete($url);

        $db->setting_value = $imageName;
        $db->save();

      }

      if($req->companyFavicon):
        $x = explode('.',$req->companyFavicon->getClientOriginalName());
        $ext = array_last($x);
        $imageName = 'favicon'.$timestamp.'.'.$ext;

        #### SAVE IMAGE
        $req->file('companyFavicon')->storeAs(
            'img/', $imageName
        );

        $filename = mSetting::where('setting_name','companyFavicon')->first();
        $url = 'img/'.$filename->setting_value;
        Storage::delete($url);

        $db = mSetting::find($faviconId);
        $db->setting_value = $imageName;
        $db->setting_desc = 'v='.($faviconVersion+1);
        $db->save();
      endif;

      $db = mSetting::find($nameId);
      $db->setting_value = $companyName;
      $db->save();

      $db = mSetting::find($descId);
      $db->setting_value = $companyDesc;
      $db->save();

      $db = mSetting::where('setting_name', 'logoSetting')->first();
      $db->setting_value = $req->logoSetting ? 'yes' : 'no';
      $db->save();

      $db = mSetting::where('setting_name', 'nameSetting')->first();
      $db->setting_value = $req->nameSetting ? 'yes' : 'no';
      $db->save();

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

      return back();
    }


    function save_color(Request $req){
      ## MAIN COLOR
      $color = $req->color;
      $idcolor = $req->idcolor;

      $save = implode('|',$color);
      $db = mSetting::find($idcolor);
      $db->setting_value = $save;
      $db->save();

      ## BUTTON COLOR
      $color = $req->btn_color;
      $idcolor = $req->idbtncolor;

      $save = implode('|',$color);
      $db = mSetting::find($idcolor);
      $db->setting_value = $save;
      $db->save();

      ## TEXT ON BANNER COLOR
      $color = $req->text_onbanner;
      $idcolor = $req->idtxtbannercolor;

      $save = $color;
      $db = mSetting::find($idcolor);
      $db->setting_value = $save;
      $db->save();

      ## NAVBAR / DIVIDER / CARD COLOR
      $color = $req->panel_color;
      $idcolor = $req->idnavbarcolor;

      $save = implode('|',$color);
      $db = mSetting::find($idcolor);
      $db->setting_value = $save;
      $db->save();

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

    	return back();
      // return $save;
    }

    function save_page_name(Request $req){
    	$pagename = $req->pagename;

      foreach($pagename as $id => $content){
        $main_locale = config('app.fallback_locale');
        $db = Pagename::find($id);
        $db->slug = str_slug($content[$main_locale]);
        $db->save();
        foreach($content as $locale => $value){
          $data = Pagename::find($id)->locales()->where('locale',$locale)->first();
          if(empty($data->id)){
            # create
            $db = new PagenameLocale;
            $db->pagename_id = $id;
            $db->locale = $locale;
            $db->page_name = $value;
            $db->save();
          }else{
            # update
            $db = PagenameLocale::find($data->id);
            $db->page_name = $value;
            $db->save();
          }
        }
      }

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

    	return back();
    }

    function page_publish(Request $req){
      $page = $req->page;
      $stat = $req->stat;
      $id = mSetting::where(['setting_name'=>'publishPage'])->first()->id;
      $content = explode('|',mSetting::where(['setting_name'=>'publishPage'])->first()->setting_value);

      $db = mSetting::find($id);
      if($page == "section1"):
        $db->setting_value = $stat.'|'.$content[1];
      else:
        $db->setting_value = $content[0].'|'.$stat;
      endif;
      $db->save();

      $data = [
        'page'=>$page,
        'stat'=>$stat
      ];

      return json_encode($data);
    }

    function savefont(Request $req){
      $fonts = $req->fontselect;
      $id = mSetting::where(['setting_name'=>'webFont'])->first()->id;

      $save = implode('|',$fonts);
      $db = mSetting::find($id);
      $db->setting_value = $save;
      $db->save();

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

    	return back();
    }

    function save_currency(Request $req){
      $code = $req->select_currency;
      $currency = mSetting::where('setting_name','currency')->first();

      if(empty($currency)){
        # CREATE
        $db = new mSetting;
        $db->setting_name = "currency";
        $db->setting_value = $code;
        $db->setting_desc = "Main Currency";
        $db->save();
      }else{
        # UPDATE
        $id = $currency->id;
        $db = mSetting::find($id);
        $db->setting_value = $code;
        $db->save();
      }

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

    function updateRedirection(Request $req)
    {
      $banner1 = mMedia::findOrFail($req->id1);
      $banner1->media_target = $req->redirect1;
      $banner1->save();

      $banner2 = mMedia::findOrFail($req->id2);
      $banner2->media_target = $req->redirect2;
      $banner2->save();

      flash('Update Succesfully!!')->success();
      return redirect (route('backendSettings'));
    }

    public function updateAdvanced(Request $req)
    {
      $compressionLevel = mSetting::firstOrCreate(['setting_name' => 'image-compression']);
      $compressionLevel->setting_value = $req->compression;
      $compressionLevel->save();

      flash('Update Succesfully!!')->success();
      return redirect (route('backendSettings'));
    }

    public function updateSitemap(Request $req)
    {
      $this->validate($req, [
          'sitemap_file' => 'required|mimes:xml',
      ]);

      $req->file('sitemap_file')->storeAs(
          '/', 'sitemap.xml', 'root'
      );

      flash('Update Succesfully!')->success();
      return redirect (route('backendSettings'));
    }

    public function updateMtMode(Request $request)
    {
      $db = mSetting::firstOrCreate(['setting_name' => 'maintenace-mode']);

      if($request->mode === 'on') {
        $db->setting_value = 1;
      } else {
        $db->setting_value = 0;
      }

      $db->save();

      flash('Update Succesfully!')->success();
      return redirect (route('backendSettings'));
    }
}
