<?php
function OutputIconPageHeader(){
  OutputHTMLHeader('ユーザアイコン一覧', 'icon_view');
  echo <<<HTML
</head>
<body>
<a href="./">←ホームページに戻る</a><br>
<img class="title" src="img/icon_view_title.jpg"><br>
<div class="link"><a href="icon_upload.php">→アイコン登録</a></div>

HTML;
}

function OutputIconList($base_url = 'icon_view'){
  global $RQ_ARGS;
  //編集フォームの表示
  if($RQ_ARGS->icon_no > 0){
    $params = $RQ_ARGS->ToArray();
    unset($params['icon_no']);
    echo <<<HTML
<div class="link"><a href="icon_view.php">→アイコン一覧に戻る</a></div>
<form action="icon_edit.php" method="POST">
<fieldset><legend>アイコン設定の変更</legend>

HTML;
    OutputIconEditForm($RQ_ARGS->icon_no);
    echo <<<HTML
</fieldset>
</form>

HTML;
  }
  elseif ($base_url == 'icon_view') {
    echo <<<HTML
<form method="GET">
<fieldset><legend>ユーザアイコン一覧</legend>

HTML;
    ConcreteOutputIconList($base_url);
    echo <<<HTML
</fieldset>
</form>

HTML;
  }
  else {
    ConcreteOutputIconList($base_url);
  }
}

