<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Models\Location;

class FrontIndexController extends Controller
{
    private $limit = 15;

    public function start()
    {
        $locations = Location::where("active", true)->get();
        $count     = count($locations);

        $terms = "no|agenda";

        //$result = DB::select("SELECT * FROM searchlocations('$terms')");

        return view('front.index', [
            'count' => $count,
            'title' => "The Bad Space"
        ]);
    }

    public function listings(int $pageNum = 1)
    {
        $range     = $pageNum * $this->limit - $this->limit;
        $active    = Location::where("active", true)->get();
        $locations = Location::where("active", true)
            ->limit($this->limit)->offset($range)->orderByDesc('id')->get();
        $pageCount = ceil(count($active) / $this->limit);

        $next = $pageNum + 1;
        if ($next > $pageCount) {
            $next = 1;
        }

        $prev = $pageNum - 1;

        if ($prev <= 0) {
            $prev = $pageCount;
        }

        return view('front.listing', [
            'title'      => "Listings",
            "totalPages" => $pageCount,
            "prev"       => $prev,
            "next"       => $next,
            'pageNum'    => $pageNum,
            'locations'  => $locations
        ]);
    }
}