<?php
declare(strict_types=1);

$PAGE_TITLE = 'Users';
$ACTIVE = 'users';

require_once __DIR__ . '/../includes/admin_auth.php';
require_once __DIR__ . '/../includes/admin_layout_top.php';

if (!isset($mysqli) && isset($conn)) {
    $mysqli = $conn;
}

if (!function_exists('h')) {
    function h($v): string {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('tbl_exists')) {
    function tbl_exists(mysqli $db, string $table): bool {
        $safe = $db->real_escape_string($table);
        $res = $db->query("SHOW TABLES LIKE '{$safe}'");
        return $res && $res->num_rows > 0;
    }
}

if (!function_exists('col_exists')) {
    function col_exists(mysqli $db, string $table, string $col): bool {
        $safeTable = $db->real_escape_string($table);
        $safeCol   = $db->real_escape_string($col);
        $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
        return $res && $res->num_rows > 0;
    }
}

$msg = '';
$err = '';

$usersTable = tbl_exists($mysqli, 'elms_users') ? 'elms_users' : (tbl_exists($mysqli, 'admins') ? 'admins' : '');

if ($usersTable === '') {
    $err = 'Users table not found. Expected table: users or admins.';
}

if ($usersTable && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $name     = trim($_POST['name'] ?? '');
        $email    = trim($_POST['email'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $role     = trim($_POST['role'] ?? 'admin');
        $password = trim($_POST['password'] ?? '');

        $allowedRoles = ['super_admin', 'admin', 'manager'];

        if ($name === '' || $password === '') {
            $err = 'Name and password are required.';
        } elseif (!in_array($role, $allowedRoles, true)) {
            $err = 'Invalid admin role.';
        } else {
            $cols = [];
            $vals = [];
            $types = '';

            if (col_exists($mysqli, $usersTable, 'name')) {
                $cols[] = 'name';
                $vals[] = $name;
                $types .= 's';
            } elseif (col_exists($mysqli, $usersTable, 'full_name')) {
                $cols[] = 'full_name';
                $vals[] = $name;
                $types .= 's';
            }

            if (col_exists($mysqli, $usersTable, 'email')) {
                $cols[] = 'email';
                $vals[] = $email;
                $types .= 's';
            }

            if (col_exists($mysqli, $usersTable, 'username')) {
                $cols[] = 'username';
                $vals[] = $username !== '' ? $username : $email;
                $types .= 's';
            }

            if (col_exists($mysqli, $usersTable, 'role')) {
                $cols[] = 'role';
                $vals[] = $role;
                $types .= 's';
            } elseif (col_exists($mysqli, $usersTable, 'admin_role')) {
                $cols[] = 'admin_role';
                $vals[] = $role;
                $types .= 's';
            }

            $passwordHash = password_hash($password, PASSWORD_DEFAULT);

            if (col_exists($mysqli, $usersTable, 'password')) {
                $cols[] = 'password';
                $vals[] = $passwordHash;
                $types .= 's';
            } elseif (col_exists($mysqli, $usersTable, 'password_hash')) {
                $cols[] = 'password_hash';
                $vals[] = $passwordHash;
                $types .= 's';
            }

            if (col_exists($mysqli, $usersTable, 'status')) {
                $cols[] = 'status';
                $vals[] = 'active';
                $types .= 's';
            }

            if (col_exists($mysqli, $usersTable, 'created_at')) {
                $cols[] = 'created_at';
                $vals[] = date('Y-m-d H:i:s');
                $types .= 's';
            }

            if (!$cols) {
                $err = 'No supported columns found in users table.';
            } else {
                $placeholders = implode(',', array_fill(0, count($cols), '?'));
                $colSql = '`' . implode('`,`', $cols) . '`';

                $stmt = $mysqli->prepare("INSERT INTO `{$usersTable}` ({$colSql}) VALUES ({$placeholders})");
                if ($stmt) {
                    $stmt->bind_param($types, ...$vals);
                    if ($stmt->execute()) {
                        $msg = 'User created successfully.';
                    } else {
                        $err = 'Create failed: ' . $stmt->error;
                    }
                    $stmt->close();
                } else {
                    $err = 'Prepare failed: ' . $mysqli->error;
                }
            }
        }
    }

    if ($action === 'toggle_status') {
        $id = (int)($_POST['id'] ?? 0);
        $status = trim($_POST['status'] ?? 'active');

        if ($id > 0 && col_exists($mysqli, $usersTable, 'status')) {
            $newStatus = strtolower($status) === 'active' ? 'inactive' : 'active';
            $stmt = $mysqli->prepare("UPDATE `{$usersTable}` SET status=? WHERE id=? LIMIT 1");
            $stmt->bind_param('si', $newStatus, $id);
            if ($stmt->execute()) {
                $msg = 'User status updated.';
            } else {
                $err = 'Status update failed.';
            }
            $stmt->close();
        }
    }
}

$rows = [];
if ($usersTable) {
    $select = ['id'];

    if (col_exists($mysqli, $usersTable, 'name')) {
        $select[] = 'name';
    } elseif (col_exists($mysqli, $usersTable, 'full_name')) {
        $select[] = 'full_name AS name';
    } else {
        $select[] = "'' AS name";
    }

    $select[] = col_exists($mysqli, $usersTable, 'email') ? 'email' : "'' AS email";
    $select[] = col_exists($mysqli, $usersTable, 'username') ? 'username' : "'' AS username";

    if (col_exists($mysqli, $usersTable, 'role')) {
        $select[] = 'role';
    } elseif (col_exists($mysqli, $usersTable, 'admin_role')) {
        $select[] = 'admin_role AS role';
    } else {
        $select[] = "'' AS role";
    }

    $select[] = col_exists($mysqli, $usersTable, 'status') ? 'status' : "'active' AS status";
    $select[] = col_exists($mysqli, $usersTable, 'created_at') ? 'created_at' : "NULL AS created_at";

    $sql = "SELECT " . implode(',', $select) . " FROM `{$usersTable}` ORDER BY id DESC";
    $res = $mysqli->query($sql);
    if ($res) {
        $rows = $res->fetch_all(MYSQLI_ASSOC);
    }
}
?>

<div class="container-fluid">
    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
        <div>
            <h4 class="mb-1">Users</h4>
            <div class="text-muted small">Manage ELMS admin users.</div>
        </div>
        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="bi bi-plus-circle me-1"></i> Add User
        </button>
    </div>

    <?php if ($msg): ?>
        <div class="alert alert-success"><?= h($msg) ?></div>
    <?php endif; ?>

    <?php if ($err): ?>
        <div class="alert alert-danger"><?= h($err) ?></div>
    <?php endif; ?>

    <div class="card border-0 shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table align-middle table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>#</th>
                            <th>Name</th>
                            <th>Email / Username</th>
                            <th>Role</th>
                            <th>Status</th>
                            <th>Created</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$rows): ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted py-4">No users found.</td>
                            </tr>
                        <?php endif; ?>

                        <?php foreach ($rows as $r): ?>
                            <?php
                                $status = strtolower((string)($r['status'] ?? 'active'));
                                $badge = $status === 'active' ? 'bg-success' : 'bg-secondary';
                            ?>
                            <tr>
                                <td><?= (int)$r['id'] ?></td>
                                <td class="fw-semibold"><?= h($r['name'] ?? '') ?></td>
                                <td>
                                    <div><?= h($r['email'] ?? '') ?></div>
                                    <?php if (!empty($r['username'])): ?>
                                        <div class="small text-muted"><?= h($r['username']) ?></div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge bg-dark"><?= h($r['role'] ?? '') ?></span>
                                </td>
                                <td>
                                    <span class="badge <?= $badge ?>"><?= h(ucfirst($status)) ?></span>
                                </td>
                                <td class="text-muted small"><?= h($r['created_at'] ?? '-') ?></td>
                                <td class="text-end">
                                    <?php if (col_exists($mysqli, $usersTable, 'status')): ?>
                                        <form method="post" class="d-inline">
                                            <input type="hidden" name="action" value="toggle_status">
                                            <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                                            <input type="hidden" name="status" value="<?= h($status) ?>">
                                            <button class="btn btn-outline-secondary btn-sm">
                                                <?= $status === 'active' ? 'Deactivate' : 'Activate' ?>
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <span class="text-muted small">No action</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="addUserModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form method="post" class="modal-content border-0 shadow">
            <input type="hidden" name="action" value="create">

            <div class="modal-header">
                <h5 class="modal-title">Add Admin User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Name *</label>
                    <input type="text" name="name" class="form-control" required>
                </div>

                <div class="mb-3">
                    <label class="form-label">Email</label>
                    <input type="email" name="email" class="form-control">
                </div>

                <div class="mb-3">
                    <label class="form-label">Username</label>
                    <input type="text" name="username" class="form-control">
                </div>

                <div class="mb-3">
                    <label class="form-label">Role *</label>
                    <select name="role" class="form-select" required>
                        <option value="admin">Admin</option>
                        <option value="manager">Manager</option>
                        <option value="super_admin">Super Admin</option>
                    </select>
                </div>

                <div class="mb-1">
                    <label class="form-label">Password *</label>
                    <input type="password" name="password" class="form-control" required>
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn btn-primary">
                    <i class="bi bi-check-circle me-1"></i> Save User
                </button>
            </div>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/admin_layout_bottom.php'; ?>