function OutputIconEditForm($icon_no) {
  global $ICON_CONF, $USER_ICON, $RQ_ARGS;
  foreach(FetchAssoc("SELECT * FROM user_icon WHERE icon_no = {$icon_no}") as $selected) {
    extract($selected, EXTR_PREFIX_ALL, 'selected');
    $location = $ICON_CONF->path . '/' . $selected_icon_filename;
    echo <<<EOF
<form method="POST" action="icon_edit.php">
<input type="hidden" name="icon_no" value="{$selected_icon_no}">
<table>
<tr><td rowspan="6"><img src="{$location}"></td>
<td><label>アイコンの名前</label></td>
<td><input type="text" name="icon_name" maxlength="{$icon_name_length_max}" size="{$icon_name_length_max}" value="{$selected_icon_name}"></td></tr>

<tr><td><label>出典</label></td>
<td><input type="text" name="appearance" maxlength="{$icon_name_length_max}" size="{$icon_name_length_max}" value="{$selected_appearance}"></td></tr>

<tr><td><label>カテゴリ</label></td>
<td><input type="text" name="category" maxlength="{$icon_name_length_max}" size="{$icon_name_length_max}" value="{$selected_category}"></td></tr>

<tr><td><label>アイコンの作者</label></td>
<td><input type="text" name="author" maxlength="{$icon_name_length_max}" size="{$icon_name_length_max}" value="{$selected_author}"></td></tr>

<tr><td><label>アイコン枠の色</label></td>
<td><input type="text" name="color" size="10px" maxlength="7" value="{$selected_color}"> (例：#6699CC)</td></tr>

<tr><td><label>編集パスワード</label></td>
<td><input type="password" name="password" size="20"></td></tr>

<tr><td colspan="2"><input type="submit" value="変更"></td></tr>
</table>
</form>

EOF;
  }
}

function ConcreteOutputIconList($base_url = 'icon_view') {
  global $ICON_CONF, $USER_ICON, $RQ_ARGS;

  //アイコン情報の準備
  $sql_prepare = <<<SQL
CREATE TEMPORARY TABLE IF NOT EXISTS _icons
SELECT
  ico.icon_no,
  ico.icon_name,
  ico.icon_filename,
  ico.icon_width,
  ico.icon_height,
  ico.color,
  ico.appearance,
  ico.category,
  ico.author,
  COUNT( usr.uname ) AS num_used
FROM
  user_icon AS ico
  LEFT JOIN user_entry AS usr USING (icon_no)
GROUP BY
  ico.icon_no,
  ico.icon_name,
  ico.icon_filename,
  ico.icon_width,
  ico.icon_height,
  ico.color,
  ico.appearance,
  ico.category,
  ico.author

SQL;
  SendQuery($sql_prepare);

  //ヘッダーの出力
  $icon_count = FetchResult('SELECT COUNT(icon_no) FROM _icons WHERE icon_no > 0');
  $line_header = '<tr><td colspan="10">';
  $line_footer = '</td></tr>'."\n";
  $url_header  = '<a href="' . $base_url . '.php?';
  $url_option  = array();
  $query_stack = array();
  $category_list = GetIconCategoryList('category');
  $all_url = $url_header;
  if($RQ_ARGS->room_no > 0) $all_url .= 'room_no=' . $RQ_ARGS->room_no;

  //PrintData($category_list);
  //PrintData($RQ_ARGS);

  echo <<<EOF
<table>
<tr>

EOF;

  //検索項目とタイトル、検索条件のセットから選択肢を抽出し、表示します。
  function _outputSelectionByType($type, $caption, $filter) {
    global $RQ_ARGS;
    $selected
      = isset($RQ_ARGS->$type)
        ? is_array($RQ_ARGS->$type) ? $RQ_ARGS->$type : array($RQ_ARGS->$type)
        : array();
    $sql = "SELECT DISTINCT {$type} FROM _icons WHERE {$type} IS NOT NULL";
    if (count($filter)) {
      $sql .= ' AND '.implode(' AND ', $filter);
    }
    $list = FetchArray($sql);
    echo <<<HTML
<td>
<label for="{$type}[]">{$caption}</label><br>
<select name="{$type}[]" size="6" multiple style="width:12em;">
<option value="__all__">全て</option>',

HTML;
    foreach($list as $name){
      printf(
        '<option value="%s" %s>%s</option>',
        $name,
        in_array($name, $selected) ? 'selected' : '',
        strlen($name) ? $name : '空欄'
      );
    }
    echo '</select></td>';
    return in_array('__all__', $selected) ? array() : $selected;
  }

  //検索項目と検索値のセットから抽出条件を生成します。
  function _generateInClause($type, $values) {
    $safe_values = array();
    foreach($values as $value) {
      $safe_values[] = sprintf("'%s'", mysql_real_escape_string($value));
    }
    return $type.' IN ('.implode(',', $safe_values).')';
  }

  //検索条件の表示
  $where_cond = array();

  $selected_categories = _outputSelectionByType('category', 'カテゴリ', $where_cond);
  if(0 < count($selected_categories)){
    $where_cond[] = _generateInClause('category', $selected_categories);
  }

  $selected_appearances = _outputSelectionByType('appearance', '出典', $where_cond);
  if(0 < count($selected_appearances)){
    $where_cond[] = _generateInClause('appearance', $selected_appearances);
  }

  $selected_authors = _outputSelectionByType('author', 'アイコン作者', $where_cond);
  if(0 < count($selected_authors)){
    $where_cond[] = _generateInClause('author', $selected_authors);
  }

  echo <<<EOF
</tr>
<tr>
<td colspan="10">
<button type="submit">検索</button>
</td>
</tr>
</table>

EOF;


  //検索結果の表示
  if ($is_icon_view = empty($RQ_ARGS->room_no)) {
    echo <<<HTML
<table>
<caption>
[S] 出典 / [C] カテゴリ / [A] アイコンの作者 / [U] 使用回数'<br>
アイコンをクリックすると編集できます (要パスワード)'
</caption>

HTML;
  }
  if ($is_user_entry = isset($RQ_ARGS->room_no)) {
    echo <<<HTML
<table>
<caption>
あなたのアイコンを選択して下さい。
</caption>
<thead>
<tr>

HTML;
  }

  //ユーザアイコンのテーブルから一覧を取得
  $query = 'SELECT * FROM _icons WHERE ';
  $where_cond[] = 'icon_no > 0';
  $query .= implode(' AND ', $where_cond);
  $query .= ' ORDER BY icon_name, icon_no';
  $records = FetchAssoc($query);

  $PAGE_CONF = $ICON_CONF;
  $PAGE_CONF->count = count($records);
  $PAGE_CONF->url     = $base_url;
  $PAGE_CONF->current = $RQ_ARGS->page;
  $PAGE_CONF->option  = $url_option;
  if($RQ_ARGS->room_no > 0) $PAGE_CONF->option[] = 'room_no=' . $RQ_ARGS->room_no;
  echo '<td colspan="10" style="text-align:right;">';
  //PrintData($PAGE_CONF, 'PAGE_CONF');
  OutputPageLink($PAGE_CONF);
  echo <<<HTML
</td>
</tr>
</thead>
<tbody>
<tr>

HTML;

  if($RQ_ARGS->page != 'all'){
    $limit_min = $ICON_CONF->view * ($RQ_ARGS->page - 1);
    if($limit_min < 1) $limit_min = 0;
    $query .= sprintf(' LIMIT %d, %d', $limit_min, $ICON_CONF->view);
  }
  $icon_list = array();
  $columns = 0;
  foreach($records as $icon_info) {
    extract($icon_info);
    $location = $ICON_CONF->path . '/' . $icon_filename;
    $info_width = 162 - $icon_width;
    $href = $is_icon_view ? "href=\"{$base_url}.php?icon_no={$icon_no}\"" : '';

    if ($is_user_entry) {
      echo <<<HTML
<th>
<input type="radio" id="icon_{$icon_no}" name="icon_no" value="{$icon_no}">
</th>
 
HTML;
    }

    echo <<<HTML
<td style="padding:4px;">
<label for="icon_{$icon_no}">
<a {$href} style="display:block;float:left;vertical-align:middle;">
<img src="{$location}" width="{$icon_width}" height="{$icon_height}" style="border:3px solid {$color};">
</a>
<ul style="list-style:none;float:left;width:{$info_width}px;margin-left:4px;padding:0;vertical-align:middle;">
<li><a {$href}>No. {$icon_no}</a></li>
<li><a {$href}>{$icon_name}</a></li>
<li><font color="{$color}">◆</font>{$color}</li>

HTML;
    if(!$is_icon_view){
      $data = '';
      if(!empty($appearance)) $data .= '<li>[S]' . $appearance;
      if(!empty($category))   $data .= '<li>[C]' . $category;
      if(!empty($author))     $data .= '<li>[A]' . $author;
      $data .= '<li>[U]' . $num_used;
      echo $data;
    }
    echo <<<HTML
</ul>
</label>
</td>

HTML;
    if (4 <= ++$columns) {
      $columns = 0;
      echo '</tr><tr>';
    }
  }
  echo <<<HTML
</tr>
</tbody>
</table>

HTML;

}

function GetIconCategoryList($type, $limit = '', $query_stack = array()){
  $stack = array('SELECT', 'FROM user_icon WHERE', 'IS NOT NULL GROUP BY', 'ORDER BY icon_no');
  if(count($query_stack) > 0){
    $list = $query_stack;
    $list[] = '';
    $stack[1] .= ' ' . implode(' AND ', $list);
  }
  return FetchArray(implode(" {$type} ", $stack) . $limit);
}

function AddIconURLOption(&$stack, $option){
  global $RQ_ARGS;
  if(is_int($RQ_ARGS->$option)) $stack[] = "{$option}={$RQ_ARGS->$option}";
}

function OutputIconPageFooter(){
  OutputHTMLFooter();
}
