<?php
$nosession = true;
$nosecu = true;
include("./includes/common.php");
if(!isset($_SESSION)) session_start();

function ensure_folder_share_columns_for_view($DB){
    static $inited = false;
    if($inited) return;
    $inited = true;
    $columns = $DB->getAll("SHOW COLUMNS FROM pre_folder");
    $exists = [];
    foreach((array)$columns as $col){
        if(isset($col['Field'])) $exists[$col['Field']] = true;
    }
    if(!isset($exists['share_key'])) $DB->exec("ALTER TABLE pre_folder ADD COLUMN share_key varchar(64) DEFAULT NULL");
    if(!isset($exists['share_need_pwd'])) $DB->exec("ALTER TABLE pre_folder ADD COLUMN share_need_pwd tinyint(1) NOT NULL DEFAULT 0");
    if(!isset($exists['share_pwd'])) $DB->exec("ALTER TABLE pre_folder ADD COLUMN share_pwd varchar(255) DEFAULT NULL");
    if(!isset($exists['share_notice'])) $DB->exec("ALTER TABLE pre_folder ADD COLUMN share_notice text");
}

ensure_folder_share_columns_for_view($DB);

function generate_share_key($DB, $folder_id) {
    $key = md5($folder_id . time() . rand());
    $DB->exec("UPDATE pre_folder SET share_key=:k WHERE folder_id=:id", [':k'=>$key, ':id'=>$folder_id]);
    return $key;
}

$shareKey = isset($_GET['key']) ? trim($_GET['key']) : '';
$inputPwd = isset($_GET['pwd']) ? trim($_GET['pwd']) : null;
if($shareKey === '') exit('分享链接无效');

$folderRow = $DB->getRow("SELECT * FROM pre_folder WHERE share_key=:k LIMIT 1", [':k'=>$shareKey]);
if(!$folderRow) exit('分享链接不存在或已失效');

$isOwner = $islogin2 && intval($uid) === intval($folderRow['uid']);
if(intval($folderRow['share_need_pwd']) === 1 && !$isOwner){
    if($inputPwd === null || $inputPwd !== (string)$folderRow['share_pwd']){
        ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>请输入访问密码 - <?php echo $conf['title']; ?></title>
    <link href="https://s4.zstatic.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="./assets/css/folder-share.css" rel="stylesheet">
    <style>
        .pwd-body {
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            padding: 20px;
        }
        .pwd-card {
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(20px);
            border-radius: 24px;
            padding: 48px 40px;
            width: 100%;
            max-width: 420px;
            text-align: center;
            box-shadow: 0 25px 80px rgba(0,0,0,0.3);
            animation: slideUp 0.5s ease;
        }
        @keyframes slideUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .pwd-icon {
            width: 90px;
            height: 90px;
            background: var(--gradient-1);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 28px;
            color: #fff;
            font-size: 36px;
            box-shadow: var(--shadow-lg);
        }
        .pwd-title {
            font-size: 26px;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 10px;
        }
        .pwd-subtitle {
            font-size: 15px;
            color: #6b7280;
            margin-bottom: 32px;
        }
        .pwd-input-group {
            position: relative;
            margin-bottom: 24px;
        }
        .pwd-input {
            width: 100%;
            padding: 16px 20px;
            border: 2px solid #e5e7eb;
            border-radius: var(--radius);
            font-size: 16px;
            transition: all 0.3s;
            outline: none;
            background: #f9fafb;
        }
        .pwd-input:focus {
            border-color: var(--primary);
            background: #fff;
            box-shadow: 0 0 0 4px rgba(6, 182, 212, 0.1);
        }
        .pwd-btn {
            width: 100%;
            padding: 16px;
            background: var(--gradient-1);
            color: #fff;
            border: none;
            border-radius: var(--radius);
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: var(--shadow);
        }
        .pwd-btn:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }
        .pwd-back {
            margin-top: 24px;
            font-size: 14px;
        }
        .pwd-back a {
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
        }
        .pwd-back a:hover {
            text-decoration: underline;
        }
        .pwd-error {
            background: #fee2e2;
            color: #dc2626;
            padding: 14px;
            border-radius: var(--radius);
            margin-bottom: 20px;
            font-size: 14px;
            display: none;
            font-weight: 500;
        }
        .pwd-error.show {
            display: block;
            animation: shake 0.5s ease;
        }
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-10px); }
            75% { transform: translateX(10px); }
        }
        @media (max-width: 480px) {
            .pwd-card {
                padding: 36px 24px;
            }
            .pwd-icon {
                width: 72px;
                height: 72px;
                font-size: 28px;
            }
            .pwd-title {
                font-size: 22px;
            }
        }
    </style>
