<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/auth.php';
if (function_exists('ggai_user_require_login')) {
    ggai_user_require_login();
}
$user_id = (int) ($_SESSION['user_id'] ?? 0);

$stmt = $pdo->prepare('SELECT role_id FROM users WHERE id=?');
$stmt->execute([$user_id]);
$role_id = (int) ($stmt->fetchColumn());

$stmt = $pdo->query('SELECT id, username, nickname, real_name, phone, created_at, level, referrer_id, referral_code FROM users');
$all_users = $stmt->fetchAll(PDO::FETCH_ASSOC);
$user_map = [];
foreach ($all_users as $u) {
    $user_map[$u['id']] = $u;
}
$stmt = $pdo->query("SELECT user_id, SUM(amount) as total FROM recharge_orders WHERE status='confirmed' GROUP BY user_id");
$all_performance = $stmt->fetchAll(PDO::FETCH_ASSOC);
$performance_map = [];
foreach ($all_performance as $p) {
    $performance_map[$p['user_id']] = $p['total'];
}

function get_team_members_fast($parent_id, $user_map, $performance_map, &$all_users, $level = 1, $parent_name = '', &$visited = [])
{
    $members = [];
    foreach ($all_users as $u) {
        if ($u['referrer_id'] == $parent_id && !in_array($u['id'], $visited)) {
            $visited[] = $u['id'];
            $performance = isset($performance_map[$u['id']]) ? $performance_map[$u['id']] : 0;
            $members[] = [
                'id' => $u['id'],
                'username' => $u['username'],
                'nickname' => $u['nickname'],
                'real_name' => $u['real_name'] ?? '',
                'phone' => $u['phone'],
                'created_at' => $u['created_at'],
                'level' => $u['level'],
                'performance' => $performance,
                'referrer_id' => $u['referrer_id'],
                'referrer_name' => $parent_name,
                'tree_level' => $level,
            ];
            $members = array_merge($members, get_team_members_fast($u['id'], $user_map, $performance_map, $all_users, $level + 1, $u['username'], $visited));
        }
    }
    return $members;
}
$visited = [];
$team_members = get_team_members_fast($user_id, $user_map, $performance_map, $all_users, 1, '', $visited);

$is_team_leader = ($role_id >= 13 && $role_id <= 38);
$is_partner = ($role_id == 9 || $role_id == 10 || $role_id == 11)
    || (function_exists('merchant_is_shop_owner') && merchant_is_shop_owner($pdo, $user_id));
if (!$is_team_leader && !$is_partner) {
    $team_members = array_filter($team_members, static function ($m) {
        return $m['tree_level'] == 1 || $m['tree_level'] == 2;
    });
}

$layer_stats = [];
$total_performance = 0;
foreach ($team_members as $m) {
    $l = $m['tree_level'];
    if (!isset($layer_stats[$l])) {
        $layer_stats[$l] = ['count' => 0, 'performance' => 0];
    }
    $layer_stats[$l]['count']++;
    $layer_stats[$l]['performance'] += $m['performance'];
    $total_performance += $m['performance'];
}

function mask_phone($phone)
{
    if (preg_match('/^1[3-9]\d{9}$/', $phone)) {
        return substr($phone, 0, 3) . '****' . substr($phone, -4);
    } elseif (strlen($phone) > 7) {
        return substr($phone, 0, 3) . '****' . substr($phone, -4);
    }
    return $phone;
}

function mask_name($str)
{
    $len = mb_strlen($str, 'UTF-8');
    if ($len <= 6) {
        if ($len <= 2) {
            return $str;
        }
        return mb_substr($str, 0, 2, 'UTF-8') . str_repeat('*', max(1, $len - 4)) . mb_substr($str, -2, 2, 'UTF-8');
    }
    return mb_substr($str, 0, 3, 'UTF-8') . str_repeat('*', $len - 6) . mb_substr($str, -3, 3, 'UTF-8');
}

function mask_real_name($real_name)
{
    if (empty($real_name)) {
        return '';
    }
    $len = mb_strlen($real_name, 'UTF-8');
    if ($len == 1) {
        return '*';
    }
    if ($len == 2) {
        return '*' . mb_substr($real_name, 1, 1, 'UTF-8');
    }
    $first_two = mb_substr($real_name, 0, 2, 'UTF-8');
    $remaining = mb_substr($real_name, 2, null, 'UTF-8');
    $stars = str_repeat('*', mb_strlen($remaining, 'UTF-8'));
    return $first_two . $stars;
}

