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

/* /lotto/cron/ 에서만 사용하는 함수 시작 */
function cron_log($root_path, $error_text) {

    $log_path = $root_path."/lotto/cron/log";
    $fp = fopen($log_path."/".G5_TIME_YMD.".txt", "a", false);
    fwrite($fp, $error_text);
    fclose($fp);
}

function get_curl($root_path, $url, $log_filename, $header) {
    $curl = curl_init();

    if( !trim($url) )
        return;

    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => $header
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        $err_text = G5_TIME_HIS." ".$root_path."/cron/".$log_filename." - cURL Error #:" . $err . "\n";
        cron_log($root_path, $err_text);
        exit;
    }

    return $response;
}
/* /lotto/cron/ 에서만 사용하는 함수 끝 */

// 한페이지에 보여줄 행, 현재페이지, 총페이지수, URL
function lotto_paging($write_pages, $cur_page, $total_page, $url, $add="") {
    //$url = preg_replace('#&amp;page=[0-9]*(&amp;page=)$#', '$1', $url);
    $url = preg_replace('#(&amp;)?page=[0-9]*#', '', $url);
    $url .= substr($url, -1) === '?' ? 'page=' : '&amp;page=';

    $str = '';
    if ($cur_page > 1) {
        $str  .= '  <li class="page-item">
                        <a class="page-link" href="'.$url.'1'.$add.'">
                            <!-- Download SVG icon from http://tabler-icons.io/i/chevrons-left -->
                            <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><polyline points="11 7 6 12 11 17" /><polyline points="17 7 12 12 17 17" /></svg>
                        </a>
                    </li>';
    }

    $start_page = ( ( (int)( ($cur_page - 1 ) / $write_pages ) ) * $write_pages ) + 1;
    $end_page = $start_page + $write_pages - 1;

    if ($end_page >= $total_page) $end_page = $total_page;

    if ($start_page > 1) {
        $str  .= '  <li class="page-item">
                        <a class="page-link" href="'.$url.($start_page-1).$add.'">
                            <!-- Download SVG icon from http://tabler-icons.io/i/chevron-left -->
                            <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><polyline points="15 6 9 12 15 18" /></svg>
                        </a>
                    </li>';
    }

    if ($total_page > 1) {
        for ($k=$start_page;$k<=$end_page;$k++) {
            if ($cur_page != $k)
                $str .= '<li class="page-item"><a class="page-link" href="'.$url.$k.$add.'">'.$k.'</a></li>'.PHP_EOL;
            else
                $str .= '<li class="page-item active"><a class="page-link" href="'.$url.$k.$add.'" tabindex="-1" aria-disabled="true">'.$k.'</a></li>'.PHP_EOL;
        }
    }

    if ($total_page > $end_page) {
        $str .= '<li class="page-item">
                    <a class="page-link" href="'.$url.($end_page+1).$add.'">
                        <!-- Download SVG icon from http://tabler-icons.io/i/chevron-right -->
                        <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><polyline points="9 6 15 12 9 18"></polyline></svg>
                    </a>
                </li>';
    }

    if ($cur_page < $total_page) {
        $str .= '<li class="page-item">
                    <a class="page-link" href="'.$url.$total_page.$add.'">
                        <!-- Download SVG icon from http://tabler-icons.io/i/chevrons-right -->
                        <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><polyline points="7 7 12 12 7 17" /><polyline points="13 7 18 12 13 17" /></svg>
                    </a>
                </li>';
    }

    if ($str)
        return "<ul class=\"pagination m-0 ms-auto\">{$str}</ul>";
    else
        return "";
}

// ajax 처리페이지에서 메세지 피드백할때 사용
function alert_ajax($status, $msg='', $url='') {
    $json['status'] = $status;
    $json['msg'] = $msg;
    $json['url'] = $url;
//    print_r($json);
    echo json_encode($json);
    exit;
}

