<?php

namespace App\Http\Controllers\CMS;


use App\Http\Controllers\Controller;
use App\Models\CMSContent;
use Input;
use Request;
use Validator;


class CMSContentController extends Controller
{

/*
* Create a new controller instance.
*
* @return void
*/
    public function __construct()
    {
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = [
            'contents' => CMSContent::all()->sortByDesc('id')
        ];
        return view('cms.content.index', $data);

    }


    public function store()
    {
        $data = Input::all();
        $rules = array(
            'name' => 'required',
            'field' => 'required',
        );
        $validator = Validator::make(Input::all(), $rules);

        if ($validator->fails()) {
            return back()->withErrors($validator);
        }

        if($data['id'] == "new"){
            CMSContent::create($data);
        }else{
            $model = CMSContent::find($data['id']);
            $model->fill($data);
            $model->save();
        }
        \Session()->flash('alert-save', '1');
        return redirect(route('cms_content'));
    }


    public function loadModal()
    {
        if(Request::ajax()){
            $data = Input::all();
            $returnHTML = "";
            if(isset($data['model']) && isset($data['id']) ){
                if($data['model'] == 'content'){
                    if($data['id'] == "new"){
                        $value = new CMSContent();
                    }else {
                        $value = CMSContent::find($data['id']);
                    }
                    $returnHTML =  view("cms.content.modal", compact('data','value') )->render();
                }

            }
            return response()->json(['response' =>  $data, 'html'=>$returnHTML]);
        }
    }



    public function delete($id){
        $content = CMSContent::findOrFail($id);
        $content->delete();
        \Session()->flash('alert-success', __('Content gelöscht'));
        return redirect(route('cms_content'));
    }




}