$team_page_size = 50;
$team_total = count($team_members);
$team_page = max(1, (int) ($_GET['page'] ?? 1));
$team_total_pages = $team_total > 0 ? (int) ceil($team_total / $team_page_size) : 1;
if ($team_page > $team_total_pages) {
    $team_page = $team_total_pages;
}
$team_offset = ($team_page - 1) * $team_page_size;
$team_members_page = array_slice($team_members, $team_offset, $team_page_size);
$team_show_pager = $team_total > $team_page_size;
$team_row_from = $team_total > 0 ? $team_offset + 1 : 0;
$team_row_to = min($team_offset + count($team_members_page), $team_total);

$team_form_path = '/user/team_structure.php';
$teamRuPath = parse_url((string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH);
if (is_string($teamRuPath) && $teamRuPath !== '') {
    $team_form_path = $teamRuPath;
} elseif (!empty($_SERVER['SCRIPT_NAME'])) {
    $team_form_path = (string) $_SERVER['SCRIPT_NAME'];
}
$team_form_get = is_array($_GET) ? $_GET : [];
$team_pager_url = static function (int $pageNum) use ($team_form_path, $team_form_get): string {
    $q = $team_form_get;
    if ($pageNum > 1) {
        $q['page'] = $pageNum;
    } else {
        unset($q['page']);
    }
    $path = $team_form_path . ($q === [] ? '' : ('?' . http_build_query($q)));
    return function_exists('ggai_member_url_with_impersonate')
        ? ggai_member_url_with_impersonate($path)
        : $path;
};

ob_start();
?>
<div class="tech-header">
    <h2><i class="fas fa-users"></i> <?= __t('team_page_title', '团队成员列表'); ?></h2>
    <div class="desc">
        <?php
        $suffix = __t('team_page_title_suffix', '(共{count}人)');
        echo str_replace('{count}', (string) count($team_members), $suffix);
        ?>
    </div>
    <div class="tech-header-actions">
        <a href="<?php echo htmlspecialchars(function_exists('ggai_member_url_with_impersonate') ? ggai_member_url_with_impersonate('/user/index.php') : '/user/index.php'); ?>" class="btn btn-outline-light btn-sm">
            <i class="fas fa-home me-1"></i> <?= __t('common_back_home', '返回会员首页'); ?>
        </a>
    </div>
</div>
<div class="member-page-wrap">
    <div class="glass-card p-3 mb-4">
    <div class="table-responsive">
        <table class="table table-tech align-middle mb-0" id="teamTable">
            <thead class="table-light">
                <tr>
                    <th><?= __t('team_table_col_id', 'ID'); ?></th>
                    <th><?= __t('team_table_col_username', '用户名'); ?></th>
                    <th><?= __t('team_table_col_nickname', '昵称'); ?></th>
                    <th><?= __t('team_table_col_realname', '真实姓名'); ?></th>
                    <th><?= __t('team_table_col_referral_code', '推广码'); ?></th>
                    <th><?= __t('team_table_col_phone', '手机号'); ?></th>
                    <th><?= __t('team_table_col_created_at', '注册时间'); ?></th>
                    <th><?= __t('team_table_col_level', '等级'); ?></th>
                    <th><?= __t('team_table_col_performance', '累计业绩'); ?></th>
                    <th><?= __t('team_table_col_referrer', '推荐人'); ?></th>
                    <th><?= __t('team_table_col_layer', 'CJ'); ?></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($team_members_page as $m): ?>
                <tr>
                    <td><?php echo $m['id']; ?></td>
                    <td><?php echo htmlspecialchars(mask_name($m['username'])); ?></td>
                    <td><?php echo htmlspecialchars($m['nickname']); ?></td>
                    <td><?php echo htmlspecialchars(mask_real_name($m['real_name'] ?? '')); ?></td>
                    <td><?php echo htmlspecialchars($user_map[$m['id']]['referral_code'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars(mask_phone($m['phone'])); ?></td>
                    <td><?php echo htmlspecialchars($m['created_at']); ?></td>
                    <td><?php echo htmlspecialchars($m['level']); ?></td>
                    <td><?php echo number_format($m['performance'], 2); ?></td>
                    <td><?php echo htmlspecialchars(mask_name($m['referrer_name'])); ?></td>
                    <td><?php echo $m['tree_level']; ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if ($team_show_pager): ?>
    <div class="d-flex flex-column flex-md-row align-items-center justify-content-between gap-2 mt-3 team-structure-pager">
        <div class="text-muted small">
            <?php
            $teamPagerSummary = __t('team_pager_summary', '共 {total} 人，第 {page}/{pages} 页（本页 {from}-{to}）');
            echo htmlspecialchars(str_replace(
                ['{total}', '{page}', '{pages}', '{from}', '{to}'],
                [(string) $team_total, (string) $team_page, (string) $team_total_pages, (string) $team_row_from, (string) $team_row_to],
                $teamPagerSummary
            ));
            ?>
        </div>
        <nav aria-label="<?= htmlspecialchars(__t('team_pager_nav', '团队成员分页')) ?>">
            <ul class="pagination pagination-sm mb-0 flex-wrap justify-content-center">
                <?php if ($team_page > 1): ?>
                <li class="page-item">
                    <a class="page-link" href="<?= htmlspecialchars($team_pager_url($team_page - 1)) ?>"><?= htmlspecialchars(__t('team_pager_prev', '上一页')) ?></a>
                </li>
                <?php endif; ?>
                <?php
                $teamPagerWindow = 5;
                $teamPagerStart = max(1, $team_page - (int) floor($teamPagerWindow / 2));
                $teamPagerEnd = min($team_total_pages, $teamPagerStart + $teamPagerWindow - 1);
                $teamPagerStart = max(1, $teamPagerEnd - $teamPagerWindow + 1);
                if ($teamPagerStart > 1): ?>
                <li class="page-item">
                    <a class="page-link" href="<?= htmlspecialchars($team_pager_url(1)) ?>">1</a>
                </li>
                <?php if ($teamPagerStart > 2): ?>
                <li class="page-item disabled"><span class="page-link">…</span></li>
                <?php endif; ?>
                <?php endif; ?>
                <?php for ($i = $teamPagerStart; $i <= $teamPagerEnd; $i++): ?>
                <li class="page-item<?= $i === $team_page ? ' active' : '' ?>">
                    <?php if ($i === $team_page): ?>
                    <span class="page-link"><?= (int) $i ?></span>
                    <?php else: ?>
                    <a class="page-link" href="<?= htmlspecialchars($team_pager_url($i)) ?>"><?= (int) $i ?></a>
                    <?php endif; ?>
                </li>
                <?php endfor; ?>
                <?php if ($teamPagerEnd < $team_total_pages): ?>
                <?php if ($teamPagerEnd < $team_total_pages - 1): ?>
                <li class="page-item disabled"><span class="page-link">…</span></li>
                <?php endif; ?>
                <li class="page-item">
                    <a class="page-link" href="<?= htmlspecialchars($team_pager_url($team_total_pages)) ?>"><?= (int) $team_total_pages ?></a>
                </li>
                <?php endif; ?>
                <?php if ($team_page < $team_total_pages): ?>
                <li class="page-item">
                    <a class="page-link" href="<?= htmlspecialchars($team_pager_url($team_page + 1)) ?>"><?= htmlspecialchars(__t('team_pager_next', '下一页')) ?></a>
                </li>
                <?php endif; ?>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
    </div>
    <div class="glass-card p-3 mb-4">
    <h4 class="card-title mb-3"><i class="fas fa-chart-pie me-2"></i><?= __t('team_stats_title', '团队统计'); ?></h4>
    <div class="table-responsive">
    <table class="table table-tech w-auto mb-3">
        <thead>
        <tr>
            <?php
            $headers = explode(',', __t('team_stats_headers', 'CJ,人数,累计业绩'));
            foreach ($headers as $h) {
                echo '<th>' . htmlspecialchars(trim($h)) . '</th>';
            }
            ?>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($layer_stats as $l => $stat): ?>
            <tr><td><?php echo $l; ?></td><td><?php echo $stat['count']; ?></td><td><?php echo number_format($stat['performance'], 2); ?></td></tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <div class="mb-1"><b><?= __t('team_stats_total_performance', '团队业绩总计（下级个人充值合计，不含本人）：'); ?></b><?php echo number_format($total_performance, 2); ?> U</div>
    <div class="mb-0" style="font-size:0.88em;opacity:0.85;line-height:1.45;">
        <?= htmlspecialchars(__t('team_stats_scope_note', '本页按推荐关系统计下级个人已确认充值，不等于独站「升档有效业绩」；升档进度请看「独站业绩」。'), ENT_QUOTES, 'UTF-8'); ?>
    </div>
    </div>
</div>
<script>
function exportTableToCSV() {
    var csv = '';
    $("#teamTable tr").each(function(){
        var row = [];
        $(this).find('th,td').each(function(){
            var text = $(this).text().replace(/\s+/g,' ').replace(/"/g,'""');
            row.push('"'+text+'"');
        });
        csv += row.join(',') + "\n";
    });
    var blob = new Blob([csv], {type: 'text/csv'});
    var link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'team_members.csv';
    link.click();
}
</script>
<?php
$pageContent = ob_get_clean();
require_once __DIR__ . '/includes/layout.php';
