<?php
require_once __DIR__ . '/../library/auth.php';
allow_roles(['admin']);

$school_id = $_SESSION['school_id'] ?? 0; // super_admin = 0

// ================= EDIT USER =================
$edit_user = null;
if (isset($_GET['edit_id'])) {

    if ($school_id == 0) {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$_GET['edit_id']]);
    } else {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? AND school_id = ?");
        $stmt->execute([$_GET['edit_id'], $school_id]);
    }

    $edit_user = $stmt->fetch(PDO::FETCH_ASSOC);
}

$page_title = 'User Management';
require_once __DIR__ . '/../include/header.php';
require_once __DIR__ . '/../include/sidebar.php';

// ================= USERS LIST =================
if ($school_id == 0) {
    $stmt = $pdo->query("SELECT * FROM users ORDER BY id DESC");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE school_id = ? ORDER BY id DESC");
    $stmt->execute([$school_id]);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<div class="content-wrapper">
    <section class="content">
        <div class="container-fluid">

            <!-- Add/Edit Form -->
            <div class="card p-3 mb-4">
                <h4 class="widgettitle"><?php echo $edit_user ? 'Edit User' : 'Add New User'; ?></h4>

                <form action="process.php?action=save" method="post">
                    <input type="hidden" name="id" value="<?php echo $edit_user['id'] ?? ''; ?>">

                    <div class="row">

                        <div class="col-md-3">
                            <input type="text" name="name" class="form-control" placeholder="Name"
                            value="<?php echo $edit_user['name'] ?? ''; ?>" required>
                        </div>

                        <div class="col-md-2">
                            <input type="text" name="username" class="form-control" placeholder="Username"
                            value="<?php echo $edit_user['username'] ?? ''; ?>" required>
                        </div>

                        <div class="col-md-2">
                            <select name="role" class="form-control">
                                <option value="admin" <?php if(($edit_user['role']??'') == 'admin') echo 'selected'; ?>>Admin</option>
                                <option value="teacher" <?php if(($edit_user['role']??'') == 'teacher') echo 'selected'; ?>>Teacher</option>
                                <option value="accountant" <?php if(($edit_user['role']??'') == 'accountant') echo 'selected'; ?>>Accountant</option>
                                <?php if($school_id == 0): ?>
                                <option value="super_admin" <?php if(($edit_user['role']??'') == 'super_admin') echo 'selected'; ?>>Super Admin</option>
                                <?php endif; ?>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <input type="password" name="password" class="form-control"
                            placeholder="<?php echo $edit_user ? 'Leave blank to keep current' : 'Password'; ?>"
                            <?php echo $edit_user ? '' : 'required'; ?>>
                        </div>

                        <?php if($school_id == 0): ?>
                        <div class="col-md-2">
                            <input type="number" name="school_id" class="form-control"
                            placeholder="School ID"
                            value="<?php echo $edit_user['school_id'] ?? ''; ?>">
                        </div>
                        <?php endif; ?>

                        <div class="col-md-2 mt-2">
                            <button type="submit" class="btn btn-primary">
                                <?php echo $edit_user ? 'Update' : 'Save'; ?>
                            </button>
                        </div>

                    </div>
                </form>
            </div>

            <!-- USERS LIST -->
            <h4 class="widgettitle">Manage Users</h4>

            <?php if(isset($_GET['msg'])): ?>
                <div class="alert alert-info"><?php echo htmlspecialchars($_GET['msg']); ?></div>
            <?php endif; ?>

            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Username</th>
                        <th>Role</th>
                        <?php if($school_id == 0): ?>
                        <th>School ID</th>
                        <?php endif; ?>
                        <th>Action</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach($users as $u): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($u['name']); ?></td>
                        <td><?php echo htmlspecialchars($u['username']); ?></td>
                        <td><?php echo htmlspecialchars($u['role']); ?></td>

                        <?php if($school_id == 0): ?>
                        <td><?php echo $u['school_id']; ?></td>
                        <?php endif; ?>

                        <td>
                            <a href="?edit_id=<?php echo $u['id']; ?>" class="btn btn-xs btn-success">Edit</a>
                            <a href="process.php?action=delete&id=<?php echo $u['id']; ?>" 
                               class="btn btn-xs btn-danger"
                               onclick="return confirm('Delete user?')">Delete</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>

            </table>

        </div>
    </section>
</div>

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