<?php
namespace Clevercherry\Backslash4\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use App\Models\Addresses;

class AddressController extends Controller
{
    /**
     * Returns the index page view
     * @return type
     */
    public function index()
    {
        $items = Addresses::active()->get();

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

        if(view()->exists('addresses.index'))
            return view('addresses.index')->with('items', $items);
        //else

        return view('backslash4::addresses.index')->with('items', $items);

    }
 
    /**
     * 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)
    {
        if( empty(Request()->preview) 
            || empty( Addresses::allowPreviewAlgorithm()) 
            ||  (Request()->preview!=hash(  Addresses::allowPreviewAlgorithm(), end($params)) ) )
        {
            $item = Addresses::where('slug', end($params))->active()->first();
        } else
        {
            // preview param exists and matches the slug's hash so allow any pages
            $item = Addresses::where('slug', end($params))->first();
        }

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

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

        if(view()->exists('addresses.view'))
            return view('addresses.view')->with('item', $item);

        if(view()->exists('generic.view')) {
            return view('generic.view')->with('item', $item);
        }
        //else
    
        return view('backslash4::generic.view')->with('item', $item);
    }
}
