<?php
require_once __DIR__ . '/../config/config.php';
requireLogin();

// 權限檢查：只有 admin 可以管理帳號
if ($_SESSION['role'] !== 'admin') {
    die("您沒有權限訪問此頁面");
}

$success = '';
$error = '';

// 處理新增帳號
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $role = $_POST['role'] ?? 'staff';

    if (!empty($username) && !empty($password)) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        try {
            $stmt = $pdo->prepare("INSERT INTO admins (username, password, role) VALUES (?, ?, ?)");
            $stmt->execute([$username, $hashed_password, $role]);
            $success = '帳號已成功創建';
        } catch (PDOException $e) {
            $error = '創建失敗：' . ($e->getCode() == 23000 ? '用戶名已存在' : $e->getMessage());
        }
    } else {
        $error = '請填寫所有必填項';
    }
}

// 處理刪除帳號
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    // 不能刪除自己
    if ($id === (int)$_SESSION['admin_id']) {
        $error = '不能刪除當前登入的帳號';
    } else {
        $stmt = $pdo->prepare("DELETE FROM admins WHERE id = ?");
        $stmt->execute([$id]);
        $success = '帳號已成功刪除';
    }
}

// 獲取所有帳號
$admins = $pdo->query("SELECT * FROM admins ORDER BY created_at DESC")->fetchAll();

include __DIR__ . '/../includes/header.php';
?>

<div class="flex justify-between items-center mb-8">
    <div>
        <h1 class="text-2xl font-bold text-slate-800">帳號管理</h1>
        <p class="text-slate-500">管理系統管理員及工作人員帳號</p>
    </div>
    <button onclick="document.getElementById('add-modal').classList.remove('hidden')" 
        class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center shadow-sm transition">
        <i class="fas fa-user-plus mr-2"></i> 新增帳號
    </button>
</div>

<?php if ($success): ?>
    <div class="bg-green-50 text-green-600 p-4 rounded-lg mb-6 flex items-center">
        <i class="fas fa-check-circle mr-2"></i> <?php echo $success; ?>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="bg-red-50 text-red-600 p-4 rounded-lg mb-6 flex items-center">
        <i class="fas fa-exclamation-circle mr-2"></i> <?php echo $error; ?>
    </div>
<?php endif; ?>

<!-- Account List -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
    <div class="overflow-x-auto">
        <table class="w-full text-left">
            <thead class="bg-slate-50 border-b border-slate-100 text-slate-500 text-sm font-semibold">
                <tr>
                    <th class="px-6 py-4">用戶名</th>
                    <th class="px-6 py-4">權限</th>
                    <th class="px-6 py-4">創建日期</th>
                    <th class="px-6 py-4 text-right">操作</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php foreach ($admins as $admin): ?>
                <tr class="hover:bg-slate-50 transition">
                    <td class="px-6 py-4 font-medium text-slate-800"><?php echo htmlspecialchars($admin['username']); ?></td>
                    <td class="px-6 py-4">
                        <span class="px-2 py-1 rounded text-xs font-semibold <?php echo $admin['role'] === 'admin' ? 'bg-purple-100 text-purple-600' : 'bg-blue-100 text-blue-600'; ?>">
                            <?php echo $admin['role'] === 'admin' ? '管理員' : '工作人員'; ?>
                        </span>
                    </td>
                    <td class="px-6 py-4 text-slate-500 text-sm"><?php echo date('Y-m-d H:i', strtotime($admin['created_at'])); ?></td>
                    <td class="px-6 py-4 text-right">
                        <?php if ($admin['id'] != $_SESSION['admin_id']): ?>
                        <a href="?delete=<?php echo $admin['id']; ?>" onclick="return confirm('確定要刪除此帳號嗎？')" 
                            class="text-red-500 hover:text-red-700 transition">
                            <i class="fas fa-trash-alt"></i>
                        </a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add Modal -->
<div id="add-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl w-full max-w-md p-8 shadow-2xl transform transition-all">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-bold text-slate-800">新增帳號</h2>
            <button onclick="document.getElementById('add-modal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form action="accounts.php" method="POST" class="space-y-4">
            <input type="hidden" name="action" value="add">
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">用戶名</label>
                <input type="text" name="username" required 
                    class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">密碼</label>
                <input type="password" name="password" required 
                    class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">權限</label>
                <select name="role" class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
                    <option value="staff">工作人員</option>
                    <option value="admin">管理員</option>
                </select>
            </div>
            <div class="pt-4 flex gap-3">
                <button type="button" onclick="document.getElementById('add-modal').classList.add('hidden')" 
                    class="flex-1 px-4 py-2 border border-slate-200 text-slate-600 rounded-lg hover:bg-slate-50 transition">
                    取消
                </button>
                <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 shadow-lg transition">
                    確認新增
                </button>
            </div>
        </form>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