// 불법접근을 막도록 토큰을 생성하면서 토큰값을 리턴
function get_lotto_admin_token() {
    $token = md5(uniqid(rand(), true));
    set_session('ss_lotto_admin_token', $token);

    return $token;
}

// POST로 넘어온 토큰과 세션에 저장된 토큰 비교
function check_lotto_admin_token() {
    $token = get_session('ss_lotto_admin_token');
    set_session('ss_lotto_admin_token', '');

    if(!$token || !$_REQUEST['token'] || $token != $_REQUEST['token'])
        alert('올바른 방법으로 이용해 주십시오.', G5_URL);

    return true;
}

// 키오스크 정보를 얻는다.
function get_kiosk_by_id($ki_id) {
    global $lo;

    if (preg_match("/[^0-9]+/i", $ki_id))
        return array();

    $sql = " select * from {$lo['kiosk_table']} where ki_id = trim('$ki_id') ";
    return sql_fetch($sql);
}

// 키오스크 이름에서 개행을 공백으로 치환.
function get_kiosk_name($name) {
    return preg_replace('/\r\n|\r|\n/', ' ', $name);
}

// 회원의 키오스크 목록을 얻는다.
function get_kiosk_ids($member) {
    global $lo;

    if( $member['mb_level'] < 6 )
        return array();

    if( $member['mb_id'] ) {
        $sql = "select ki_id from {$lo['kiosk_table']} where ki_1_agency_mb_id = '{$member['mb_id']}' or ki_2_agency_mb_id = '{$member['mb_id']}' or ki_3_agency_mb_id = '{$member['mb_id']}' or ki_4_agency_mb_id = '{$member['mb_id']}' or ki_d_agency_mb_id = '{$member['mb_id']}' ";

        $result = sql_query($sql);
        $list = array();
        while( $row = sql_fetch_array($result) ) {
            if( trim($row['ki_id']) ) {
                $list[] = $row['ki_id'];
            }
        }

        return $list;
    } else {
        return array();
    }
}

// 회원목록을 SELECT 형식으로 얻음
function get_member_option($selected='', $mb_level_min=6, $mb_level_max=9, $print_level=0) {
    global $g5, $config, $is_admin;

    if( $is_admin != "lotto" ) return;

    $sql  = "select * from {$g5['member_table']} where (1) ";

    $mb_level_min = (int)$mb_level_min;
    $mb_level_max = (int)$mb_level_max;

    if( $mb_level_min > 0 && $mb_level_min == $mb_level_max ) {
        $sql .= " and mb_level = {$mb_level_min} ";
    } else {
        if( $mb_level_min > 0 ) {
            $sql .= " and mb_level >= {$mb_level_min} ";
        }

        if( $mb_level_max > 0 ) {
            $sql .= " and mb_level <= {$mb_level_max} ";
        }
    }

    $sql .= " order by mb_id ";

    $curr_ymd = date("Ymd", G5_SERVER_TIME);

    $result = sql_query($sql);
    for( $i=0; $row = sql_fetch_array($result); $i++ ) {
        // 차단된 아이디인가?
        if( $row['mb_intercept_date'] && $row['mb_intercept_date'] <= $curr_ymd ) {
            continue;
        }

        // 탈퇴한 아이디인가?
        if( $row['mb_leave_date'] && $row['mb_leave_date'] <= $curr_ymd ) {
            continue;
        }

        $level_text = "";
        if( $print_level ) {
            $key = "lev_cf_{$row['mb_level']}";
            $level_text = "[".$config[$key]."] ";
        }

        $str .= option_selected($row['mb_id'], $selected, "{$level_text}{$row['mb_name']} ({$row['mb_nick']}) - {$row['mb_id']}");
    }
    return $str;
}

function get_agency_text($mb_id) {
    global $config;

    $mb = get_member($mb_id);
    return "[".$config['lev_cf_'.$mb['mb_level']]."] ".$mb['mb_name']." (".$mb['mb_nick'].") - ".$mb['mb_id'];
}

