<?php
if (!defined('_GNUBOARD_'))
  exit;

function get_rank_name($rank)
{
  global $g5;
  $str = "";
  $result = sql_fetch("SELECT lv_name FROM {$g5['level_table']} where lv_id = '{$rank}'");
  $str = $result['lv_name'];
  if (!$str) {
    $str = '-';
  }
  return $str;
}

function get_rank_id($rank)
{
  global $g5;
  $str = "";
  $result = sql_fetch("SELECT lv_id FROM {$g5['level_table']} where lv_name = '{$rank}'");
  $str = $result['lv_id'];
  return $str;
}

function get_rank_exp($exp, $ch_id)
{
  global $g5;
  $result = [];

  $ch = sql_fetch("SELECT ch_rank FROM {$g5['character_table']} where ch_id = '{$ch_id}'");
  $ch_rank = sql_fetch("SELECT * FROM {$g5['level_table']} where lv_id = '{$ch['ch_rank']}'");

  $level = sql_fetch("SELECT * FROM {$g5['level_table']} where lv_exp <= {$exp} ORDER BY lv_exp DESC limit 0, 1");
  $n_level = sql_fetch("SELECT * FROM {$g5['level_table']} where lv_exp >= {$level['lv_exp']} ORDER BY lv_exp ASC limit 0, 1");

  if ($ch_rank['lv_exp'] < $level['lv_exp']) {
    $add_status = sql_fetch("SELECT SUM(lv_add_state) as status FROM {$g5['level_table']} where lv_exp > '{$ch_rank['lv_exp']}' and lv_exp <= '{$level['lv_exp']}'");
    $add_status = $add_status['status'];

  } else if ($ch_rank['lv_exp'] > $level['lv_exp']) {
    $add_status = sql_fetch("SELECT SUM(lv_add_state) as status FROM {$g5['level_table']} where lv_exp <= '{$ch_rank['lv_exp']}' and lv_exp > '{$level['lv_exp']}'");
    $add_status = $add_status['status'] * -1;
  }

  $result['rank'] = $level['lv_id'];
  $result['next_rank'] = $n_level['lv_id'];
  $result['add_point'] = $add_status;
  $result['rest_exp'] = ($n_level ? $n_level['lv_exp'] - $level['lv_exp'] : 0);

  return $result;
}
