<?php
include __DIR__ . '/auth.php';
admin_check();
include __DIR__ . '/layout.php';
include __DIR__ . '/config_writer.php';

$file = __DIR__ . '/../config/links.php';

function admin_links_default_config(){
    return array(
        'settings' => array(
            'enabled' => 1,
            'home_count' => 15,
            'inner_min_count' => 3,
            'inner_max_count' => 6,
            'new_window' => 1,
            'nofollow' => 1,
            'auto_domain_links' => 1,
        ),
        'items' => array(),
    );
}

function admin_links_load($file){
    $cfg = is_file($file) ? include $file : array();
    if(!is_array($cfg)) $cfg = array();
    if(isset($cfg[0]) && is_array($cfg[0])){
        $cfg = array(
            'settings' => admin_links_default_config()['settings'],
            'items' => array_map(function($item){
                return array(
                    'enabled' => 1,
                    'theme' => $item['theme'] ?? 'industrial',
                    'weight' => intval($item['weight'] ?? 1),
                    'name' => $item['name'] ?? '',
                    'url' => $item['url'] ?? '',
                );
            }, $cfg),
        );
    }
    $default = admin_links_default_config();
    $cfg['settings'] = array_merge($default['settings'], $cfg['settings'] ?? array());
    $cfg['items'] = $cfg['items'] ?? array();
    return $cfg;
}

function admin_links_save($file, $cfg){
    admin_backup_file($file);
    $export = "<?php\n// 客户端本地友情链接配置，授权中心不参与。\nreturn " . var_export($cfg, true) . ";\n";
    $ok = (bool)file_put_contents($file, $export, LOCK_EX);
    if($ok && function_exists('static_cache_clear')) static_cache_clear();
    return $ok;
}

function admin_links_norm_url($url){
    $url = trim((string)$url);
    if($url === '') return '';
    if(!preg_match('#^https?://#i', $url)) $url = 'https://' . $url;
    return $url;
}

function admin_links_paginate($items, $page, $pageSize){
    $total = count($items);
    $pageSize = max(10, min(100, intval($pageSize)));
    $pages = max(1, (int)ceil($total / $pageSize));
    $page = max(1, min($pages, intval($page)));
    return array(array_slice($items, ($page - 1) * $pageSize, $pageSize, true), $total, $pages, $page, $pageSize);
}

function admin_links_page_url($pageNo){
    $params = $_GET;
    $params['page'] = $pageNo;
    return cms_admin_url('links.php') . '?' . http_build_query($params);
}

$themes = admin_site_themes();
$cfg = admin_links_load($file);
$message = '';
$error = '';

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $action = $_POST['action'] ?? '';
    if($action === 'save_settings'){
        $cfg['settings'] = array(
            'enabled' => isset($_POST['enabled']) ? 1 : 0,
            'home_count' => max(1, min(50, intval($_POST['home_count'] ?? 15))),
            'inner_min_count' => max(1, min(20, intval($_POST['inner_min_count'] ?? 3))),
            'inner_max_count' => max(1, min(20, intval($_POST['inner_max_count'] ?? 6))),
            'new_window' => isset($_POST['new_window']) ? 1 : 0,
            'nofollow' => isset($_POST['nofollow']) ? 1 : 0,
            'auto_domain_links' => isset($_POST['auto_domain_links']) ? 1 : 0,
        );
        if($cfg['settings']['inner_min_count'] > $cfg['settings']['inner_max_count']){
            $tmp = $cfg['settings']['inner_min_count'];
            $cfg['settings']['inner_min_count'] = $cfg['settings']['inner_max_count'];
            $cfg['settings']['inner_max_count'] = $tmp;
        }
        $message = admin_links_save($file, $cfg) ? '友链规则已保存。' : '保存失败，请检查 config/links.php 权限。';
    }elseif($action === 'add_link'){
        $name = trim((string)($_POST['name'] ?? ''));
        $url = admin_links_norm_url($_POST['url'] ?? '');
        $theme = $_POST['theme'] ?? 'industrial';
        $weight = max(1, min(10, intval($_POST['weight'] ?? 1)));
        if($name === '' || $url === ''){
            $error = '站点名称和 URL 不能为空。';
        }elseif(!isset($themes[$theme])){
            $error = '主题分类无效。';
        }else{
            $cfg['items'][] = array('enabled'=>1, 'theme'=>$theme, 'weight'=>$weight, 'name'=>$name, 'url'=>$url);
            $message = admin_links_save($file, $cfg) ? '友情链接已添加。' : '保存失败，请检查 config/links.php 权限。';
        }
    }elseif($action === 'update_links'){

        $items = $cfg['items'];
        foreach(($_POST['links'] ?? array()) as $row){
            $idx = intval($row['idx'] ?? -1);
            if($idx < 0 || !isset($items[$idx])) continue;
            $name = trim((string)($row['name'] ?? ''));
            $url = admin_links_norm_url($row['url'] ?? '');
            if($name === '' || $url === '') continue;
            $theme = $row['theme'] ?? 'industrial';
            if(!isset($themes[$theme])) $theme = 'industrial';
            $items[$idx] = array(
                'enabled' => isset($row['enabled']) ? 1 : 0,
                'theme' => $theme,
                'weight' => max(1, min(10, intval($row['weight'] ?? 1))),
                'name' => $name,
                'url' => $url,
            );
        }
        $cfg['items'] = $items;
        $message = admin_links_save($file, $cfg) ? '友情链接列表已更新。' : '保存失败，请检查 config/links.php 权限。';
    }elseif($action === 'delete_selected'){
        $delete = array_map('intval', $_POST['delete_ids'] ?? array());
        $items = array();
        foreach($cfg['items'] as $idx=>$item){
            if(in_array((int)$idx, $delete, true)) continue;
            $items[] = $item;
        }
        $cfg['items'] = $items;
        $message = admin_links_save($file, $cfg) ? '已删除选中的友情链接。' : '保存失败，请检查 config/links.php 权限。';
    }elseif($action === 'clear_links'){
        $count = count($cfg['items']);
        $cfg['items'] = array();
        $message = admin_links_save($file, $cfg) ? '友链列表已清空：' . intval($count) . ' 条。' : '保存失败，请检查 config/links.php 权限。';
    }
    $cfg = admin_links_load($file);
}

