<?php

const ITEMS_PER_PAGE = 50;

// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// include database and object files
include_once '../../config/database.php';
include_once '../objects/gallery_item.php';
include_once '../objects/user.php';
include_once '../objects/like.php';
include_once '../authenticator.php';

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    // CORS Pre-flight request
    header("Access-Control-Allow-Headers: origin, content-type, accept, authentication");
    http_response_code(200);
    exit();
} else if ($_SERVER['REQUEST_METHOD'] != 'GET') {
    http_response_code(400);
    echo json_encode(array("error" => "Method not accepted."));
    exit();
}

// get params
$page = 0;
if (isset($_GET["page"])) {
    if (!is_int($_GET["page"])) {
        http_response_code(400);
    }
    $page = $_GET["page"];
}
$id = null;
if (isset($_GET['id'])) {
    if (!is_int($_GET["id"])) {
        http_response_code(400);
    }
    $id = $_GET["id"];
}

// instantiate database and product object
$database = new Database();
$db = $database->getConnection();

$auth = new Authenticator($db);
$uid = $auth->authenticate();

// query products
if ($id)
    $stmt = GalleryItem::readById($db, $uid, $id);
else
    $stmt = GalleryItem::read($db, $uid, $page, ITEMS_PER_PAGE);

// products array
$gi_arr=array();
$gi_arr["records"]=array();
$gi_arr["page"]=$page;
$gi_arr["more"]=FALSE;

// retrieve our table contents
// fetch() is faster than fetchAll()
// http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
$count = 0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $count++;

    $gallery_item = GalleryItem::fromRow($row);

    if ($count <= ITEMS_PER_PAGE) {
        array_push($gi_arr["records"], $gallery_item);
    } else {
        $gi_arr["more"] = TRUE;     // If the query returns one more element than ITEMS_PER_PAGE, there is at least another page
    }
}

// set response code - 200 OK
http_response_code(200);

// show products data in json format
echo json_encode($gi_arr);