function time_to_sec($time) {
    list($hours, $minutes, $seconds) = explode(":", $time);
    return ($hours * 3600 + $minutes * 60 + $seconds);
}

function sec_to_time($sec) {
    $hour = (int)($sec / 3600);
    $minute = (int)($sec % 3600 / 60);
    $second = (int)($sec % 3600 % 60);

    $hour = $hour < 10 ? '0'.$hour : $hour;
    $minute = $minute < 10 ? '0'.$minute : $minute;
    $second = $second < 10 ? '0'.$second : $second;
    return ((int)$hour ? $hour.'시간':'').((int)$minute ? $minute.'분':'').((int)$second ? $second.'초':'');
}

function empty_reg_no($reg_no) {
    if( !trim($reg_no) )
        return "등록번호를 입력해 주십시오.";
    else
        return "";
}

function valid_reg_no($reg_no) {
    if( preg_match("/[^0-9a-z]+/i", $reg_no) )
        return "등록번호는 영문자, 숫자만 입력하세요.";
    else
        return "";
}

function exist_reg_no($reg_no) {
    global $lo;

    $reg_no = trim($reg_no);
    if( $reg_no == "" ) return "";

    $sql = " select count(*) as cnt from `{$lo['kiosk_table']}` where ki_reg_no = '{$reg_no}' ";
    $row = sql_fetch($sql);
    if( $row['cnt'] )
        return "이미 존재하는 등록번호입니다.";
    else
        return "";
}

function get_payment_result($pa_id) {
    global $lo;

    if( !$pa_id ) {
        return '';
    }

    $row = sql_fetch("select count(*) cnt from {$lo['order_table']} where pa_id = '{$pa_id}' and od_pay_status = '결제완료' and od_result = '대기' ");
    if( $row['cnt'] == 0 ) {
        return 1;
    }
}

function lotto_number_filter($main_set, $bonus) {
    if( !($main_set && $bonus) ) {
        return false;
    }

    $number['main'] = array_unique(array_filter(explode(',', $main_set), 'intval'));
    sort($number['main']);

    $number['bonus'] = (int)$bonus;

    if( count($number['main'])==5 && $number['bonus'] ) {
        return $number;
    } else {
        return false;
    }
}