</head>
<body class="pwd-body">
    <div class="pwd-card">
        <div class="pwd-icon">
            <i class="fa fa-lock"></i>
        </div>
        <h1 class="pwd-title">访问受限</h1>
        <p class="pwd-subtitle">该文件夹已加密，请输入访问密码</p>
        <div class="pwd-error" id="error-msg">
            <i class="fa fa-exclamation-circle"></i> 密码错误，请重试
        </div>
        <form method="get" action="" onsubmit="return handleSubmit()">
            <input type="hidden" name="key" value="<?php echo htmlspecialchars($shareKey); ?>">
            <div class="pwd-input-group">
                <input type="password" name="pwd" class="pwd-input" placeholder="请输入访问密码" required autofocus>
            </div>
            <button type="submit" class="pwd-btn">
                <i class="fa fa-unlock"></i> 进入文件夹
            </button>
        </form>
        <div class="pwd-back">
            <a href="javascript:history.back();"><i class="fa fa-arrow-left"></i> 返回上一页</a>
        </div>
    </div>
    <script>
        function handleSubmit() {
            return true;
        }
        <?php if($inputPwd !== null && $inputPwd !== (string)$folderRow['share_pwd']): ?>
        document.getElementById('error-msg').classList.add('show');
        <?php endif; ?>
    </script>
</body>
</html>
        <?php
        exit;
    }
}

$childrenFolders = $DB->getAll("SELECT folder_id,name,share_key,updated_at FROM pre_folder WHERE uid=:uid AND parent_id=:pid ORDER BY sort ASC, folder_id DESC", [':uid'=>$folderRow['uid'], ':pid'=>$folderRow['folder_id']]);
$files = $DB->getAll("SELECT id,name,size,type,hash,addtime FROM pre_file WHERE uid=:uid AND folder_id=:pid ORDER BY id DESC", [':uid'=>$folderRow['uid'], ':pid'=>$folderRow['folder_id']]);

$totalFolders = count($childrenFolders);
$totalFiles = count($files);

function getFileIcon($filename) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $icons = [
        'folder' => 'fa-folder',
        'image' => ['jpg','jpeg','png','gif','bmp','webp','svg','ico'],
        'video' => ['mp4','avi','mkv','mov','wmv','flv','webm'],
        'audio' => ['mp3','wav','flac','aac','ogg','wma','m4a'],
        'document' => ['doc','docx','pdf','txt','rtf'],
        'spreadsheet' => ['xls','xlsx','csv'],
        'presentation' => ['ppt','pptx'],
        'archive' => ['zip','rar','7z','tar','gz','bz2'],
        'code' => ['php','js','html','css','py','java','cpp','c','go','rs','json','xml','sql'],
        'executable' => ['exe','msi','dmg','pkg','deb','rpm']
    ];
    
    foreach($icons as $type => $exts) {
        if($type === 'folder') continue;
        if(in_array($ext, $exts)) {
            return $type;
        }
    }
    return 'file';
}

