<?php
require_once 'config.php';

// 获取数据库连接
$conn = getDBConnection();

// 获取基础URL
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://";
$domain = $_SERVER['HTTP_HOST'];
$baseUrl = $protocol . $domain;

// 处理上传结果
$alert = '';
if (isset($_GET['upload'])) {
    $alert = $_GET['upload'] === 'success' 
        ? '<div class="alert alert-success">图片上传成功！</div>' 
        : '<div class="alert alert-danger">'.htmlspecialchars($_GET['error']).'</div>';
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>星空图床</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
    <style>
        body {
            background-color: #f8f9fa;
            padding: 20px;
        }
       .gallery-container {
            max-width: 1200px;
            margin: 0 auto;
        }
       .table-img {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 4px;
            cursor: pointer;
            transition: transform 0.3s;
        }
       .table-img:hover {
            transform: scale(1.5);
            z-index: 10;
        }
       .upload-btn {
            background: linear-gradient(135deg, #6c5ce7, #a29bfe);
            border: none;
        }
       .copy-btn {
            cursor: pointer;
            transition: all 0.2s;
        }
       .copy-btn:hover {
            color: #6c5ce7;
        }
       .empty-state {
            text-align: center;
            padding: 50px 0;
            color: #636e72;
        }
       .table-responsive {
            overflow-x: auto; /* 使表格在水平方向可滚动 */
        }
       .table {
            min-width: 100%; /* 确保表格至少占据父元素的宽度 */
        }
        /* 上传进度条样式 */
       .progress {
            display: none; /* 初始隐藏进度条 */
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="gallery-container">
        <!-- 顶部导航 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1><i class="bi bi-images"></i> 星空图床</h1>
            <div>
                <a href="admin/login.php" class="btn btn-outline-secondary me-2">
                    <i class="bi bi-person"></i> 管理
                </a>
                <button class="btn btn-primary upload-btn" data-bs-toggle="modal" data-bs-target="#uploadModal">
                    <i class="bi bi-cloud-upload"></i> 上传
                </button>
            </div>
        </div>

        <?php echo $alert; ?>

        <!-- 图片表格 -->
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-light">
                    <tr>
                        <th width="80">ID</th>
                        <th width="120">预览</th>
                        <th>图片链接</th>
                        <th width="180">上传时间</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $sql = "SELECT id, filename, upload_time FROM images ORDER BY upload_time DESC";
                    $result = $conn->query($sql);
                    
                    if ($result->num_rows > 0) {
                        while($row = $result->fetch_assoc()) {
                            $imageUrl = "$baseUrl/uploads/" . $row['filename'];
                            echo '<tr>
                                    <td>#'.$row['id'].'</td>
                                    <td>
                                        <img src="'.$imageUrl.'" class="table-img" 
                                             data-bs-toggle="modal" data-bs-target="#imageModal"
                                             data-img="'.$imageUrl.'">
                                    </td>
                                    <td>
                                        <div class="input-group input-group-sm">
                                            <input type="text" class="form-control" value="'.$imageUrl.'" readonly>
                                            <button class="btn btn-outline-secondary copy-btn" onclick="copyToClipboard(this)">
                                                <i class="bi bi-clipboard"></i>
                                            </button>
                                        </div>
                                    </td>
                                    <td>'.date('Y-m-d H:i', strtotime($row['upload_time'])).'</td>
                                  </tr>';
                        }
                    } else {
                        echo '<tr>
                                <td colspan="4" class="text-center py-5">
                                    <i class="bi bi-images" style="font-size: 3rem; opacity: 0.5;"></i>
                                    <p class="mt-3 text-muted">暂无图片，请上传第一张图片</p>
                                </td>
                              </tr>';
                    }
                    $conn->close();
                    ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 上传模态框 (已移除验证码) -->
    <div class="modal fade" id="uploadModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-cloud-upload"></i> 上传图片</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="upload.php" method="post" enctype="multipart/form-data" id="uploadForm">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">选择图片文件</label>
                            <input type="file" class="form-control" name="image" accept="image/*" required>
                            <div class="form-text">支持 JPG/PNG/GIF 格式，最大 5MB</div>
                        </div>
                        <div class="progress">
                            <div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">上传</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 图片预览模态框 -->
    <div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">图片预览</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center p-0">
                    <img src="" id="modalImage" class="img-fluid" style="max-height: 70vh;">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <a href="#" id="downloadBtn" class="btn btn-primary" download>
                        <i class="bi bi-download"></i> 下载
                    </a>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 图片预览功能
        const imageModal = document.getElementById('imageModal');
        if (imageModal) {
            imageModal.addEventListener('show.bs.modal', function(event) {
                const button = event.relatedTarget;
                const imgSrc = button.getAttribute('data-img');
                document.getElementById('modalImage').src = imgSrc;
                document.getElementById('downloadBtn').href = imgSrc;
            });
        }

        // 复制链接功能
        function copyToClipboard(button) {
            const input = button.closest('.input-group').querySelector('input');
            input.select();
            document.execCommand('copy');
            
            const icon = button.querySelector('i');
            icon.className = 'bi bi-check2';
            setTimeout(() => {
                icon.className = 'bi bi-clipboard';
            }, 2000);
        }

        // 上传进度条功能
        const uploadForm = document.getElementById('uploadForm');
        if (uploadForm) {
            uploadForm.addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(this);
                const xhr = new XMLHttpRequest();
                xhr.upload.addEventListener('progress', function(event) {
                    if (event.lengthComputable) {
                        const percentComplete = (event.loaded / event.total) * 100;
                        const progressBar = document.querySelector('.progress-bar');
                        progressBar.style.width = percentComplete + '%';
                        progressBar.setAttribute('aria-valuenow', percentComplete);
                        progressBar.textContent = percentComplete + '%';
                    }
                });
                xhr.addEventListener('load', function() {
                    if (xhr.status === 200) {
                        location.reload(); // 上传成功后刷新页面
                    } else {
                        console.error('上传失败');
                    }
                });
                xhr.open('POST', 'upload.php', true);
                xhr.send(formData);
                const progress = document.querySelector('.progress');
                progress.style.display = 'block'; // 显示进度条
            });
        }
    </script>
</body>
</html>