// 당첨처리
function lotto_match_proc($ht_id, $order, $lotto_number, $rank_info) {
    global $g5, $lo, $lotto_name_kr;

    if( !$order['od_id'] || $order['od_result']!='대기' || !$rank_info || !$ht_id ) {
        return '';
    }

    // 회원아이디가 없다면 당첨처리 할 필요 없음
    $mb = sql_fetch(" select mb_id from {$g5['member_table']} where mb_id = '{$order['mb_id']}' ");
    if( !$mb['mb_id'] ) { return ''; }

    // 회원복권번호 확인
    $user_number = lotto_number_filter($order['od_main_set'], $order['od_bonus']);

    // order 복권번호 체크
    if( !(count($user_number['main'])==5 && $user_number['bonus']) ) {
        return '';
    }

    $main_match = count(array_intersect($user_number['main'], $lotto_number['main']));

    $bonus_match = 0;
    if( $user_number['bonus'] == $lotto_number['bonus'] ) {
        $bonus_match = 1;
    }

    $od_result = '낙첨';
    $od_rank = 0;
    $od_tax  = 0;
    $od_prize_usd = 0;
    $od_prize_krw = 0;
    $od_payed_prize = 0;
    $od_is_payed = 'Y';

    $user_rank = $rank_info[$main_match][$bonus_match];

    if( $user_rank['rank'] ) {

        $rank = sql_fetch("select * from {$lo['rank_table']} where ht_id = '{$ht_id}' and ra_rank = '{$user_rank['rank']}' ");
        if( $rank['ra_rank'] ) {
            $od_name = $rank['ra_name'];
            $od_rank = $rank['ra_rank'];
            $od_tax  = $rank['ra_tax'];
            $od_result = '당첨';
            $od_is_payed = 'N';

            if( $rank['ra_rank'] == '1' ) {
                $od_prize_usd = 'Jackpot';
                $od_prize_krw = 'Jackpot';
                $od_payed_prize = 'Jackpot';
            } else {
                $od_prize_usd = $rank['ra_prize'];

                // Multiplier Apply by Bill at 05272025
                $od_multiplier = ($order['od_multiplier'] === null || $order['od_multiplier'] == 0) ? 1 : (int)$order['od_multiplier'];
                $od_pay_usd = (int)$od_prize_usd;
                // Add 3 only for ranks 8 or 9 with 'mega millions'
                if (in_array($od_rank, ['8', '9']) && $od_name === 'mega million') {
                    $od_pay_usd += 3;
                }
                $od_prize_usd = $od_pay_usd * $od_multiplier;
    //          $od_prize_krw = $od_prize_usd * $exchange_rate;
                $od_payed_prize = round($od_prize_usd * (100 - $od_tax) / 100);
                //------------------------------------------------------------

                if( $rank['ra_pay'] == 'Y' ) {
                    $cash_content  = "[{$lotto_name_kr[$order['od_name']]}]";
                    $cash_content .= " {$order['od_draw_date']}";
                    $cash_content .= " {$od_rank}등 당첨금적립";
                    $result = insert_cash($order['mb_id'], $od_payed_prize, $cash_content, $lo['order_table'], $order['mb_id'], "{$order['od_id']} - 당첨금적립");
                    if( $result )
                        $od_is_payed = 'Y';
                }
            }
        } else {
            return false;
        }
    }

    $sql = "update {$lo['order_table']} set
                od_exchange_rate = '{$exchange_rate}',
                od_rank          = '{$od_rank}',
                od_tax           = '{$od_tax}',
                od_prize_usd     = '{$od_prize_usd}',
                od_prize_krw     = '{$od_prize_krw}',
                od_payed_prize   = '{$od_payed_prize}',
                od_result        = '{$od_result}',
                od_is_payed      = '{$od_is_payed}'
            where od_id = '{$order['od_id']}'
           ";
    sql_query($sql);

    return 1;
}

// 캐시 부여
function insert_cash($mb_id, $cash, $content='', $rel_table='', $rel_id='', $rel_action='', $expire=0) {
    global $config;
    global $g5, $lo;

    // 캐시가 없다면 업데이트 할 필요 없음
    if ($cash == 0) { return 0; }

    // 회원아이디가 없다면 업데이트 할 필요 없음
    if ($mb_id == '') { return 0; }
    $mb = sql_fetch(" select mb_id from {$g5['member_table']} where mb_id = '$mb_id' ");
    if (!$mb['mb_id']) { return 0; }

    // 회원캐시
    $mb_cash = get_cash_sum($mb_id);

    // 이미 등록된 내역이라면 건너뜀
    if ($rel_table || $rel_id || $rel_action) {
        $sql = " select count(*) as cnt from {$lo['cash_table']}
                  where mb_id = '$mb_id'
                    and ca_rel_table = '$rel_table'
                    and ca_rel_id = '$rel_id'
                    and ca_rel_action = '$rel_action' ";
        $row = sql_fetch($sql);
        if( $row['cnt'] )
            return -1;
    }

    // 캐시 건별 생성
    $ca_expire_date = '9999-12-31';
    if($expire > 0)
        $ca_expire_date = date('Y-m-d', strtotime('+'.($expire - 1).' days', G5_SERVER_TIME));

    $ca_expired = 0;
    if($cash < 0) {
        $ca_expired = 1;
        $ca_expire_date = G5_TIME_YMD;
    }
    $ca_mb_cash = $mb_cash + $cash;

    $sql = " insert into {$lo['cash_table']}
                set mb_id = '$mb_id',
                    ca_datetime = '".G5_TIME_YMDHIS."',
                    ca_content = '".addslashes($content)."',
                    ca_cash = '$cash',
                    ca_mb_cash_before = '$mb_cash',
                    ca_mb_cash = '$ca_mb_cash',
                    ca_expired = '$ca_expired',
                    ca_expire_date = '$ca_expire_date',
                    ca_rel_table = '$rel_table',
                    ca_rel_id = '$rel_id',
                    ca_rel_action = '$rel_action' ";
    sql_query($sql);

    // 캐시 UPDATE
    $sql = " update {$g5['member_table']} set mb_cash = '$ca_mb_cash' where mb_id = '$mb_id' ";
    return sql_query($sql);
}