$pageSize = intval($_GET['page_size'] ?? 20);
$page = intval($_GET['page'] ?? 1);
list($pageItems, $linkTotal, $linkPages, $page, $pageSize) = admin_links_paginate($cfg['items'], $page, $pageSize);

admin_header('友情链接');
?>
<?php if($message): ?><div class="notice"><?php echo admin_h($message); ?></div><?php endif; ?>
<?php if($error): ?><div class="error"><?php echo admin_h($error); ?></div><?php endif; ?>

<div class="card">
    <h2>站群友链规则</h2>
    <p class="help">本功能只在当前客户端本地生效。系统可自动读取 <code>/config/domain.php</code> 和 <code>/config/domain_auto.php</code> 中的域名，按“同主题、排除自己、每日稳定随机”的规则展示友链。</p>
    <form method="post" class="config-form">
        <input type="hidden" name="action" value="save_settings">
        <div class="friend-rule-checks">
            <label><input type="checkbox" name="enabled" value="1" <?php echo !empty($cfg['settings']['enabled'])?'checked':''; ?>> <span>开启友情链接展示</span></label>
            <label><input type="checkbox" name="auto_domain_links" value="1" <?php echo !empty($cfg['settings']['auto_domain_links'])?'checked':''; ?>> <span>自动读取已解析域名生成友链</span></label>
            <label><input type="checkbox" name="new_window" value="1" <?php echo !empty($cfg['settings']['new_window'])?'checked':''; ?>> <span>新窗口打开</span></label>
            <label><input type="checkbox" name="nofollow" value="1" <?php echo !empty($cfg['settings']['nofollow'])?'checked':''; ?>> <span>添加 nofollow</span></label>
        </div>
        <div class="form-grid">
            <label>首页展示数量<input type="number" name="home_count" value="<?php echo intval($cfg['settings']['home_count']); ?>" min="1" max="50"></label>
            <label>内页最少数量<input type="number" name="inner_min_count" value="<?php echo intval($cfg['settings']['inner_min_count']); ?>" min="1" max="20"></label>
            <label>内页最多数量<input type="number" name="inner_max_count" value="<?php echo intval($cfg['settings']['inner_max_count']); ?>" min="1" max="20"></label>
        </div>
        <p><button type="submit">保存规则</button></p>
    </form>
</div>

