<?php
require_once dirname(__DIR__) . '/lib/boardroom-auth.php';

boardroom_session_start();

$indexRoot = boardroom_index_root();
$dataRoot = $indexRoot . DIRECTORY_SEPARATOR . 'data';
$sub = boardroom_norm_rel($_GET['p'] ?? '');

if (!is_dir($dataRoot)) {
    http_response_code(500);
    exit('data folder not found');
}

$rel = 'data' . ($sub !== '' ? '/' . $sub : '');
$abs = $dataRoot . ($sub !== '' ? DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $sub) : '');

if (!is_dir($abs) || strpos(realpath($abs), realpath($dataRoot)) !== 0) {
    http_response_code(404);
    exit('Not found');
}

$needsLogin = boardroom_path_is_protected($rel) && !boardroom_is_logged_in();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['boardroom_password'])) {
    $r = boardroom_login((string)$_POST['boardroom_password']);
    if ($r['ok']) {
        header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?') . ($sub !== '' ? '?p=' . rawurlencode($sub) : ''));
        exit;
    }
    $loginError = $r['message'];
}

if (isset($_GET['logout'])) {
    boardroom_logout();
    header('Location: index.php' . ($sub !== '' ? '?p=' . rawurlencode($sub) : ''));
    exit;
}

if ($needsLogin) {
    $hasPw = boardroom_has_password();
    header('Content-Type: text/html; charset=utf-8');
    ?>
<!DOCTYPE html>
<html lang="ja"><head><meta charset="utf-8"><title>Password Required</title>
<style>
body{font-family:sans-serif;max-width:420px;margin:40px auto;padding:20px}
.box{border:1px solid #ccc;padding:24px;border-radius:8px;background:#fafafa}
input{width:100%;padding:10px;margin:8px 0;box-sizing:border-box}
button{padding:10px 20px;background:#2d3e50;color:#fff;border:none;border-radius:4px;cursor:pointer}
.err{color:#c00;margin-bottom:10px}
</style></head><body>
<div class="box">
<h2>🔒 Password Required</h2>
<p>この資料は理事会関係者のみ閲覧できます。</p>
<?php if (!$hasPw): ?>
<p class="err">パスワードが未設定です。管理者は R-Scope で「理事会パスワード」を設定してください。</p>
<?php else: ?>
<?php if (!empty($loginError)): ?><p class="err"><?= htmlspecialchars($loginError) ?></p><?php endif; ?>
<form method="post">
<label>パスワード</label>
<input type="password" name="boardroom_password" autofocus required>
<button type="submit">ログイン</button>
</form>
<?php endif; ?>
</div>
</body></html>
    <?php
    exit;
}

$entries = [];
foreach (scandir($abs) as $e) {
    if ($e === '.' || $e === '..') continue;
    if (function_exists('boardroom_is_news_archive_files_entry') && boardroom_is_news_archive_files_entry($e, $sub, $abs)) {
        continue;
    }
    if (function_exists('boardroom_is_browse_hidden')) {
        if (boardroom_is_browse_hidden($e, $sub, $abs)) continue;
    } elseif ($e !== '' && $e[0] === '.') {
        continue;
    } elseif (strcasecmp($e, 'files') === 0 && strcasecmp(basename($abs), 'News-Archive') === 0) {
        continue;
    } elseif (in_array(strtolower($e), ['index.php', 'file.php', '.htaccess', '.protected'], true)) {
        continue;
    }
    $entries[] = $e;
}
natcasesort($entries);

$parent = '';
if ($sub !== '') {
    $pos = strrpos($sub, '/');
    $parent = $pos === false ? '' : substr($sub, 0, $pos);
}

header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Board Room — <?= htmlspecialchars($sub ?: 'data') ?></title>
<style>
body{font-family:sans-serif;margin:16px}
a{color:#06c}
table{border-collapse:collapse;width:100%}
th,td{border-bottom:1px solid #ddd;padding:8px;text-align:left}
th{background:#f5f5f5}
.lock{color:#c00}
</style>
</head>
<body>
<p>
<?php if (boardroom_is_logged_in()): ?>
<a href="?logout=1<?= $sub !== '' ? '&amp;p=' . urlencode($sub) : '' ?>">ログアウト</a> |
<?php endif; ?>
<a href="<?= htmlspecialchars(dirname($_SERVER['SCRIPT_NAME'])) ?>/../Board-Room.php">Board Room</a>
</p>
<h2>📁 <?= htmlspecialchars($sub ?: 'data') ?></h2>
<table>
<tr><th>名前</th><th>種類</th></tr>
<?php if ($sub !== ''): ?>
<tr><td><a href="?p=<?= urlencode($parent) ?>">⤴ ..</a></td><td></td></tr>
<?php endif; ?>
<?php foreach ($entries as $e):
    $full = $abs . DIRECTORY_SEPARATOR . $e;
    $isDir = is_dir($full);
    $child = $sub === '' ? $e : $sub . '/' . $e;
    $childRel = 'data/' . $child;
    $prot = $isDir && boardroom_is_protected_dir($full);
?>
<tr>
<td>
<?php if ($isDir): ?>
<a href="?p=<?= urlencode($child) ?>"><?= $prot ? '🔒 ' : '' ?><?= htmlspecialchars($e) ?></a>
<?php else: ?>
<a href="file.php?p=<?= urlencode($child) ?>"><?= htmlspecialchars($e) ?></a>
<?php endif; ?>
</td>
<td><?= $isDir ? 'フォルダ' : 'ファイル' ?><?= $prot ? ' <span class="lock">protected</span>' : '' ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
