<?php
// manage_users.php — Admin only.
require_once 'includes/auth.php';
require_role(['admin']);

require_once 'db.php';

$me = current_user();
$message = '';
$error = '';

// Create a new user (Inspector or Coordinator — Admin accounts are only
// ever created via setup.php, never here, to avoid casually minting more
// full-access accounts from a dropdown).
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_user'])) {
    require_csrf();
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $role = $_POST['role'] ?? 'inspector';

    if (!in_array($role, ['inspector', 'coordinator'], true)) {
        $role = 'inspector';
    }

    if ($name === '' || $email === '' || strlen($password) < 8) {
        $error = 'Name, email, and a password of at least 8 characters are required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';
    } else {
        try {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare(
                "INSERT INTO tbl_users (Name, Email, Password_Hash, Role, Is_Active) VALUES (?, ?, ?, ?, 1)"
            );
            $stmt->execute([$name, $email, $hash, $role]);
            $message = 'Account created for ' . htmlspecialchars($name) . '.';
        } catch (\PDOException $e) {
            error_log('manage_users.php create error: ' . $e->getMessage());
            $error = 'Could not create account — the email may already be in use.';
        }
    }
}

// Toggle active status. Soft-disable only — never a real delete, so the
// audit trail (who created/edited which certificate) stays intact even
// for accounts that no longer work here.
if (isset($_GET['toggle_id'])) {
    require_csrf();
    $toggleId = (int) $_GET['toggle_id'];

    if ($toggleId === (int) $me['id']) {
        $error = "You can't disable your own account.";
    } else {
        $stmt = $pdo->prepare("SELECT Role, Is_Active FROM tbl_users WHERE UserID = ?");
        $stmt->execute([$toggleId]);
        $target = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($target) {
            $newStatus = $target['Is_Active'] ? 0 : 1;
            $upd = $pdo->prepare("UPDATE tbl_users SET Is_Active = ? WHERE UserID = ?");
            $upd->execute([$newStatus, $toggleId]);
            header('Location: manage_users.php');
            exit;
        }
    }
}

$users = $pdo->query("SELECT * FROM tbl_users WHERE Deleted_At IS NULL ORDER BY Role, Name ASC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Users — Liftek</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container my-4" style="max-width: 900px;">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold m-0"><i class="fa-solid fa-users-gear text-primary me-2"></i> Manage Users</h3>
        <a href="index.php" class="btn btn-outline-secondary btn-sm"><i class="fa-solid fa-arrow-left me-1"></i> Back to Register</a>
    </div>

    <?php if ($message): ?><div class="alert alert-success py-2"><?= $message; ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger py-2"><?= htmlspecialchars($error); ?></div><?php endif; ?>

    <div class="card mb-4 border-primary">
        <div class="card-header bg-primary text-white fw-bold"><i class="fa-solid fa-user-plus me-1"></i> Add New Account</div>
        <div class="card-body">
            <form method="POST" class="row g-2">
                <input type="hidden" name="create_user" value="1">
                <?php csrf_field(); ?>
                <div class="col-md-3">
                    <input type="text" name="name" class="form-control" placeholder="Full Name" required>
                </div>
                <div class="col-md-3">
                    <input type="email" name="email" class="form-control" placeholder="Email" required>
                </div>
                <div class="col-md-2">
                    <input type="password" name="password" class="form-control" placeholder="Password (min 8)" minlength="8" required>
                </div>
                <div class="col-md-2">
                    <select name="role" class="form-select">
                        <option value="inspector">Inspector</option>
                        <option value="coordinator">Coordinator</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100 fw-bold">Create</button>
                </div>
            </form>
            <div class="form-text mt-2">Admin accounts can only be created via the one-time <code>setup.php</code> — not from here.</div>
        </div>
    </div>

    <div class="card">
        <div class="card-header bg-dark text-white fw-bold">Existing Accounts</div>
        <div class="table-responsive">
            <table class="table table-hover align-middle m-0">
                <thead class="table-light">
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Status</th>
                        <th class="text-center">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $u): ?>
                        <tr>
                            <td class="fw-semibold"><?= htmlspecialchars($u['Name']); ?></td>
                            <td><?= htmlspecialchars($u['Email']); ?></td>
                            <td><span class="badge bg-secondary text-capitalize"><?= htmlspecialchars($u['Role']); ?></span></td>
                            <td>
                                <?php if ($u['Is_Active']): ?>
                                    <span class="badge bg-success">Active</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Disabled</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <?php if ((int) $u['UserID'] === (int) $me['id']): ?>
                                    <span class="text-muted small">(You)</span>
                                <?php else: ?>
                                    <a href="manage_users.php?toggle_id=<?= (int) $u['UserID']; ?>&amp;csrf_token=<?= urlencode(csrf_token()); ?>"
                                       class="btn btn-sm <?= $u['Is_Active'] ? 'btn-outline-danger' : 'btn-outline-success'; ?>"
                                       onclick="return confirm('<?= $u['Is_Active'] ? 'Disable' : 'Re-enable'; ?> this account?');">
                                        <?= $u['Is_Active'] ? 'Disable' : 'Enable'; ?>
                                    </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>
</body>
</html>
