<?php
session_start();
require_once '../config.php';
require_once 'functions.php';

// 检查登录状态
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$message = '';
$message_type = '';

// 检查配置文件权限
$permission_check = check_config_permission();
if ($permission_check !== true) {
    $message = $permission_check;
    $message_type = 'danger';
}

// 添加友情链接
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_link'])) {
    $new_link = [
        'name' => safe_input($_POST['name']),
        'url' => safe_input($_POST['url']),
        'description' => safe_input($_POST['description']),
        'expire_type' => safe_input($_POST['expire_type']),
        'expire_date' => safe_input($_POST['expire_date'] ?? ''),
        'status' => 'active',
        'created_at' => date('Y-m-d H:i:s')
    ];

    // 处理自定义过期日期
    if ($new_link['expire_type'] === 'custom' && empty($new_link['expire_date'])) {
        $message = '请设置自定义过期日期！';
        $message_type = 'danger';
    } else {
        // 确保friend_links数组存在
        if (!isset($config['friend_links']) || !is_array($config['friend_links'])) {
            $config['friend_links'] = [];
        }
        
        $config['friend_links'][] = $new_link;

        if (save_config($config)) {
            $message = '友情链接添加成功！';
            $message_type = 'success';
        } else {
            $message = '友情链接添加失败，请检查文件权限！';
            $message_type = 'danger';
        }
    }
}

// 删除友情链接
if (isset($_GET['delete'])) {
    $index = intval($_GET['delete']);
    if (isset($config['friend_links'][$index])) {
        array_splice($config['friend_links'], $index, 1);
        if (save_config($config)) {
            $message = '友情链接删除成功！';
            $message_type = 'success';
        } else {
            $message = '友情链接删除失败，请检查文件权限！';
            $message_type = 'danger';
        }
    } else {
        $message = '友情链接不存在！';
        $message_type = 'danger';
    }
}

// 切换链接状态
if (isset($_GET['toggle_status'])) {
    $index = intval($_GET['toggle_status']);
    if (isset($config['friend_links'][$index])) {
        $config['friend_links'][$index]['status'] = 
            $config['friend_links'][$index]['status'] === 'active' ? 'inactive' : 'active';
        
        if (save_config($config)) {
            $message = '链接状态更新成功！';
            $message_type = 'success';
        } else {
            $message = '状态更新失败，请检查文件权限！';
            $message_type = 'danger';
        }
    }
}