// 캐시 부여
function insert_cash2($mb_id, $cash, $content='', $rel_table='', $rel_id='', $rel_action='', $expire=0) {
    global $config;
    global $g5, $lo;

    // 캐시가 없다면 업데이트 할 필요 없음
    if ($cash == 0) { return 0; }

    // 회원아이디가 없다면 업데이트 할 필요 없음
    if ($mb_id == '') { return 0; }
    $mb = sql_fetch(" select mb_id from {$g5['member_table']} where mb_id = '$mb_id' ");
    if (!$mb['mb_id']) { return 0; }

    // 회원캐시
    $mb_cash = get_cash_sum($mb_id);

    // 이미 등록된 내역이라면 건너뜀
    if ($rel_table || $rel_id || $rel_action) {
        $sql = " select count(*) as cnt from {$lo['cash_table']}
                  where mb_id = '$mb_id'
                    and ca_rel_table = '$rel_table'
                    and ca_rel_id = '$rel_id'
                    and ca_rel_action = '$rel_action' ";
        $row = sql_fetch($sql);
        if( $row['cnt'] )
            return -1;
    }

    // 캐시 건별 생성
    $ca_expire_date = '9999-12-31';
    if($expire > 0)
        $ca_expire_date = date('Y-m-d', strtotime('+'.($expire - 1).' days', G5_SERVER_TIME));

    $ca_expired = 0;
    if($cash < 0) {
        $ca_expired = 1;
        $ca_expire_date = G5_TIME_YMD;
    }
    $ca_mb_cash = $mb_cash + $cash;

    $sql = " insert into {$lo['cash_table']}
                set mb_id = '$mb_id',
                    ca_datetime = '2023-08-22 00:00:00',
                    ca_content = '".addslashes($content)."',
                    ca_cash = '$cash',
                    ca_mb_cash_before = '$mb_cash',
                    ca_mb_cash = '$ca_mb_cash',
                    ca_expired = '$ca_expired',
                    ca_expire_date = '$ca_expire_date',
                    ca_rel_table = '$rel_table',
                    ca_rel_id = '$rel_id',
                    ca_rel_action = '$rel_action' ";
//                    ca_datetime = '".$order['od_draw_date']." ".$order['od_draw_time']."',
    return sql_query($sql);
}

// 캐시 내역 합계
function get_cash_sum($mb_id) {
    global $lo, $config;

    // 소멸캐시가 있으면 내역 추가
    $expire_cash = get_expire_cash($mb_id);
    if($expire_cash > 0) {
        $mb = get_member($mb_id, 'mb_cash');
        $content = '캐쉬 만료';
        $rel_table = '@expire';
        $rel_id = $mb_id;
        $rel_action = 'expire'.'-'.uniqid('');
        $cash = $expire_cash * (-1);
        $ca_mb_cash = $mb['mb_cash'] + $cash;
        $ca_expire_date = G5_TIME_YMD;
        $ca_expired = 1;

        $sql = " insert into {$lo['cash_table']}
                    set mb_id = '$mb_id',
                        ca_datetime = '".G5_TIME_YMDHIS."',
                        ca_content = '".addslashes($content)."',
                        ca_cash = '$cash',
                        ca_use_cash = '0',
                        ca_mb_cash_before = '{$mb['mb_cash']}',
                        ca_mb_cash = '$ca_mb_cash',
                        ca_expired = '$ca_expired',
                        ca_expire_date = '$ca_expire_date',
                        ca_rel_table = '$rel_table',
                        ca_rel_id = '$rel_id',
                        ca_rel_action = '$rel_action' ";
        sql_query($sql);
    }

    // 유효기간이 있을 때 기간이 지난 캐시 expired 체크
    $sql = "update {$lo['cash_table']} set
                ca_expired = '1'
            where mb_id = '$mb_id'
              and ca_expired <> '1'
              and ca_expire_date <> '9999-12-31'
              and ca_expire_date < '".G5_TIME_YMD."' ";
    sql_query($sql);

    // 캐시합
    $sql = "select sum(ca_cash) as sum_ca_cash from {$lo['cash_table']} where mb_id = '$mb_id' ";
    $row = sql_fetch($sql);

    return $row['sum_ca_cash'];
}

