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

// 내 VPN서버 SSO 자동로그인 이력 조회
// 판매자 본인 소유 서버에 대한 SSO 접속 이력만 표시

$table = $g5['apms_vpn_sso_log'];

// 테이블 미생성시 자동 생성
$exists = sql_fetch("SHOW TABLES LIKE '{$table}'", false);
if (!is_array($exists) || count($exists) === 0) {
    sql_query("
        CREATE TABLE IF NOT EXISTS `{$table}` (
          `log_no`       int(11)      NOT NULL AUTO_INCREMENT,
          `vs_no`        int(11)      NOT NULL DEFAULT '0',
          `vs_alias`     varchar(100) NOT NULL DEFAULT '',
          `login_type`   varchar(10)  NOT NULL DEFAULT 'sso',
          `actor`        varchar(50)  NOT NULL DEFAULT '',
          `mb_id`        varchar(20)  NOT NULL DEFAULT '',
          `client_ip`    varchar(45)  NOT NULL DEFAULT '',
          `user_agent`   varchar(500) NOT NULL DEFAULT '',
          `nonce_prefix` varchar(16)  NOT NULL DEFAULT '',
          `sso_at`       datetime     NOT NULL,
          PRIMARY KEY (`log_no`),
          KEY `mb_id`  (`mb_id`),
          KEY `vs_no`  (`vs_no`),
          KEY `sso_at` (`sso_at`)
        ) ENGINE=MyISAM DEFAULT CHARSET=utf8
    ");
}

$page = isset($page) && (int)$page > 0 ? (int)$page : 1;
$rows = 30;
$mb_id_esc = sql_real_escape_string($mb_id);

// 슈퍼 관리자는 전체 조회 허용
$where_mb = ($is_admin === 'super') ? '' : " AND mb_id = '{$mb_id_esc}'";

// 서버 필터
$filter_vs   = isset($_GET['vs_no']) ? (int)$_GET['vs_no'] : 0;
$filter_type = isset($_GET['login_type']) && in_array($_GET['login_type'], ['sso', 'manual']) ? $_GET['login_type'] : '';
$where_vs    = $filter_vs > 0 ? " AND vs_no = {$filter_vs}" : '';
$where_type  = $filter_type !== '' ? " AND login_type = '" . sql_real_escape_string($filter_type) . "'" : '';

$total_count = (int)(sql_fetch("SELECT COUNT(*) as cnt FROM {$table} WHERE 1=1 {$where_mb} {$where_vs} {$where_type}", false)['cnt'] ?? 0);
$total_page  = (int)ceil($total_count / $rows);
$from_record = ($page - 1) * $rows;

$list = [];
$srv_tbl = $g5['apms_vpn_server'];
$result = sql_query(
    "SELECT l.*, COALESCE(s.vs_ip, '') AS vs_ip
       FROM {$table} l
       LEFT JOIN {$srv_tbl} s ON s.vs_no = l.vs_no
      WHERE 1=1 {$where_mb} {$where_vs} {$where_type}
      ORDER BY l.log_no DESC
      LIMIT {$from_record}, {$rows}"
);
for ($i = 0; $row = sql_fetch_array($result); $i++) {
    $list[$i] = $row;
}

// 본인 소유 서버 목록 (필터 드롭다운용)
$my_servers = [];
$srv_result = sql_query(
    "SELECT vs_no, vs_alias, vs_hostname FROM {$g5['apms_vpn_server']}
      WHERE pt_id = '{$mb_id_esc}'
      ORDER BY vs_registered_at DESC"
);
while ($s = sql_fetch_array($srv_result)) {
    $my_servers[] = $s;
}

$write_pages = (G5_IS_MOBILE) ? $config['cf_mobile_pages'] : $config['cf_write_pages'];

// iframe 모드 감지 (index.php?_iframe=1 경유)
$_in_iframe = !empty($_GET['_iframe']) && $_GET['_iframe'] === '1';

// fragment/iframe 모드 감지
$_vpns_frag = !empty($_vpns_frag)
    || (!empty($_GET['_frag']) && $_GET['_frag'] === '1')
    || $_in_iframe;

if ($_in_iframe) {
    $list_page = './?ap=vpnserver_sso_log&_iframe=1'
        . ($filter_vs ? "&vs_no={$filter_vs}" : '')
        . ($filter_type !== '' ? "&login_type={$filter_type}" : '')
        . '&page=';
} elseif (!empty($_vpns_frag)) {
    $list_page = APMS_PARTNER_URL . '/vpnserver_log_frag.php?'
        . ($filter_vs ? "vs_no={$filter_vs}&" : '')
        . ($filter_type !== '' ? "login_type={$filter_type}&" : '')
        . 'page=';
} else {
    $list_page = './?ap=vpnserver_sso_log'
        . ($filter_vs ? "&vs_no={$filter_vs}" : '')
        . ($filter_type !== '' ? "&login_type={$filter_type}" : '')
        . '&page=';
}

include_once($skin_path . '/itemlist_vpnserver_sso_log.skin.php');