function getFileIconClass($type) {
    $classes = [
        'folder' => 'icon-folder',
        'image' => 'icon-image',
        'video' => 'icon-video',
        'audio' => 'icon-audio',
        'document' => 'icon-document',
        'spreadsheet' => 'icon-spreadsheet',
        'presentation' => 'icon-presentation',
        'archive' => 'icon-archive',
        'code' => 'icon-code',
        'executable' => 'icon-executable',
        'file' => 'icon-file'
    ];
    return $classes[$type] ?? 'icon-file';
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title><?php echo htmlspecialchars($folderRow['name']); ?> - <?php echo $conf['title']; ?></title>
    <meta name="description" content="<?php echo $conf['title']; ?> - 文件夹分享">
    <link href="https://s4.zstatic.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="./assets/css/folder-share.css" rel="stylesheet">
</head>
<body>
    <div class="floating-shapes">
        <div class="floating-shape"></div>
        <div class="floating-shape"></div>
        <div class="floating-shape"></div>
        <div class="floating-shape"></div>
    </div>

    <header class="header-section">
        <div class="container">
            <div class="folder-icon-wrapper">
                <i class="fa fa-folder-open"></i>
            </div>
            <h1 class="folder-title"><?php echo htmlspecialchars($folderRow['name']); ?></h1>
            <div class="folder-meta">
                <span><i class="fa fa-calendar-o"></i> <?php echo htmlspecialchars($folderRow['updated_at']); ?> 更新</span>
            </div>
        </div>
    </header>

    <main class="content-section">
        <div class="container">
            <div class="stats-cards">
                <div class="stat-card folders">
                    <i class="fa fa-folder"></i>
                    <div class="stat-value"><?php echo $totalFolders; ?></div>
                    <div class="stat-label">子文件夹</div>
                </div>
                <div class="stat-card files">
                    <i class="fa fa-file"></i>
                    <div class="stat-value"><?php echo $totalFiles; ?></div>
                    <div class="stat-label">文件</div>
                </div>
            </div>

            <?php if(!empty($folderRow['share_notice'])){ ?>
            <div class="glass-card notice-card">
                <div class="file-list-header">
                    <i class="fa fa-bullhorn"></i>
                    公告
                </div>
                <div class="notice-content">
                    <?php echo $folderRow['share_notice']; ?>
                </div>
            </div>
            <?php } ?>

            <div class="glass-card file-list-card">
                <div class="file-list-header">
                    <i class="fa fa-files-o"></i>
                    文件列表
                </div>
                <div class="card-body" style="padding: 0;">
                    <?php if($totalFolders === 0 && $totalFiles === 0){ ?>
                    <div class="empty-state">
                        <i class="fa fa-folder-open-o"></i>
                        <p>该文件夹为空</p>
                    </div>
                    <?php } else { ?>
                    <ul class="file-list">
                        <?php foreach((array)$childrenFolders as $f){ 
                            $subKey = !empty($f['share_key']) ? $f['share_key'] : generate_share_key($DB, $f['folder_id']);
                            $subFolderUrl = './folder.php?key='.urlencode($subKey);
                            $iconMap = ['fa-folder'];
                            $faIcon = 'fa-folder';
                        ?>
                        <li class="file-item is-folder">
                            <div class="file-icon icon-folder">
                                <i class="fa fa-folder"></i>
                            </div>
                            <div class="file-info">
                                <div class="file-name">
                                    <a href="<?php echo $subFolderUrl; ?>"><?php echo htmlspecialchars($f['name']); ?></a>
                                </div>
                                <div class="file-meta">
                                    <span><i class="fa fa-folder-o"></i> 文件夹</span>
                                    <span><i class="fa fa-clock-o"></i> <?php echo htmlspecialchars($f['updated_at']); ?></span>
                                </div>
                            </div>
                            <div class="file-action">
                                <a href="<?php echo $subFolderUrl; ?>" class="btn btn-primary">
                                    <i class="fa fa-arrow-right"></i>
                                    <span>进入</span>
                                </a>
                            </div>
                        </li>
                        <?php } ?>
                        <?php foreach((array)$files as $f){ 
                            $fileType = getFileIcon($f['name']);
                            $iconClass = getFileIconClass($fileType);
                            $iconMap = [
                                'image' => 'fa-file-image-o',
                                'video' => 'fa-file-video-o',
                                'audio' => 'fa-file-audio-o',
                                'document' => 'fa-file-text-o',
                                'spreadsheet' => 'fa-file-excel-o',
                                'presentation' => 'fa-file-powerpoint-o',
                                'archive' => 'fa-file-zip-o',
                                'code' => 'fa-file-code-o',
                                'executable' => 'fa-cog',
                                'file' => 'fa-file-o'
                            ];
                            $faIcon = $iconMap[$fileType] ?? 'fa-file-o';
                        ?>
                        <li class="file-item">
                            <div class="file-icon <?php echo $iconClass; ?>">
                                <i class="fa <?php echo $faIcon; ?>"></i>
                            </div>
                            <div class="file-info">
                                <div class="file-name">
                                    <a href="<?php echo './file.php?hash='.urlencode($f['hash']); ?>" target="_blank">
                                        <?php echo htmlspecialchars($f['name']); ?>
                                    </a>
                                </div>
                                <div class="file-meta">
                                    <span><i class="fa fa-database"></i> <?php echo size_format($f['size']); ?></span>
                                    <span><i class="fa fa-clock-o"></i> <?php echo htmlspecialchars($f['addtime']); ?></span>
                                </div>
                            </div>
                            <div class="file-action">
                                <a href="<?php echo './file.php?hash='.urlencode($f['hash']); ?>" target="_blank" class="btn btn-success">
                                    <i class="fa fa-download"></i>
                                    <span>下载</span>
                                </a>
                            </div>
                        </li>
                        <?php } ?>
                    </ul>
                    <?php } ?>
                </div>
            </div>
        </div>
    </main>

    <footer class="footer-section">
        <div class="container">
            <p>由 <a href="./"><?php echo $conf['title']; ?></a> 提供分享服务</p>
        </div>
    </footer>
</body>
</html>