<?php
require_once('Models/FacilityDataSet.php');
require_once("Models/Paginator.php");

if(!isset($_GET['page'])) {
    header("location: ?page=0");
}

$filterArray = [
    0 => "",
    1 => "",
    2 => "",
    3 => "",
    4 => "",
    5 => "",
    6 => "",
    7 => "",
    8 => ""
];

$rowLimit = 5; //$_POST['rowCount'];

$facilityDataSet = new FacilityDataSet();

if (isset($_POST['applyFilters']) && isset($_POST['filter'])) {
    var_dump($_POST);
    $applyFilters = filter_input(INPUT_POST, 'applyFilters', FILTER_SANITIZE_STRING);
    $filterKey = filter_input(INPUT_POST, 'filter', FILTER_SANITIZE_STRING);
    $filterArray[$filterKey] = $applyFilters;
    // Set the filter and generate the new URI
    $filterSet = $facilityDataSet->setFilterUri($applyFilters, array_search($applyFilters, $filterArray));

    // Parse the existing query string
    parse_str($filterSet["newUri"], $queryParams);

    // Add or overwrite the 'page' parameter
    $queryParams['page'] = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, [
        'options' => ['default' => 0, 'min_range' => 0] // Default to 0 for the first page
    ]);

    // Build the updated query string
    $newQueryString = http_build_query($queryParams);

    // Redirect with the updated URI
    header("Location: {$filterSet["path"]}?{$newQueryString}");
    exit;
}


$filterArray[$_GET['category'] ?? null] = $_GET['term'] ?? null;

$view->pageData = $facilityDataSet->fetchAll($filterArray);
$view->paginator = new Paginator($rowLimit, $view->pageData);

// Initialize paginator
$view->pageNumber = $view->paginator->getPageFromUri();
$view->pageData = $view->paginator->getPage($view->pageNumber);

// Send result count to view
$view->dbMessage = $view->paginator->countPageResults($view->pageNumber) == 0
    ? "No results"
    : $view->paginator->countPageResults($view->pageNumber) . " result(s)";