$page_title = '友情链接';
?>
<?php include 'header.php'; ?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <div class="col-md-10 p-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2 class="mb-0">友情链接管理</h2>
                <span class="badge bg-primary"><?php echo count($config['friend_links'] ?? []); ?> 个链接</span>
            </div>

            <?php if ($message): ?>
            <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                <?php echo $message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>

            <style>
                .usage-guide {
                    background: #f8f9fa;
                    border: 1px solid #e9ecef;
                    border-radius: 8px;
                    padding: 1.5rem;
                    margin: 1.5rem 0;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                }
                .usage-guide h6 {
                    color: #2c3e50;
                    margin-bottom: 1rem;
                    font-weight: 600;
                    border-bottom: 2px solid #28a745;
                    padding-bottom: 0.5rem;
                }
                .code-example {
                    background: #2c3e50;
                    color: #ecf0f1;
                    padding: 1rem;
                    border-radius: 6px;
                    font-family: 'Courier New', monospace;
                    font-size: 0.85rem;
                    margin: 0.75rem 0;
                    border-left: 4px solid #28a745;
                }
                .link-card {
                    transition: transform 0.2s;
                    border: 1px solid #e9ecef;
                    border-radius: 10px;
                }
                .link-card:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
                }
                .status-badge {
                    font-size: 0.7rem;
                }
                .expired {
                    opacity: 0.6;
                    background-color: #f8f9fa;
                }
            </style>

            <div class="row">
                <div class="col-md-6">
                    <div class="card link-card">
                        <div class="card-header bg-primary text-white">
                            <i class="bi bi-plus-circle"></i> 添加友情链接
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <div class="mb-3">
                                    <label class="form-label">网站名称</label>
                                    <input type="text" class="form-control" name="name" placeholder="输入网站名称" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">网站URL</label>
                                    <input type="url" class="form-control" name="url" placeholder="https://example.com" required>
                                    <div class="form-text">请以 http:// 或 https:// 开头</div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">网站描述</label>
                                    <textarea class="form-control" name="description" rows="3" placeholder="输入网站描述（可选）"></textarea>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">有效期</label>
                                    <select class="form-select" name="expire_type" id="expireType" required>
                                        <option value="permanent">永久</option>
                                        <option value="1month">1个月</option>
                                        <option value="1year">1年</option>
                                        <option value="custom">自定义</option>
                                    </select>
                                </div>
                                <div class="mb-3 d-none" id="customDateGroup">
                                    <label class="form-label">过期时间</label>
                                    <input type="date" class="form-control" name="expire_date" min="<?php echo date('Y-m-d'); ?>">
                                    <div class="form-text">设置链接的过期日期</div>
                                </div>
                                <button type="submit" name="add_link" class="btn btn-primary w-100">
                                    <i class="bi bi-check-lg"></i> 添加链接
                                </button>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="card link-card">
                        <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-link-45deg"></i> 友情链接列表</span>
                            <span class="badge bg-light text-dark"><?php echo count($config['friend_links'] ?? []); ?> 个</span>
                        </div>
                        <div class="card-body">
                            <?php if (empty($config['friend_links'])): ?>
                            <div class="text-center py-4">
                                <i class="bi bi-link-45deg display-1 text-muted"></i>
                                <p class="text-muted mt-3">暂无友情链接</p>
                            </div>
                            <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php 
                                $active_links = 0;
                                foreach ($config['friend_links'] as $index => $link): 
                                    if ($link['status'] === 'active') $active_links++;
                                ?>
                                <div class="list-group-item px-0 <?php echo $link['status'] === 'inactive' ? 'expired' : ''; ?>">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div style="flex: 1;">
                                            <div class="d-flex align-items-center mb-1">
                                                <h6 class="mb-0 me-2"><?php echo $link['name']; ?></h6>
                                                <span class="badge <?php echo $link['status'] === 'active' ? 'bg-success' : 'bg-secondary'; ?> status-badge">
                                                    <?php echo $link['status'] === 'active' ? '活跃' : '禁用'; ?>
                                                </span>
                                            </div>
                                            <p class="mb-1 small">
                                                <a href="<?php echo $link['url']; ?>" target="_blank" class="text-decoration-none">
                                                    <i class="bi bi-box-arrow-up-right"></i> <?php echo $link['url']; ?>
                                                </a>
                                            </p>
                                            <?php if (!empty($link['description'])): ?>
                                            <p class="mb-1 text-muted small"><?php echo $link['description']; ?></p>
                                            <?php endif; ?>
                                            <div class="d-flex justify-content-between align-items-center mt-2">
                                                <small class="text-muted">
                                                    <i class="bi bi-calendar"></i> 
                                                    有效期: 
                                                    <?php
                                                    switch($link['expire_type']) {
                                                        case 'permanent': echo '永久'; break;
                                                        case '1month': echo '1个月'; break;
                                                        case '1year': echo '1年'; break;
                                                        case 'custom': echo $link['expire_date']; break;
                                                        default: echo $link['expire_type'];
                                                    }
                                                    ?>
                                                </small>
                                                <small class="text-muted">
                                                    <i class="bi bi-clock"></i> <?php echo $link['created_at'] ?? '未知'; ?>
                                                </small>
                                            </div>
                                        </div>
                                        <div class="ms-3 d-flex flex-column gap-1">
                                            <a href="?toggle_status=<?php echo $index; ?>" class="btn btn-sm <?php echo $link['status'] === 'active' ? 'btn-warning' : 'btn-success'; ?>" 
                                               title="<?php echo $link['status'] === 'active' ? '禁用链接' : '启用链接'; ?>">
                                                <i class="bi bi-power"></i>
                                            </a>
                                            <a href="?delete=<?php echo $index; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('确定删除这个友情链接吗？')">
                                                <i class="bi bi-trash"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="mt-3 pt-3 border-top">
                                <small class="text-muted">
                                    <i class="bi bi-info-circle"></i> 
                                    总计: <?php echo count($config['friend_links']); ?> 个链接, 
                                    活跃: <?php echo $active_links; ?> 个, 
                                    禁用: <?php echo count($config['friend_links']) - $active_links; ?> 个
                                </small>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 使用说明放在功能后面 -->
            <div class="usage-guide">
                <h6>📝 友情链接使用说明</h6>
                <p><strong>模板调用方法：</strong></p>
                <div class="code-example">
                    {if $friend_links}<br>
                    &nbsp;&nbsp;{foreach $friend_links as $link}<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;&lt;a href="{$link.url}" target="_blank" title="{$link.description}"&gt;{$link.name}&lt;/a&gt;<br>
                    &nbsp;&nbsp;{/foreach}<br>
                    {/if}
                </div>
                <p><strong>显示位置：</strong>友情链接默认显示在侧边栏底部。</p>
                <p><strong>有效期说明：</strong></p>
                <div class="row">
                    <div class="col-md-6">
                        <ul class="list-unstyled">
                            <li><i class="bi bi-infinity text-primary"></i> <strong>永久</strong> - 链接长期有效</li>
                            <li><i class="bi bi-calendar-month text-info"></i> <strong>1个月</strong> - 链接有效期为1个月</li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <ul class="list-unstyled">
                            <li><i class="bi bi-calendar-year text-success"></i> <strong>1年</strong> - 链接有效期为1年</li>
                            <li><i class="bi bi-calendar-date text-warning"></i> <strong>自定义</strong> - 可设置具体的过期日期</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdmirror.com/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.getElementById('expireType').addEventListener('change', function() {
    const type = this.value;
    const customDateGroup = document.getElementById('customDateGroup');

    if (type === 'custom') {
        customDateGroup.classList.remove('d-none');
    } else {
        customDateGroup.classList.add('d-none');
    }
});

// 设置最小日期为今天
document.addEventListener('DOMContentLoaded', function() {
    const today = new Date().toISOString().split('T')[0];
    document.querySelector('input[name="expire_date"]').min = today;
});
</script>
</body>
</html>