<?php
/**
 * This script prints tags of a page in a json
 * @author Rihards Silins <rihards.silins@mtcmedia.co.uk>
 * @version 1 02/11/2016
 */

$cms_root_path = "../../../";
require_once($cms_root_path."includes/compatibility_includer.php");

use Mtc\Cms\Models\PageListItemData;

$search_text = "%";
if (!empty($_GET['term'])) {
    $search_text = $_GET['term'] . "%";
}

$tag_pagedata_name = "Tag";
if (!empty($_GET['tag_pagedata_name'])) {
    $tag_pagedata_name = $_GET['tag_pagedata_name'];
}

$builder = PageListItemData::where("varchar_value", "LIKE", $search_text)
    ->where("name", $tag_pagedata_name)
    ->orderBy("varchar_value")
    ->groupBy("varchar_value");

if (!empty($_GET['page_id']) && is_numeric($_GET['page_id'])) {
    $builder = $builder->where("page_id", "!=", $_GET['page_id']);
}

$tag_list = $builder->get(["varchar_value"])->toArray();

$result = array();
foreach ($tag_list as $tag) {
    $result[] = [
        'id'    => $tag['varchar_value'],
        'label' => $tag['varchar_value'],
        'value' => $tag['varchar_value'],
    ];
}

die(json_encode($result));
