<?php
namespace Clevercherry\Backslash4\Controllers;

use Illuminate\Support\Str;
use Illuminate\Support\Facades\Schema;

class Controller extends \App\Http\Controllers\Controller
{

    /**
     * Returns a template / content page view
     * @param array $params    presuming the last parametre is the {slug} $slug -- override in your model if necessary
     * @return type
     */
    public function view(...$params)
    {
        $modelName = Str::replaceLast('Controller', '', $this->basename());
        $appModel = '\\App\\Models\\'.$modelName;
        $viewName=Str::plural(strtolower($modelName)).'.view';
        
        $slug = !empty($appModel::$slugfield ?? null) ? $appModel::$slugfield : 'slug';
        if (!Schema::hasColumn((new $appModel)->getTable(), $slug)) {
            $slug = 'id';
        }

        if( method_exists($appModel, 'scopeActive')
            && (
                empty(Request()->preview) 
                || empty(($appModel)::allowPreviewAlgorithm()) 
                ||  (Request()->preview!=hash( ($appModel)::allowPreviewAlgorithm(), end($params)) ) )
            )
        {
            $item = ($appModel)::where($slug, end($params))->active()->first();
        } else
        {
            // preview param exists and matches the slug's hash so allow any pages
            $item = ($appModel)::where($slug, end($params))->first();
        }

        if(!$item)
        {  abort(404);
        }

        if((config('backslash4.tenants-on',0)!=0) && view()->exists('tenant::'.$viewName))
            return view('tenant::'.$viewName)->with('item', $item);
        //else

        if((config('backslash4.tenants-on',0)!=0) && view()->exists('tenant::generic.view'))
            return view('tenant::generic.view')->with('item', $item);
        //else

        if(view()->exists($viewName))
            return view($viewName)->with('item', $item);
        //else

        //app generic view
        if(view()->exists('generic.view'))
            return view('generic.view')->with('item', $item);

        return view('backslash4::generic.view')->with('item', $item);
    }

    /**
     * Returns the base class name of this object class model
     * @return String base class name
     */
    public function basename()
    {
        return (new \ReflectionClass($this))->getShortName();
    }    

}
