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

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

$success = isset($_GET['success']) ? "User created successfully!" : "";
$error = "";

// Handle User Delete
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $delete_id = (int)$_GET['delete'];
    
    // Prevent deleting yourself
    if ($delete_id == $_SESSION['user_id']) {
        $error = "You cannot delete your own account.";
    } else {
        try {
            $conn->query("DELETE FROM users WHERE id = $delete_id");
            header("Location: users-list.php?success=User deleted successfully");
            exit();
        } catch (Exception $e) {
            $error = "Failed to delete user.";
        }
    }
}

// Fetch All Users
$users_result = $conn->query("
    SELECT id, user_code, full_name, email, phone, role, department, status, created_at 
    FROM users 
    ORDER BY created_at DESC
");

$users = $users_result->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.10);
            --glass-border: rgba(255,255,255,0.20);
        }
        * { margin:0; padding:0; box-sizing:border-box; }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
            min-height: 100vh;
        }
        .container { max-width: 1350px; margin: auto; }

        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 32px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 25px 80px rgba(0,0,0,0.65);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
            padding: 50px 40px;
            text-align: center;
        }
        .header h1 {
            font-size: clamp(28px, 5.5vw, 42px);
            font-weight: 700;
        }

        .top-bar {
            padding: 25px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            background: rgba(255,255,255,0.05);
        }

        .search-box {
            flex: 1;
            min-width: 280px;
        }
        .search-box input {
            width: 100%;
            padding: 14px 20px;
            background: rgba(255,255,255,0.09);
            border: 1px solid rgba(255,255,255,0.25);
            border-radius: 16px;
            color: white;
            font-size: 16px;
        }
        option{
            color: black;
        }
        .add-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            padding: 14px 28px;
            border-radius: 16px;
            text-decoration: none;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 10px 25px rgba(168,85,247,0.4);
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }
        th {
            background: rgba(168,85,247,0.3);
            padding: 18px 16px;
            text-align: left;
            font-weight: 600;
        }
        td {
            padding: 18px 16px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .status-badge {
            padding: 8px 18px;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 700;
        }
        .status-Active { background: #22c55e; color: white; }
        .status-Inactive { background: #64748b; color: white; }
        .status-Suspended { background: #ef4444; color: white; }

        .role-badge {
            padding: 6px 14px;
            border-radius: 30px;
            font-size: 0.85rem;
            font-weight: 600;
            background: rgba(168,85,247,0.2);
            color: #c4b5fd;
        }

        .action-btns a {
            margin: 0 6px;
            padding: 8px 14px;
            border-radius: 10px;
            text-decoration: none;
            font-size: 0.95rem;
        }
        .btn-view  { background: rgba(59,130,246,0.2); color: #60a5fa; }
        .btn-edit  { background: rgba(234,179,8,0.2); color: #fde047; }
        .btn-delete{ background: rgba(239,68,68,0.2); color: #f87171; }

        .message {
            padding: 16px 24px;
            border-radius: 16px;
            margin: 20px 40px;
            font-weight: 600;
        }
        .success { background: rgba(34,197,94,0.25); border:1px solid #4ade80; color:#86efac; }

        @media (max-width: 768px) {
            .top-bar { flex-direction: column; align-items: stretch; }
            th, td { padding: 14px 10px; font-size: 0.95rem; }
        }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">

        <div class="header">
            <h1><i class="fas fa-users"></i> User Management</h1>
            <p style="margin-top:12px; opacity:0.9;">Manage all system users</p>
        </div>

        <div class="top-bar">
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="Search by name, email, role..." onkeyup="filterTable()">
            </div>
            <a href="add-user.php" class="add-btn">
                <i class="fas fa-user-plus"></i> Add New User
            </a>
        </div>

        <?php if ($success): ?>
            <div class="message success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="message" style="background:rgba(239,68,68,0.25); color:#fca5a5;"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <div style="padding:0 40px 40px;">
            <?php if (empty($users)): ?>
                <div style="text-align:center; padding:80px 20px; color:#94a3b8;">
                    <i class="fas fa-users" style="font-size:4rem; opacity:0.3; margin-bottom:20px;"></i>
                    <h3>No users found</h3>
                </div>
            <?php else: ?>
                <table id="userTable">
                    <thead>
                        <tr>
                            <th>User Code</th>
                            <th>Full Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Role</th>
                            <th>Department</th>
                            <th>Status</th>
                            <th style="text-align:center;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $user): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($user['user_code']) ?></strong></td>
                            <td><?= htmlspecialchars($user['full_name']) ?></td>
                            <td><?= htmlspecialchars($user['email']) ?></td>
                            <td><?= htmlspecialchars($user['phone'] ?? '—') ?></td>
                            <td>
                                <span class="role-badge"><?= htmlspecialchars(ucwords($user['role'])) ?></span>
                            </td>
                            <td><?= htmlspecialchars($user['department'] ?? '—') ?></td>
                            <td>
                                <span class="status-badge status-<?= htmlspecialchars($user['status']) ?>">
                                    <?= htmlspecialchars($user['status']) ?>
                                </span>
                            </td>
                            <td class="action-btns" style="text-align:center; white-space:nowrap;">
                                <a href="user-view.php?id=<?= $user['id'] ?>" class="btn-view" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="user-edit.php?id=<?= $user['id'] ?>" class="btn-edit" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                <a href="users-list.php?delete=<?= $user['id'] ?>" 
                                   class="btn-delete" 
                                   title="Delete"
                                   onclick="return confirm('Are you sure you want to delete this user? This action cannot be undone.')">
                                    <i class="fas fa-trash"></i>
                                </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function filterTable() {
    const input = document.getElementById("searchInput").value.toLowerCase();
    const rows = document.querySelectorAll("#userTable tbody tr");

    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(input) ? "" : "none";
    });
}
</script>

</body>
</html>

<?php $conn->close(); ?>