// 소멸 캐시
function get_expire_cash($mb_id) {
    global $lo;

    $sql = "select sum(ca_cash) as sum_cash from {$lo['cash_table']}
            where mb_id = '$mb_id'
              and ca_expired = '0'
              and ca_expire_date <> '9999-12-31'
              and ca_expire_date < '".G5_TIME_YMD."' ";
    $row = sql_fetch($sql);

    return $row['sum_cash'];
}

function percent_format($percent) {
    if( fmod($percent, 1) == 0 )
        return (int)$percent;
    else
        return $percent;
}

// KWON 수기결제 결제정보 조회
function ksnet_get_api($trxId) {
    global $ksnet_key;

    if( !$trxId )
        return;

    $host = "https://svcapi.mtouch.com/api/get/{$trxId}";
    $ch = curl_init($host);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "Authorization: {$ksnet_key}"));
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, JSON_UNESCAPED_UNICODE);
}

// KWON 수기결제 결제정보 조회
function ksnet_pay_api($post_data) {
    global $ksnet_key;

    if( !$post_data )
        return;

    $host = "https://svcapi.mtouch.com/api/pay";

    //CURL함수 사용
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $host);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //header값 셋팅(없을시 삭제해도 무방함)
    $headers = array("Accept: application/json",
                     "Accept-Language: ko_KR",
                     "Authorization: {$ksnet_key}",
                     "Content-Type: application/json"
    );

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);
    if(curl_error($ch)){
        $curl_data = null;
    } else {
        $curl_data = $response;
    }

    curl_close($ch);

    return $response;
}

// 키오스크의 수수료 정보를 가져옴
function get_calc_comm($kiosk, $platform, $amount) {
    if( ($platform != 'WEB' && $platform != 'KIOSK' && $platform != 'PC방') || !$amount )
        return;

    $comm = array();
    $percent = 100;
    $rest_amount = $amount;
    $agency = array("1", "2", "3", "4", "d", "");

    foreach( $agency as $v ) {
        if( $v == "" ) { // 본사
            $agency_mb_id = "";
            $comm_percent = $percent;
            $comm_amount = $rest_amount;
            $class = "H";
            $type  = "A";
        } else { // 가맹점
            $agency_mb_id = $kiosk["ki_{$v}_agency_mb_id"];
            if( $platform == 'WEB' )
                $comm_percent = $kiosk["ki_{$v}_agency_comm_web"];
            else if( $platform == 'KIOSK' || $platform == 'PC방' )
                $comm_percent = $kiosk["ki_{$v}_agency_comm"];

            if( $agency_mb_id && $comm_percent > 0 ) {
                if( 1 <= $v && $v <= 4 ) {
                    $class = $v;
                    $type  = "A";
                } else if( $v == "d" ) {
                    $mb = get_member($agency_mb_id);
                    if( $mb['mb_level'] == "6" ) {
                        $class = "4";
                    } else if( $mb['mb_level'] == "7" ) {
                        $class = "3";
                    } else if( $mb['mb_level'] == "8" ) {
                        $class = "2";
                    } else if( $mb['mb_level'] == "9" ) {
                        $class = "1";
                    } else {
                        continue;
                    }

                    $type = "D"; // 영업점
                } else {
                    continue;
                }

                $percent -= $comm_percent;
                $comm_amount = floor($amount / 100 * $comm_percent);
                $rest_amount -= $comm_amount;

            } else {
                continue;
            }
        }

        $comm[] = array(
                    'class'   => $class,
                    'type'    => $type,
                    'mb_id'   => $agency_mb_id,
                    'percent' => $comm_percent,
                    'amount'  => $comm_amount
                  );
    }

    return $comm;
}