<div class="card">
    <h2>添加同主题友链</h2>
    <form method="post" class="config-form">
        <input type="hidden" name="action" value="add_link">
        <div class="form-grid">
            <label>站点名称<input name="name" placeholder="例如：某某企业服务网"></label>
            <label>URL 地址<input name="url" placeholder="https://www.example.com"></label>
            <label>主题分类<select name="theme"><?php foreach($themes as $k=>$v): ?><option value="<?php echo admin_h($k); ?>"><?php echo admin_h($v . ' / ' . $k); ?></option><?php endforeach; ?></select></label>
            <label>权重分组<select name="weight"><option value="1">普通权重</option><option value="2">中等权重</option><option value="3">较高权重</option><option value="5">重点权重</option></select></label>
        </div>
        <p><button type="submit">添加友链</button></p>
    </form>
</div>

<div class="card">
    <h2>友链列表</h2>
    <form method="post" id="linkListForm">
        <input type="hidden" name="action" value="delete_selected" id="linkAction">
        <div class="cc-table-toolbar">
            <div class="cc-batch-actions">
                <button type="submit" class="btn small danger" onclick="document.getElementById('linkAction').value='delete_selected'">删除选中</button>
                <button type="submit" class="btn small danger ghost" data-confirm="确定清空全部友情链接吗？此操作不可恢复。" onclick="document.getElementById('linkAction').value='clear_links'">清空</button>
                <span>共 <?php echo intval($linkTotal); ?> 条，第 <?php echo intval($page); ?>/<?php echo intval($linkPages); ?> 页</span>
            </div>
            <div class="cc-page-size-form">
                <label>每页
                <select onchange="location.href='<?php echo admin_h(cms_admin_url('links.php')); ?>?page=1&page_size='+this.value">
                    <?php foreach(array(10,20,50,100) as $size): ?><option value="<?php echo intval($size); ?>" <?php echo $pageSize===$size?'selected':''; ?>><?php echo intval($size); ?> 条</option><?php endforeach; ?>
                </select>
                </label>
            </div>
        </div>
        <table class="content-record-table friend-inline-table">
            <tr><th><input type="checkbox" data-check-all="links"></th><th>启用</th><th>站点名称</th><th>URL 地址</th><th>主题</th><th>权重</th><th>操作</th></tr>
            <?php foreach($pageItems as $idx=>$item): ?>
            <tr>
                <td><input type="checkbox" name="delete_ids[]" value="<?php echo intval($idx); ?>" class="link-check"><input type="hidden" name="links[<?php echo intval($idx); ?>][idx]" value="<?php echo intval($idx); ?>"></td>
                <td><input type="checkbox" name="links[<?php echo intval($idx); ?>][enabled]" value="1" <?php echo !empty($item['enabled'])?'checked':''; ?>></td>
                <td><input name="links[<?php echo intval($idx); ?>][name]" value="<?php echo admin_h($item['name'] ?? ''); ?>"></td>
                <td><input name="links[<?php echo intval($idx); ?>][url]" value="<?php echo admin_h($item['url'] ?? ''); ?>"></td>
                <td><select name="links[<?php echo intval($idx); ?>][theme]">
                    <?php foreach($themes as $k=>$v): ?><option value="<?php echo admin_h($k); ?>" <?php echo (($item['theme'] ?? '')===$k)?'selected':''; ?>><?php echo admin_h($v . ' / ' . $k); ?></option><?php endforeach; ?>
                </select></td>
                <td><input type="number" name="links[<?php echo intval($idx); ?>][weight]" value="<?php echo intval($item['weight'] ?? 1); ?>" min="1" max="10"></td>
                <td><button type="submit" class="btn small" onclick="document.getElementById('linkAction').value='update_links'">保存</button></td>
            </tr>
            <?php endforeach; ?>
            <?php if(empty($cfg['items'])): ?><tr><td colspan="7">暂无友链，请先添加。</td></tr><?php endif; ?>
        </table>
        <?php if($linkPages > 1): ?>
        <div class="pager cc-pager">
            <?php if($page > 1): ?><a class="btn small ghost" href="<?php echo admin_h(admin_links_page_url($page - 1)); ?>">上一页</a><?php endif; ?>
            <span>第 <?php echo intval($page); ?> / <?php echo intval($linkPages); ?> 页</span>
            <?php if($page < $linkPages): ?><a class="btn small ghost" href="<?php echo admin_h(admin_links_page_url($page + 1)); ?>">下一页</a><?php endif; ?>
        </div>
        <?php endif; ?>
    </form>
</div>
<script>
(function(){
    var checkAll = document.querySelector('[data-check-all="links"]');
    if(!checkAll) return;
    checkAll.addEventListener('change', function(){
        document.querySelectorAll('.link-check').forEach(function(box){ box.checked = checkAll.checked; });
    });
})();
</script>
<?php admin_footer(); ?>
