<?php
/*
 * Copyright (c)  2006-2008 Maskat Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require_once("../lib/maskat.php");
require_once("./common.php");

header("Content-Type: text/plain;charset=UTF-8");

/* コード表の要求元に応じてデータソースの配列を設定 */
if (isset($_REQUEST["customerIdText"])) {
  $store = find_all_customers();
  $code = "id";
  $label = "name";
  $query = utf8_urldecode($_REQUEST["customerIdText"]);
} else if (isset($_REQUEST["productIdText"])) {
  $store = find_all_products();
  $code = "id";
  $label = "name";
  $query = utf8_urldecode($_REQUEST["productIdText"]);
}

/* 検索文字列を用いてコード表を絞り込む (未指定の場合はすべて表示) */
$codelist = array();
foreach ($store as $item) {
  if ($query == null or
      !(strpos($item[$code], $query) === false) or
      !(strpos($item[$label], $query) === false)) {
    array_push($codelist, '["' . $item[$code] . '","' . $item[$label] . '"]');
  }
}

/* JSON フォーマットでコード表を返却 */
echo "[" . join($codelist, ",\n") . "]\n"
?>