function get_current_lotto() {
    global $lotto_name, $lo;

    $million = 1000000;

    $sql = "select * from {$lo['exchange_rate_table']} order by er_date desc limit 0, 1 ";
    $rate = sql_fetch($sql);

    $lotto = array();
    for( $i=0; $i < count($lotto_name); $i++ ) {
        $ht_name = $lotto_name[$i];
        $sql = "select * from {$lo['history_table']} where ht_name = '{$ht_name}' and ht_base_datetime > '".G5_TIME_YMDHIS."' order by ht_draw_date asc limit 0, 1 ";
        $lotto[$ht_name] = sql_fetch($sql);

        $sql = "select * from {$lo['history_table']} where ht_name = '{$ht_name}' and ht_draw_date <= '".G5_TIME_YMD."' and ht_jackpot_usd <> '' order by ht_draw_date desc limit 0, 1 ";
        $jackpot = sql_fetch($sql);

        $lotto[$ht_name]['jackpot_usd'] = (trim($lotto[$ht_name]['ht_jackpot_usd']) ? $lotto[$ht_name]['ht_jackpot_usd'] : $jackpot['ht_jackpot_usd']) * $million;
        $lotto[$ht_name]['jackpot_krw'] = $lotto[$ht_name]['jackpot_usd'] * $rate['er_base_rate'];
        $lotto[$ht_name]['jackpot_krw_abb'] = round($lotto[$ht_name]['jackpot_krw'] / 100000000);

        $sql = "select * from {$lo['history_table']} where ht_name = '{$ht_name}' and ht_draw_date <= '".G5_TIME_YMD."' and ht_main_set <> '' and ht_bonus <> '' order by ht_draw_date desc limit 0, 1 ";
        $prev = sql_fetch($sql);

        $lotto[$ht_name]['prev'] = $prev;
        $lotto[$ht_name]['prev']['jackpot_usd'] = $prev['ht_jackpot_usd'] * $million;
        $lotto[$ht_name]['prev']['jackpot_krw'] = $lotto[$ht_name]['prev']['jackpot_usd'] * $rate['er_base_rate'];
        $lotto[$ht_name]['prev']['jackpot_krw_abb'] = round($lotto[$ht_name]['prev']['jackpot_krw'] / 100000000);
    }

    return $lotto;
}

function sms_send($recv_hp_mb, $sms_content) {
    include_once(G5_SMS5_PATH.'/sms5.lib.php');
    global $config, $sms5;

    $send_hp = str_replace("-","",$sms5['cf_phone']);//-제거
    $recv_hp = str_replace("-","",$recv_hp_mb);//-제거

    $SMS = new SMS5;//SMS 연결
    $SMS->SMS_con($config['cf_icode_server_ip'], $config['cf_icode_id'], $config['cf_icode_pw'], $config['cf_icode_server_port']);
    $SMS->Add($recv_hp, $send_hp, $config['cf_icode_id'], iconv("utf-8", "euc-kr", stripslashes($sms_content)), "");
    $result = $SMS->Send();

    if ($result) { //SMS 서버에 접속했습니다.
        list($phone, $code) = explode(":", $SMS->Result);
        $SMS->Init(); // 보관하고 있던 결과값을 지웁니다.

        if (substr($code,0,5) == "Error") {
            $error = "SMS 서버와 통신이 불안정합니다.\n고객센터로 문의해주세요.";
        } else {
            $error = '';
        }
    } else {
        $error = "SMS 서버와 통신이 불안정합니다.\n고객센터로 문의해주세요.";
    }

    if( $error ) {
        return array(0, $error);
    } else {
        return array(1, '');
    }
}

