<?php
session_start();
require_once "config/database.php";

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: login.php");
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$users = [];

try {
    $stmt = $db->prepare("
        SELECT id, full_name, username, email, role, status, created_at
        FROM users
        ORDER BY id DESC
    ");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Query error: " . $e->getMessage());
}

function formatDateTime(?string $date): string
{
    $date = trim((string)$date);
    if ($date === '') {
        return '-';
    }

    $time = strtotime($date);
    if (!$time) {
        return $date;
    }

    return date('d/m/Y H:i', $time);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Users</title>
    <link rel="stylesheet" href="assets/css/app.css">
    <style>
        .admin-table {
            width: 100%;
            border-collapse: collapse;
            table-layout: auto;
        }

        .admin-table th,
        .admin-table td {
            padding: 14px 16px;
            vertical-align: middle;
            border-bottom: 1px solid #e5e7eb;
            font-size: 14px;
            color: #111827;
        }

        .admin-table thead th {
            background: #f8fafc;
            font-size: 15px;
            font-weight: 700;
            color: #0f172a;
            white-space: nowrap;
        }

        .admin-table tbody tr:hover {
            background: #fcfcfd;
        }

        .admin-table td:nth-child(2),
        .admin-table td:nth-child(4) {
            max-width: 220px;
            word-break: break-word;
        }

        .admin-table th:last-child,
        .admin-table td:last-child {
            width: 72px;
            min-width: 72px;
            text-align: center;
            white-space: nowrap;
        }

        .table-wrap {
            overflow-x: auto;
            border: 1px solid #e5e7eb;
            border-radius: 18px;
            background: #ffffff;
        }

        .badge {
            display: inline-flex;
            align-items: center;
            padding: 4px 10px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: 700;
            line-height: 1;
        }

        .badge.info {
            background: #eff6ff;
            color: #1d4ed8;
        }

        .badge.success {
            background: #ecfdf3;
            color: #027a48;
        }

        .badge.danger {
            background: #fef3f2;
            color: #b42318;
        }

        .chip {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 56px;
            padding: 6px 10px;
            border-radius: 999px;
            background: #f1f5f9;
            color: #0f172a;
            font-size: 12px;
            font-weight: 700;
        }

        .empty-state {
            padding: 20px;
            text-align: center;
            color: #6b7280;
        }

        .actions-cell {
            padding-left: 8px !important;
            padding-right: 8px !important;
        }

        .dropdown {
            position: relative;
            display: inline-block;
        }

        .dropdown-toggle {
            width: 34px;
            height: 34px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: none;
            border-radius: 10px;
            background: #f1f5f9;
            color: #0f172a;
            font-size: 20px;
            line-height: 1;
            cursor: pointer;
            transition: background 0.2s ease, opacity 0.2s ease;
            opacity: 0.65;
        }

        .admin-table tbody tr:hover .dropdown-toggle {
            opacity: 1;
            background: #e2e8f0;
        }

        .dropdown-toggle:hover {
            background: #e2e8f0;
            opacity: 1;
        }

        .dropdown-menu {
            position: absolute;
            top: calc(100% + 8px);
            right: 0;
            min-width: 180px;
            background: #ffffff;
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
            display: none;
            overflow: hidden;
            z-index: 999;
        }

        .dropdown-menu a {
            display: block;
            padding: 10px 14px;
            font-size: 13px;
            color: #111827;
            text-decoration: none;
        }

        .dropdown-menu a:hover {
            background: #f9fafb;
        }

        .dropdown-menu a.danger {
            color: #dc2626;
        }

        .dropdown-menu a.danger:hover {
            background: #fef2f2;
        }
        .btn-primary {
            display: inline-flex;
            align-items: center;
            padding: 8px 14px;
            background: #2563eb;
            color: #fff;
            font-size: 13px;
            font-weight: 600;
            border-radius: 8px;
            text-decoration: none;
        }

        .btn-primary:hover {
            background: #1d4ed8;
        }

        @media (max-width: 768px) {
            .admin-table th,
            .admin-table td {
                padding: 12px 10px;
                font-size: 13px;
            }

            .admin-table th:last-child,
            .admin-table td:last-child {
                width: 60px;
                min-width: 60px;
            }

            .dropdown-toggle {
                width: 30px;
                height: 30px;
                font-size: 18px;
            }
        }
    </style>
</head>
<body>
<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="hero">
            <div class="hero-top">
                <div>
                    <h1>Users</h1>
                    <p>Admin only page for viewing, editing, and managing registered users.</p>
                </div>
                <div class="welcome-badge">Admin</div>
            </div>
        </div>

        <div class="card">
            <div style="display:flex; justify-content:space-between; align-items:center; gap:12px; flex-wrap:wrap; margin-bottom:12px;">
                <div>
                    <div class="section-title">User List</div>
                    <div class="section-subtext">
                        Total: <strong><?php echo count($users); ?></strong> user(s)
                    </div>
                </div>

                <a href="add_user.php" class="btn-primary">
                    + Add New User
                </a>
            </div>

            <?php if (isset($_GET['deleted']) && $_GET['deleted'] == 1): ?>
                <div class="badge success" style="display:inline-flex; margin-bottom:12px;">
                    User deleted successfully.
                </div>
            <?php endif; ?>

            <?php if (isset($_GET['updated']) && $_GET['updated'] == 1): ?>
                <div class="badge success" style="display:inline-flex; margin-bottom:12px;">
                    User updated successfully.
                </div>
            <?php endif; ?>
            <?php if (isset($_GET['created']) && $_GET['created'] == 1): ?>
                <div class="badge success" style="display:inline-flex; margin-bottom:12px;">
                    User created successfully.
                </div>
            <?php endif; ?>

            <div class="table-wrap">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Full Name</th>
                            <th>Username</th>
                            <th>Email</th>
                            <th>Role</th>
                            <th>Status</th>
                            <th>Created At</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($users)): ?>
                            <?php foreach ($users as $user): ?>
                                <tr>
                                    <td>
                                        <span class="chip">
                                            <?php echo str_pad((int)$user['id'], 4, '0', STR_PAD_LEFT); ?>
                                        </span>
                                    </td>
                                    <td><?php echo htmlspecialchars($user['full_name'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars($user['username'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars($user['email'] ?? '-'); ?></td>
                                    <td>
                                        <span class="badge info">
                                            <?php echo htmlspecialchars($user['role'] ?? '-'); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if (($user['status'] ?? '') === 'active'): ?>
                                            <span class="badge success">Active</span>
                                        <?php else: ?>
                                            <span class="badge danger">
                                                <?php echo htmlspecialchars($user['status'] ?? '-'); ?>
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars(formatDateTime($user['created_at'] ?? '')); ?></td>
                                    <td class="actions-cell">
                                        <div class="dropdown">
                                            <button type="button" class="dropdown-toggle" aria-label="More actions">⋮</button>

                                            <div class="dropdown-menu">
                                                <a href="edit_user.php?id=<?php echo (int)$user['id']; ?>">✏️ Edit</a>
                                                <a href="reset_user_password.php?id=<?php echo (int)$user['id']; ?>">🔑 Reset Password</a>

                                                <?php if ((int)$user['id'] !== (int)($_SESSION['user_id'] ?? 0)): ?>
                                                    <a
                                                        class="danger"
                                                        href="delete_user.php?id=<?php echo (int)$user['id']; ?>"
                                                        onclick="return confirm('Delete this user?');"
                                                    >
                                                        🗑️ Delete
                                                    </a>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8">
                                    <div class="empty-state">No users found.</div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>

<script>
document.addEventListener('click', function (e) {
    document.querySelectorAll('.dropdown').forEach(function (drop) {
        const menu = drop.querySelector('.dropdown-menu');
        const button = drop.querySelector('.dropdown-toggle');

        if (drop.contains(e.target)) {
            if (e.target === button || button.contains(e.target)) {
                const isOpen = menu.style.display === 'block';

                document.querySelectorAll('.dropdown-menu').forEach(function (otherMenu) {
                    otherMenu.style.display = 'none';
                });

                menu.style.display = isOpen ? 'none' : 'block';
            }
        } else {
            menu.style.display = 'none';
        }
    });
});
</script>
</body>
</html>