function lms_send($recv_hp_mb, $sms_content) {
    global $config, $sms5;
    include_once(G5_SMS5_PATH.'/sms5.lib.php');

    $send_hp = str_replace("-","",$sms5['cf_phone']);//-제거
    $recv_hp = str_replace("-","",$recv_hp_mb);//-제거

    $SMS = new SMS5;//SMS 연결
    $port_setting = get_icode_port_type($config['cf_icode_id'], $config['cf_icode_pw']);

    if($port_setting !== false) {
        $SMS->SMS_con($config['cf_icode_server_ip'], $config['cf_icode_id'], $config['cf_icode_pw'], $port_setting);

        $result = $SMS->Add(array($recv_hp), $send_hp, $config['cf_title'], '', '', $sms_content, '', 1);

        if($result) {
            $result = $SMS->Send();

            if ($result) { //SMS 서버에 접속했습니다.
                list($phone, $code) = explode(":", $SMS->Result[0]);
                $SMS->Init(); // 보관하고 있던 결과값을 지웁니다.

                if (substr($code,0,5) == "Error") {
                    $error = "SMS 서버와 통신이 불안정합니다.\n고객센터로 문의해주세요.";
                } else {
                    $error = '';
                }
            } else {
                $error = "SMS 서버와 통신이 불안정합니다.\n고객센터로 문의해주세요.";
            }
        } else {
            $error = "SMS 서버와 통신이 불안정합니다.\n고객센터로 문의해주세요.";
        }
    } else {
        $error = "SMS 서버와 통신이 불안정합니다.\n고객센터로 문의해주세요.";
    }

    if( $error ) {
        return array(0, $error);
    } else {
        return array(1, '');
    }
}

function number_filter($lotto_numbers, $lotto) {
    if( !$lotto['ht_main_number'] || !$lotto['ht_bonus_number'] )
        return;

    $return_array = array();
    $numbers_array = json_decode(stripslashes($lotto_numbers));
    $numbers_count = count($numbers_array);

    foreach($numbers_array as $number ) {
        if( $number[1] < 1 || $number[1] > $lotto['ht_bonus_number'] )
            continue;

        $main_filter = array_unique(array_filter($number[0],
                                    function($v, $k) use ($lotto) {
                                        return 0 < $v && $v <= $lotto['ht_main_number'];
                                    },
                                    ARRAY_FILTER_USE_BOTH
                       ));
        if( count($main_filter) != 5 )
            continue;

        $return_array[] = array($main_filter, $number[1]);
    }

    return $return_array;
}

function prize_check($ht_id) {
    global $lo;
    $rank = sql_fetch("select count(*) cnt from {$lo['rank_table']} where ht_id = '{$ht_id}' ");
    if( $rank['cnt'] == 9 ) {
        return true;
    } else {
        return false;
    }
}

function get_available_lotto($ht_name) {
    global $lo;
    if( !$ht_name )
        return null;

    $return_array = array();
    $sql = "select * from {$lo['history_table']} where ht_name = '{$ht_name}' and ht_base_datetime > '".G5_TIME_YMDHIS."' order by ht_draw_date asc ";
    $result = sql_query($sql);
    for( $i=0; $row = sql_fetch_array($result); $i++ ) {
        $return_array['data'][$i] = $row;
        $return_array['sum_price'][$i+1] = $return_array['sum_price'][$i] + $row['ht_price'];
    }

    return $return_array;
}

function sql_affected_rows($link=null) {
    global $g5;

    if(!$link)
        $link = $g5['connect_db'];

    if(function_exists('mysqli_affected_rows') && G5_MYSQLI_USE) {
        return mysqli_affected_rows($link);
    } else
        return mysql_affected_rows($link);
}
?>