<?php
// admin/users.php
include __DIR__ . '/../includes/header.php'; // $lang_admin, $lang_alerts, $lang_frontend should be available via header

// Load the main notification settings definition from the language file
$notification_settings_definition = $lang_admin['ADMIN_USERS_NOTIFICATION_SETTINGS_DEFINITION'];

if (!isLoggedIn() || !isAdmin()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ADMIN_NO_PERMISSION'], 'danger');
    redirectTo(getCleanUrl('index'));
}

// Handle user actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INVALID_CSRF_TRY_AGAIN'], 'danger');
        redirectTo(getCleanUrl('admin/users'));
        exit;
    }
    try {
        // Add new user
        if (isset($_POST['add_user'])) {
            $name = sanitizeInput($_POST['name']);
            $email = sanitizeInput($_POST['email']);
            $password = $_POST['password'];
            $company = !empty($_POST['company']) ? sanitizeInput($_POST['company']) : null;
            $role = sanitizeInput($_POST['role']);

            $country_code = null;
            $city = null;
            if (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS) {
                $country_code = !empty($_POST['country_code']) ? sanitizeInput($_POST['country_code']) : null;
                $city = !empty($_POST['city']) ? sanitizeInput($_POST['city']) : null;
            }

            if (empty($name) || empty($email) || empty($password) || empty($role)) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_ALL_FIELDS_EXCEPT_COMPANY_REQUIRED'], 'danger');
            } elseif (!in_array($role, ['admin', 'staff', 'member'])) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_INVALID_ROLE'], 'danger');
            } else {
                $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
                $checkStmt->execute([$email]);
                if ($checkStmt->fetchColumn() > 0) {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_EMAIL_EXISTS'], 'danger');
                } else {
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $is_email_verified_for_new_user = true;
                    if (!in_array($role, ['admin', 'staff']) && defined('FORCE_EMAIL_VALIDATION') && FORCE_EMAIL_VALIDATION) {
                        $is_email_verified_for_new_user = false;
                    }

                    $avatar_filename = null;
                    if (!empty($_FILES['avatar']['name'])) {
                        try {
                            $currentDir = getcwd();
                            chdir(dirname(__DIR__));
                            $avatar_filename = uploadFile($_FILES['avatar'], 'uploads/avatars/');
                            chdir($currentDir);
                            if (!$avatar_filename) {
                                throw new Exception(sprintf($lang_alerts['ALERT_USERS_AVATAR_UPLOAD_FAILED'], '')); // Empty string for specific error from uploadFile
                            }
                        } catch (Exception $e) {
                            if (isset($currentDir)) { chdir($currentDir); }
                            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_USERS_ERROR_UPLOADING_AVATAR'], $e->getMessage()), 'danger');
                            redirectTo(getCleanUrl('admin/users'));
                            exit;
                        }
                    }

                    $stmt = $pdo->prepare("INSERT INTO users (name, email, password, company, role, is_email_verified, avatar, country_code, city) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    if ($stmt->execute([$name, $email, $hashed_password, $company, $role, $is_email_verified_for_new_user, $avatar_filename, $country_code, $city])) {
                        $new_user_id = $pdo->lastInsertId();
                        if (isset($_POST['new_notifications'])) {
                            $submitted_prefs = $_POST['new_notifications'];
                            $notification_values_to_save = [];
                            foreach ($notification_settings_definition as $key => $details) {
                                $notification_values_to_save[$key] = isset($submitted_prefs[$key]) ? 1 : 0;
                            }
                            $columns = array_keys($notification_settings_definition);
                            $placeholders = array_map(function($col) { return ":{$col}"; }, $columns);
                            $sql_insert_prefs = "INSERT INTO user_notification_settings (user_id, " . implode(', ', $columns) . ") VALUES (:user_id, " . implode(', ', $placeholders) . ")";
                            $stmt_save_prefs = $pdo->prepare($sql_insert_prefs);
                            $notification_values_to_save['user_id'] = $new_user_id;
                            if (!$stmt_save_prefs->execute($notification_values_to_save)) {
                                error_log("Failed to save notification settings for new user ID: " . $new_user_id);
                            }
                        }
                        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_ADDED_SUCCESS'], 'success');
                    } else {
                        if ($avatar_filename && file_exists('../uploads/avatars/' . $avatar_filename)) {
                            unlink('../uploads/avatars/' . $avatar_filename);
                        }
                        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_ADD_ERROR'], 'danger');
                    }
                }
            }
        }

        if (isset($_POST['edit_user'])) {
            $user_id = (int)$_POST['user_id'];
            $name = sanitizeInput($_POST['name']);
            $email = sanitizeInput($_POST['email']);
            $company = !empty($_POST['company']) ? sanitizeInput($_POST['company']) : null;
            $role = sanitizeInput($_POST['role']);
            $remove_avatar = isset($_POST['remove_avatar']) && $_POST['remove_avatar'] === '1';

            $country_code = null;
            $city = null;
            if (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS) {
                $country_code = !empty($_POST['country_code']) ? sanitizeInput($_POST['country_code']) : null;
                $city = !empty($_POST['city']) ? sanitizeInput($_POST['city']) : null;
            }

            if (empty($name) || empty($email) || empty($role)) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_NAME_EMAIL_ROLE_REQUIRED'], 'danger');
            } elseif (!in_array($role, ['admin', 'staff', 'member'])) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_INVALID_ROLE'], 'danger');
            } else {
                $stmt_current_user = $pdo->prepare("SELECT role, is_email_verified, avatar, country_code, city FROM users WHERE id = ?");
                $stmt_current_user->execute([$user_id]);
                $current_user_data = $stmt_current_user->fetch();

                if (!$current_user_data) {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_USER_NOT_FOUND'], 'danger');
                    redirectTo(getCleanUrl('admin/users'));
                    exit;
                }

                $current_avatar = $current_user_data['avatar'];
                $new_avatar = $current_avatar;

                if (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS) {
                    $final_country_code = $country_code;
                    $final_city = $city;
                } else {
                    $final_country_code = $current_user_data['country_code'];
                    $final_city = $current_user_data['city'];
                }

                if ($remove_avatar && !empty($current_avatar)) {
                    $avatar_path = '../uploads/avatars/' . $current_avatar;
                    if (file_exists($avatar_path)) { unlink($avatar_path); }
                    $new_avatar = null;
                }

                if (!empty($_FILES['avatar']['name'])) {
                    try {
                        $currentDir = getcwd();
                        chdir(dirname(__DIR__));
                        $uploaded_avatar = uploadFile($_FILES['avatar'], 'uploads/avatars/');
                        chdir($currentDir);
                        if (!$uploaded_avatar) {
                            throw new Exception(sprintf($lang_alerts['ALERT_USERS_AVATAR_UPLOAD_FAILED'], ''));
                        }
                        if (!empty($current_avatar) && file_exists('../uploads/avatars/' . $current_avatar)) {
                            unlink('../uploads/avatars/' . $current_avatar);
                        }
                        $new_avatar = $uploaded_avatar;
                    } catch (Exception $e) {
                        if (isset($currentDir)) { chdir($currentDir); }
                        $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_USERS_ERROR_UPLOADING_AVATAR'], $e->getMessage()), 'danger');
                        redirectTo(getCleanUrl('admin/users'));
                        exit;
                    }
                }

                $update_fields = "name = ?, email = ?, company = ?, role = ?, avatar = ?, country_code = ?, city = ?";
                $params = [$name, $email, $company, $role, $new_avatar, $final_country_code, $final_city];
                $should_verify_email_due_to_admin_role = false;
                if ($current_user_data && !in_array($current_user_data['role'], ['admin', 'staff']) && in_array($role, ['admin', 'staff'])) {
                    $should_verify_email_due_to_admin_role = true;
                } else if ($current_user_data && in_array($current_user_data['role'], ['admin', 'staff']) && in_array($role, ['admin', 'staff'])){
                    $should_verify_email_due_to_admin_role = true;
                }
                if ($should_verify_email_due_to_admin_role) {
                    $update_fields .= ", is_email_verified = TRUE, email_validation_token = NULL, email_validation_token_expires_at = NULL";
                }
                $stmt = $pdo->prepare("UPDATE users SET " . $update_fields . " WHERE id = ?");
                $params[] = $user_id;

                if ($stmt->execute($params)) {
                    // If the user being edited is the current user and role changed, regenerate session
                    if ($user_id == $_SESSION['user_id'] && $role !== $current_user_data['role']) {
                        // Update role first, then regenerate session to prevent session fixation
                        $_SESSION['role'] = $role;
                        session_regenerate_id(true);
                        if (method_exists('SessionManager', 'updateSessionState')) {
                            SessionManager::updateSessionState();
                        }
                    }

                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_UPDATED_SUCCESS'], 'success');
                    if (isset($_POST['notifications'][$user_id])) {
                        $submitted_prefs = $_POST['notifications'][$user_id];
                        $notification_values_to_save = [];
                        foreach ($notification_settings_definition as $key => $details) {
                            $notification_values_to_save[$key] = isset($submitted_prefs[$key]) ? 1 : 0;
                        }
                        $stmt_check = $pdo->prepare("SELECT id FROM user_notification_settings WHERE user_id = ?");
                        $stmt_check->execute([$user_id]);
                        $existing_settings_id = $stmt_check->fetchColumn();
                        if ($existing_settings_id) {
                            $sql_parts = [];
                            foreach ($notification_settings_definition as $key => $details) { $sql_parts[] = "{$key} = :{$key}"; }
                            $sql_update_prefs = "UPDATE user_notification_settings SET " . implode(', ', $sql_parts) . ", updated_at = CURRENT_TIMESTAMP WHERE user_id = :user_id";
                            $stmt_save_prefs = $pdo->prepare($sql_update_prefs);
                        } else {
                            $columns = array_keys($notification_settings_definition);
                            $placeholders = array_map(function($col) { return ":{$col}"; }, $columns);
                            $sql_insert_prefs = "INSERT INTO user_notification_settings (user_id, " . implode(', ', $columns) . ") VALUES (:user_id, " . implode(', ', $placeholders) . ")";
                            $stmt_save_prefs = $pdo->prepare($sql_insert_prefs);
                        }
                        $notification_values_to_save['user_id'] = $user_id;
                        if (!$stmt_save_prefs->execute($notification_values_to_save)) {
                            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_UPDATED_NOTIFICATIONS_FAILED'], 'warning');
                        }
                    }
                } else {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_UPDATE_ERROR'], 'danger');
                }
            }
        }

        if (isset($_POST['delete_user'])) {
            $user_id = (int)$_POST['user_id'];
            if ($user_id === (int)$_SESSION['user_id']) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_CANNOT_DELETE_SELF'], 'danger');
            } else {
                $stmt_avatar = $pdo->prepare("SELECT avatar FROM users WHERE id = ?");
                $stmt_avatar->execute([$user_id]);
                $user_avatar = $stmt_avatar->fetchColumn();
                $pdo->beginTransaction();
                try {
                    $stmt_del_notif = $pdo->prepare("DELETE FROM user_notification_settings WHERE user_id = ?");
                    $stmt_del_notif->execute([$user_id]);
                    $stmt_ticket_ids = $pdo->prepare("SELECT id FROM tickets WHERE user_id = ?");
                    $stmt_ticket_ids->execute([$user_id]);
                    $ticket_ids = $stmt_ticket_ids->fetchAll(PDO::FETCH_COLUMN);
                    if (!empty($ticket_ids)) {
                        $placeholders = implode(',', array_fill(0, count($ticket_ids), '?'));
                        $stmt_del_comments = $pdo->prepare("DELETE FROM ticket_replies WHERE ticket_id IN ($placeholders)");
                        $stmt_del_comments->execute($ticket_ids);
                    }
                    $stmt_del_tickets = $pdo->prepare("DELETE FROM tickets WHERE user_id = ?");
                    $stmt_del_tickets->execute([$user_id]);
                    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
                    if ($stmt->execute([$user_id])) {
                        if (!empty($user_avatar) && file_exists('../uploads/avatars/' . $user_avatar)) {
                            unlink('../uploads/avatars/' . $user_avatar);
                        }
                        $pdo->commit();
                        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_DELETED_SUCCESS'], 'success');
                    } else {
                        $pdo->rollback();
                        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_DELETE_ERROR'], 'danger');
                    }
                } catch (Exception $e) {
                    $pdo->rollback();
                    $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_USERS_DELETE_ERROR_MSG'], $e->getMessage()), 'danger');
                }
            }
        }

        if (isset($_POST['manually_verify_email'])) {
            if (defined('FORCE_EMAIL_VALIDATION') && FORCE_EMAIL_VALIDATION) {
                $user_id = (int)$_POST['user_id'];
                $stmt = $pdo->prepare("UPDATE users SET is_email_verified = TRUE, email_validation_token = NULL, email_validation_token_expires_at = NULL WHERE id = ?");
                if ($stmt->execute([$user_id])) {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_EMAIL_VERIFIED_SUCCESS'], 'success');
                } else {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_EMAIL_VERIFY_FAILED'], 'danger');
                }
            } else {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_EMAIL_VALIDATION_NOT_FORCED'], 'info');
            }
        }

        if (isset($_POST['reset_password'])) {
            $user_id = (int)$_POST['user_id'];
            $password = bin2hex(random_bytes(8));
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
            if ($stmt->execute([$hashed_password, $user_id])) {
                $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_USERS_PASSWORD_RESET_SUCCESS'], $password), 'success');
            } else {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_USERS_PASSWORD_RESET_ERROR'], 'danger');
            }
        }
    } catch (PDOException $e) {
        $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_USERS_DB_ERROR'], $e->getMessage()), 'danger');
    }
    redirectTo(getCleanUrl('admin/users'));
}

$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 25;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$role_filter = isset($_GET['role']) ? $_GET['role'] : '';
if (!in_array($per_page, [10, 25, 50, 100])) { $per_page = 25; }
$offset = ($page - 1) * $per_page;
$where_conditions = [];
$params = [];
if (!empty($search)) {
    $where_conditions[] = "(name LIKE ? OR email LIKE ? OR company LIKE ?)";
    $search_param = '%' . $search . '%';
    $params[] = $search_param; $params[] = $search_param; $params[] = $search_param;
}
if (!empty($role_filter) && in_array($role_filter, ['admin', 'staff', 'member'])) {
    $where_conditions[] = "role = ?";
    $params[] = $role_filter;
}
$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
$count_sql = "SELECT COUNT(*) FROM users " . $where_clause;
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($params);
$total_users = $count_stmt->fetchColumn();
$total_pages = ceil($total_users / $per_page);
$sql = "SELECT * FROM users " . $where_clause . " ORDER BY name ASC LIMIT ? OFFSET ?";
$params[] = $per_page; $params[] = $offset;
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h4><?php echo $lang_admin['ADMIN_USERS_PAGE_TITLE']; ?></h4>
    <div>
        <button type="button" class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="bi bi-plus-lg"></i> <?php echo $lang_admin['ADMIN_USERS_BTN_ADD_NEW']; ?>
        </button>
        <a href="<?php echo getCleanUrl('admin/dashboard'); ?>" class="btn btn-outline-primary">
            <i class="bi bi-arrow-left"></i> <?php echo $lang_admin['ADMIN_SETTINGS_BTN_BACK_TO_DASHBOARD']; ?>
        </a>
    </div>
</div>

<div class="card mb-3">
    <div class="card-body">
        <form method="GET" action="<?php echo getCleanUrl('admin/users'); ?>" class="row g-3">
            <div class="col-md-4">
                <label for="search" class="form-label"><?php echo $lang_admin['ADMIN_USERS_FILTER_SEARCH_LABEL']; ?></label>
                <input type="text" class="form-control" id="search" name="search" 
                       value="<?php echo htmlspecialchars($search); ?>" 
                       placeholder="<?php echo $lang_admin['ADMIN_USERS_FILTER_SEARCH_PLACEHOLDER']; ?>">
            </div>
            <div class="col-md-3">
                <label for="role" class="form-label"><?php echo $lang_admin['ADMIN_USERS_FILTER_ROLE_LABEL']; ?></label>
                <select class="form-select" id="role" name="role">
                    <option value=""><?php echo $lang_admin['ADMIN_USERS_FILTER_ROLE_ALL']; ?></option>
                    <option value="admin" <?php echo $role_filter === 'admin' ? 'selected' : ''; ?>><?php echo $lang_admin['ADMIN_USERS_ROLE_ADMIN']; ?></option>
                    <option value="staff" <?php echo $role_filter === 'staff' ? 'selected' : ''; ?>><?php echo $lang_admin['ADMIN_USERS_ROLE_STAFF']; ?></option>
                    <option value="member" <?php echo $role_filter === 'member' ? 'selected' : ''; ?>><?php echo $lang_admin['ADMIN_USERS_ROLE_MEMBER']; ?></option>
                </select>
            </div>
            <div class="col-md-2">
                <label for="per_page" class="form-label"><?php echo $lang_admin['ADMIN_USERS_FILTER_SHOW_LABEL']; ?></label>
                <select class="form-select" id="per_page" name="per_page">
                    <option value="10" <?php echo $per_page === 10 ? 'selected' : ''; ?>>10</option>
                    <option value="25" <?php echo $per_page === 25 ? 'selected' : ''; ?>>25</option>
                    <option value="50" <?php echo $per_page === 50 ? 'selected' : ''; ?>>50</option>
                    <option value="100" <?php echo $per_page === 100 ? 'selected' : ''; ?>>100</option>
                </select>
            </div>
            <div class="col-md-3 d-flex align-items-end">
                <button type="submit" class="btn btn-primary me-2">
                    <i class="bi bi-search"></i> <?php echo $lang_admin['ADMIN_USERS_BTN_FILTER']; ?>
                </button>
                <a href="<?php echo getCleanUrl('admin/users'); ?>" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-clockwise"></i> <?php echo $lang_admin['ADMIN_USERS_BTN_RESET_FILTERS']; ?>
                </a>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <?php echo $lang_admin['ADMIN_USERS_TABLE_HEADER_USERS']; ?>
            <?php if (!empty($search) || !empty($role_filter)): ?>
                <small class="text-light"><?php echo $lang_admin['ADMIN_USERS_TABLE_HEADER_FILTERED_SUFFIX']; ?></small>
            <?php endif; ?>
        </h5>
        <span class="badge bg-secondary text-dark">
            <?php echo sprintf($lang_admin['ADMIN_USERS_SHOWING_COUNT_OF_TOTAL'], number_format(min($per_page, $total_users - $offset)), number_format($total_users)); ?>
        </span>
    </div>
    <div class="card-body">
        <?php if (count($users) > 0): ?>
            <div class="table-responsive table-responsive-mobile">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th><?php echo $lang_admin['ADMIN_USERS_TH_NAME']; ?></th>
                            <th><?php echo $lang_admin['ADMIN_USERS_TH_EMAIL']; ?></th>
                            <th><?php echo $lang_admin['ADMIN_USERS_TH_COMPANY']; ?></th>
                            <th><?php echo $lang_admin['ADMIN_USERS_TH_ROLE']; ?></th>
                            <?php if (defined('FORCE_EMAIL_VALIDATION') && FORCE_EMAIL_VALIDATION): ?>
                                <th><?php echo $lang_admin['ADMIN_USERS_TH_EMAIL_VERIFIED']; ?></th>
                            <?php endif; ?>
                            <th><?php echo $lang_admin['ADMIN_USERS_TH_JOINED']; ?></th>
                            <th><?php echo $lang_admin['ADMIN_USERS_TH_ACTIONS']; ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $user): ?>
                            <?php
                            $stmt_prefs = $pdo->prepare("SELECT * FROM user_notification_settings WHERE user_id = ?");
                            $stmt_prefs->execute([$user['id']]);
                            $user_notification_prefs_db = $stmt_prefs->fetch(PDO::FETCH_ASSOC);
                            $current_user_prefs = [];
                            if ($user_notification_prefs_db) {
                                foreach ($notification_settings_definition as $key => $details) {
                                    $current_user_prefs[$key] = (bool)$user_notification_prefs_db[$key];
                                }
                            } else {
                                foreach ($notification_settings_definition as $key => $details) {
                                    $current_user_prefs[$key] = true;
                                }
                            }
                            ?>
                            <tr>
                                <td>
                                    <?php if (!empty($user['avatar'])): ?>
                                        <img src="../uploads/avatars/<?php echo htmlspecialchars($user['avatar']); ?>" alt="<?php echo $lang_admin['ADMIN_USERS_AVATAR_ALT']; ?>" class="avatar-sm me-2">
                                    <?php endif; ?>
                                    <?php echo htmlspecialchars($user['name']); ?>
                                </td>
                                <td><?php echo htmlspecialchars($user['email']); ?></td>
                                <td><?php echo htmlspecialchars($user['company'] ?? '-'); ?></td>
                                <td>
                                    <span class="badge bg-<?php echo $user['role'] === 'admin' ? 'danger' : ($user['role'] === 'staff' ? 'secondary' : 'primary'); ?>">
                                        <?php echo htmlspecialchars(ucfirst($lang_admin['ADMIN_USERS_ROLE_' . strtoupper($user['role'])] ?? $user['role'])); ?>
                                    </span>
                                </td>
                                <?php if (defined('FORCE_EMAIL_VALIDATION') && FORCE_EMAIL_VALIDATION): ?>
                                    <td>
                                        <?php if ($user['role'] === 'admin'): ?>
                                            <span class="badge bg-info text-dark"><?php echo $lang_admin['ADMIN_USERS_EMAIL_VERIFIED_NA_ADMIN']; ?></span>
                                        <?php elseif ($user['is_email_verified']): ?>
                                            <span class="badge bg-success"><?php echo $lang_admin['ADMIN_USERS_EMAIL_VERIFIED_YES']; ?></span>
                                        <?php else: ?>
                                            <span class="badge bg-warning text-dark"><?php echo $lang_admin['ADMIN_USERS_EMAIL_VERIFIED_NO']; ?></span>
                                            <form action="<?php echo getCleanUrl('admin/users'); ?>" method="post" class="d-inline ms-1 align-middle">
                                                <?php echo get_csrf_input_field(); ?>
                                                <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                <button type="submit" name="manually_verify_email" class="btn btn-xs btn-outline-success p-0 px-1" style="font-size: 0.75rem; line-height: 1;" title="<?php echo $lang_admin['ADMIN_USERS_BTN_MANUALLY_VERIFY_EMAIL_TITLE']; ?>">
                                                    <i class="bi bi-check-circle"></i> <?php echo $lang_admin['ADMIN_USERS_BTN_VERIFY_EMAIL']; ?>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    </td>
                                <?php endif; ?>
                                <td><?php echo getFormattedDate($user['created_at'], 'M d, Y'); ?></td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <button type="button" class="btn btn-success view-user-btn" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#viewUserModal-<?php echo $user['id']; ?>"
                                                title="View User">
                                            <i class="bi bi-eye"></i>
                                        </button>
                                        <button type="button" class="btn btn-primary edit-user-btn" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#editUserModal-<?php echo $user['id']; ?>"
                                                data-user-id="<?php echo $user['id']; ?>"
                                                data-user-name="<?php echo htmlspecialchars($user['name']); ?>"
                                                data-user-email="<?php echo htmlspecialchars($user['email']); ?>"
                                                data-user-company="<?php echo htmlspecialchars($user['company'] ?? ''); ?>"
                                                data-user-role="<?php echo $user['role']; ?>"
                                                data-user-avatar="<?php echo htmlspecialchars($user['avatar'] ?? ''); ?>"
                                                <?php if (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS): ?>
                                                data-user-country="<?php echo htmlspecialchars($user['country_code'] ?? ''); ?>"
                                                data-user-city="<?php echo htmlspecialchars($user['city'] ?? ''); ?>"
                                                <?php endif; ?>>
                                            <i class="bi bi-pencil-square"></i>
                                        </button>

                                        <button type="button" class="btn btn-warning reset-password-btn" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#resetPasswordModal-<?php echo $user['id']; ?>"
                                                data-user-id="<?php echo $user['id']; ?>"
                                                data-user-name="<?php echo htmlspecialchars($user['name']); ?>">
                                            <i class="bi bi-key"></i>
                                        </button>

                                        <?php if ($user['id'] !== $_SESSION['user_id']): ?>
                                        <button type="button" class="btn btn-danger delete-user-btn" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#deleteUserModal-<?php echo $user['id']; ?>"
                                                data-user-id="<?php echo $user['id']; ?>"
                                                data-user-name="<?php echo htmlspecialchars($user['name']); ?>">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="alert alert-info">
                <i class="bi bi-info-circle"></i> <?php echo $lang_admin['ADMIN_USERS_NO_USERS_FOUND']; ?>
                <?php if (!empty($search) || !empty($role_filter)): ?>
                    <br><small><?php echo sprintf($lang_admin['ADMIN_USERS_ADJUST_SEARCH_OR_RESET'], '<a href="' . getCleanUrl('admin/users') . '">' . $lang_admin['ADMIN_USERS_LINK_RESET_FILTERS'] . '</a>'); ?></small>
                <?php endif; ?>
            </div>
        <?php endif; ?>
        
        <?php if ($total_pages > 1): ?>
            <div class="d-flex justify-content-between align-items-center mt-4">
                <div class="text-muted">
                    <?php echo sprintf($lang_admin['ADMIN_USERS_PAGINATION_SHOWING_RANGE_OF_TOTAL'], number_format($offset + 1), number_format(min($offset + $per_page, $total_users)), number_format($total_users)); ?>
                </div>
                <nav aria-label="Users pagination">
                    <ul class="pagination pagination-sm mb-0">
                        <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="<?php echo getCleanUrl('admin/users', array_merge($_GET, ['page' => $page - 1])); ?>">
                                    <i class="bi bi-chevron-left"></i> <?php echo $lang_admin['ADMIN_USERS_PAGINATION_PREVIOUS']; ?>
                                </a>
                            </li>
                        <?php else: ?>
                            <li class="page-item disabled">
                                <span class="page-link"><i class="bi bi-chevron-left"></i> <?php echo $lang_admin['ADMIN_USERS_PAGINATION_PREVIOUS']; ?></span>
                            </li>
                        <?php endif; ?>
                        <?php
                        $start_page = max(1, $page - 2); $end_page = min($total_pages, $page + 2);
                        if ($start_page > 1): ?>
                            <li class="page-item"><a class="page-link" href="<?php echo getCleanUrl('admin/users', array_merge($_GET, ['page' => 1])); ?>">1</a></li>
                            <?php if ($start_page > 2): ?><li class="page-item disabled"><span class="page-link">...</span></li><?php endif; ?>
                        <?php endif; ?>
                        <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                            <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>"><a class="page-link" href="<?php echo getCleanUrl('admin/users', array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a></li>
                        <?php endfor; ?>
                        <?php if ($end_page < $total_pages): ?>
                            <?php if ($end_page < $total_pages - 1): ?><li class="page-item disabled"><span class="page-link">...</span></li><?php endif; ?>
                            <li class="page-item"><a class="page-link" href="<?php echo getCleanUrl('admin/users', array_merge($_GET, ['page' => $total_pages])); ?>"><?php echo $total_pages; ?></a></li>
                        <?php endif; ?>
                        <?php if ($page < $total_pages): ?>
                            <li class="page-item">
                                <a class="page-link" href="<?php echo getCleanUrl('admin/users', array_merge($_GET, ['page' => $page + 1])); ?>">
                                    <?php echo $lang_admin['ADMIN_USERS_PAGINATION_NEXT']; ?> <i class="bi bi-chevron-right"></i>
                                </a>
                            </li>
                        <?php else: ?>
                            <li class="page-item disabled">
                                <span class="page-link"><?php echo $lang_admin['ADMIN_USERS_PAGINATION_NEXT']; ?> <i class="bi bi-chevron-right"></i></span>
                            </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php foreach ($users as $user): // Loop again for modals to avoid HTML nesting issues ?>
    <?php
    // Re-fetch prefs or use previously fetched ones if structured well
    $stmt_prefs_modal = $pdo->prepare("SELECT * FROM user_notification_settings WHERE user_id = ?");
    $stmt_prefs_modal->execute([$user['id']]);
    $user_notification_prefs_db_modal = $stmt_prefs_modal->fetch(PDO::FETCH_ASSOC);
    $current_user_prefs_modal = [];
    if ($user_notification_prefs_db_modal) {
        foreach ($notification_settings_definition as $key => $details) {
            $current_user_prefs_modal[$key] = (bool)$user_notification_prefs_db_modal[$key];
        }
    } else {
        foreach ($notification_settings_definition as $key => $details) {
            $current_user_prefs_modal[$key] = true; // Default to true
        }
    }
    ?>
    <div class="modal fade" id="editUserModal-<?php echo $user['id']; // Unique ID for each modal ?>" tabindex="-1" aria-labelledby="editUserModalLabel-<?php echo $user['id']; ?>" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form action="<?php echo getCleanUrl('admin/users'); ?>" method="post" enctype="multipart/form-data">
                    <?php echo get_csrf_input_field(); ?>
                    <div class="modal-header">
                        <h5 class="modal-title" id="editUserModalLabel-<?php echo $user['id']; ?>"><?php echo sprintf($lang_admin['ADMIN_USERS_MODAL_EDIT_TITLE'], htmlspecialchars($user['name'])); ?></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; // Using Cancel for Close as it's a common pattern ?>"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                        <ul class="nav nav-tabs" id="editUserTabs-<?php echo $user['id']; ?>" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="details-tab-<?php echo $user['id']; ?>" data-bs-toggle="tab"
                                        data-bs-target="#details-<?php echo $user['id']; ?>" type="button" role="tab">
                                    <i class="bi bi-person-circle me-2"></i><?php echo $lang_admin['ADMIN_USERS_MODAL_TAB_USER_DETAILS']; ?>
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="notifications-tab-<?php echo $user['id']; ?>" data-bs-toggle="tab"
                                        data-bs-target="#notifications-<?php echo $user['id']; ?>" type="button" role="tab">
                                    <i class="bi bi-bell me-2"></i><?php echo $lang_admin['ADMIN_USERS_MODAL_TAB_NOTIFICATION_SETTINGS']; ?>
                                </button>
                            </li>
                        </ul>
                        <div class="tab-content mt-3" id="editUserTabContent-<?php echo $user['id']; ?>">
                            <div class="tab-pane fade show active" id="details-<?php echo $user['id']; ?>" role="tabpanel">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3"><label for="name-<?php echo $user['id']; ?>" class="form-label"><?php echo $lang_admin['ADMIN_USERS_TH_NAME']; ?></label><input type="text" class="form-control" id="name-<?php echo $user['id']; ?>" name="name" value="<?php echo htmlspecialchars($user['name']); ?>" required></div>
                                        <div class="mb-3"><label for="email-<?php echo $user['id']; ?>" class="form-label"><?php echo $lang_admin['ADMIN_USERS_TH_EMAIL']; ?></label><input type="email" class="form-control" id="email-<?php echo $user['id']; ?>" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required></div>
                                        <div class="mb-3"><label for="company-<?php echo $user['id']; ?>" class="form-label"><?php echo $lang_admin['ADMIN_USERS_TH_COMPANY']; ?></label><input type="text" class="form-control" id="company-<?php echo $user['id']; ?>" name="company" value="<?php echo htmlspecialchars($user['company'] ?? ''); ?>"></div>
                                        <div class="mb-3"><label for="role-<?php echo $user['id']; ?>" class="form-label"><?php echo $lang_admin['ADMIN_USERS_TH_ROLE']; ?></label>
                                            <select class="form-select" id="role-<?php echo $user['id']; ?>" name="role" required>
                                                <option value="member" <?php echo $user['role'] === 'member' ? 'selected' : ''; ?>><?php echo $lang_admin['ADMIN_USERS_ROLE_MEMBER']; ?></option>
                                                <option value="staff" <?php echo $user['role'] === 'staff' ? 'selected' : ''; ?>><?php echo $lang_admin['ADMIN_USERS_ROLE_STAFF']; ?></option>
                                                <option value="admin" <?php echo $user['role'] === 'admin' ? 'selected' : ''; ?>><?php echo $lang_admin['ADMIN_USERS_ROLE_ADMIN']; ?></option>
                                            </select>
                                        </div>
                                        <?php if (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS): ?>
                                        <div class="mb-3"><label for="country_code-<?php echo $user['id']; ?>" class="form-label"><?php echo $lang_admin['ADMIN_USERS_MODAL_LABEL_COUNTRY']; ?></label>
                                            <select class="form-select" id="country_code-<?php echo $user['id']; ?>" name="country_code">
                                                <option value=""><?php echo $lang_admin['ADMIN_USERS_MODAL_SELECT_COUNTRY_PLACEHOLDER']; ?></option>
                                                <?php $countries = get_country_list(); foreach ($countries as $code => $country_name): ?>
                                                    <option value="<?php echo htmlspecialchars($code); ?>" <?php echo ($user['country_code'] === $code) ? 'selected' : ''; ?>><?php echo htmlspecialchars($country_name); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="mb-3"><label for="city-<?php echo $user['id']; ?>" class="form-label"><?php echo $lang_admin['ADMIN_USERS_MODAL_LABEL_CITY']; ?></label><input type="text" class="form-control" id="city-<?php echo $user['id']; ?>" name="city" value="<?php echo htmlspecialchars($user['city'] ?? ''); ?>"></div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3"><label for="avatar-<?php echo $user['id']; ?>" class="form-label"><?php echo $lang_admin['ADMIN_USERS_MODAL_LABEL_PROFILE_PICTURE']; ?></label><input type="file" class="form-control" id="avatar-<?php echo $user['id']; ?>" name="avatar" accept="image/*"><div class="form-text"><?php echo sprintf($lang_admin['ADMIN_USERS_MODAL_MAX_FILE_SIZE_MB'], MAX_UPLOAD_SIZE / 1024 / 1024); ?></div>
                                        <?php if (!empty($user['avatar'])): ?> <img src="../uploads/avatars/<?php echo htmlspecialchars($user['avatar']); ?>" alt="<?php echo $lang_admin['ADMIN_USERS_AVATAR_ALT']; ?>" class="avatar-sm mt-2"><div class="form-check"><input type="checkbox" class="form-check-input" name="remove_avatar" value="1" id="remove_avatar_<?php echo $user['id']; ?>"><label class="form-check-label" for="remove_avatar_<?php echo $user['id']; ?>">Remove avatar</label></div> <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="notifications-<?php echo $user['id']; ?>" role="tabpanel">
                                <p class="text-muted mb-3"><i class="bi bi-info-circle me-2"></i><?php echo $lang_admin['ADMIN_USERS_MODAL_NOTIFICATIONS_INFO']; ?></p>
                                <?php foreach ($notification_settings_definition as $key => $details): ?>
                                    <div class="form-check form-switch mb-3">
                                        <input class="form-check-input" type="checkbox" role="switch" id="<?php echo $key . '-' . $user['id']; ?>" name="notifications[<?php echo $user['id']; ?>][<?php echo $key; ?>]" value="1" <?php echo (isset($current_user_prefs_modal[$key]) && $current_user_prefs_modal[$key]) ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="<?php echo $key . '-' . $user['id']; ?>"><strong><?php echo htmlspecialchars($lang_admin[$details['label_key']]); ?></strong>
                                            <?php if ($details['admin_only']): ?><br><small class="text-muted"><span class="badge bg-info text-dark"><?php echo $lang_admin['ADMIN_USERS_MODAL_NOTIFY_ADMIN_STAFF_ONLY']; ?></span></small><?php endif; ?>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?></button>
                        <button type="submit" name="edit_user" class="btn btn-primary"><i class="bi bi-floppy me-2"></i><?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_SAVE_CHANGES']; ?></button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="modal fade" id="resetPasswordModal-<?php echo $user['id']; ?>" tabindex="-1" aria-labelledby="resetPasswordModalLabel-<?php echo $user['id']; ?>" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form action="<?php echo getCleanUrl('admin/users'); ?>" method="post">
                    <?php echo get_csrf_input_field(); ?>
                    <div class="modal-header"><h5 class="modal-title" id="resetPasswordModalLabel-<?php echo $user['id']; ?>"><?php echo $lang_admin['ADMIN_USERS_MODAL_RESET_PASSWORD_TITLE']; ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?>"></button></div>
                    <div class="modal-body">
                        <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                        <p><?php echo sprintf($lang_admin['ADMIN_USERS_MODAL_RESET_CONFIRM_TEXT'], htmlspecialchars($user['name'])); ?></p>
                        <p><?php echo $lang_admin['ADMIN_USERS_MODAL_RESET_NEW_PASSWORD_INFO']; ?></p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?></button>
                        <button type="submit" name="reset_password" class="btn btn-warning"><?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_RESET_PASSWORD']; ?></button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php if ($user['id'] !== $_SESSION['user_id']): ?>
    <div class="modal fade" id="deleteUserModal-<?php echo $user['id']; ?>" tabindex="-1" aria-labelledby="deleteUserModalLabel-<?php echo $user['id']; ?>" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form action="<?php echo getCleanUrl('admin/users'); ?>" method="post">
                    <?php echo get_csrf_input_field(); ?>
                    <div class="modal-header"><h5 class="modal-title" id="deleteUserModalLabel-<?php echo $user['id']; ?>"><?php echo $lang_admin['ADMIN_USERS_MODAL_DELETE_USER_TITLE']; ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?>"></button></div>
                    <div class="modal-body">
                        <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                        <p><?php echo sprintf($lang_admin['ADMIN_USERS_MODAL_DELETE_CONFIRM_TEXT'], htmlspecialchars($user['name'])); ?></p>
                        <p class="text-danger"><?php echo $lang_admin['ADMIN_USERS_MODAL_DELETE_WARNING_PERMANENT']; ?></p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?></button>
                        <button type="submit" name="delete_user" class="btn btn-danger"><?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_DELETE_USER']; ?></button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <?php
    // Fetch custom fields for profile zone
    $stmt_cf = $pdo->prepare("SELECT * FROM custom_fields WHERE zone = 'profile' AND is_active = 1 ORDER BY sort_order ASC, id ASC");
    $stmt_cf->execute();
    $profile_custom_fields = $stmt_cf->fetchAll(PDO::FETCH_ASSOC);
    // Fetch custom field values for this user
    $stmt_cfval = $pdo->prepare("SELECT field_id, value FROM custom_field_values WHERE item_id = ?");
    $stmt_cfval->execute([$user['id']]);
    $user_custom_field_values = $stmt_cfval->fetchAll(PDO::FETCH_KEY_PAIR);
    ?>
    <div class="modal fade" id="viewUserModal-<?php echo $user['id']; ?>" tabindex="-1" aria-labelledby="viewUserModalLabel-<?php echo $user['id']; ?>" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title" id="viewUserModalLabel-<?php echo $user['id']; ?>">
                        <i class="bi bi-eye me-2"></i>View User: <?php echo htmlspecialchars($user['name']); ?>
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4 text-center">
                            <?php if (!empty($user['avatar'])): ?>
                                <img src="../uploads/avatars/<?php echo htmlspecialchars($user['avatar']); ?>" alt="Avatar" class="avatar-lg mb-3 rounded-circle">
                            <?php else: ?>
                                <div class="avatar-lg mx-auto mb-3 bg-primary d-flex justify-content-center align-items-center text-white rounded-circle">
                                    <i class="bi bi-person" style="font-size: 3rem;"></i>
                                </div>
                            <?php endif; ?>
                            <h4><?php echo htmlspecialchars($user['name']); ?></h4>
                            <p class="text-muted mb-1"><?php echo htmlspecialchars($user['email']); ?></p>
                            <?php if (!empty($user['company'])): ?>
                                <p><i class="bi bi-building"></i> <?php echo htmlspecialchars($user['company']); ?></p>
                            <?php endif; ?>
                            <span class="badge bg-<?php echo $user['role'] === 'admin' ? 'danger' : ($user['role'] === 'staff' ? 'secondary' : 'primary'); ?>">
                                <?php echo htmlspecialchars(ucfirst($user['role'])); ?>
                            </span>
                            <p class="mt-2"><small>Joined: <?php echo getFormattedDate($user['created_at'], 'F d, Y'); ?></small></p>
                        </div>
                        <div class="col-md-8">
                            <dl class="row mb-0">
                                <dt class="col-sm-4">Full Name</dt>
                                <dd class="col-sm-8"><?php echo htmlspecialchars($user['name']); ?></dd>
                                <dt class="col-sm-4">Email</dt>
                                <dd class="col-sm-8"><?php echo htmlspecialchars($user['email']); ?></dd>
                                <dt class="col-sm-4">Company</dt>
                                <dd class="col-sm-8"><?php echo htmlspecialchars($user['company'] ?? '-'); ?></dd>
                                <dt class="col-sm-4">Role</dt>
                                <dd class="col-sm-8"><?php echo htmlspecialchars(ucfirst($user['role'])); ?></dd>
                                <dt class="col-sm-4">Country</dt>
                                <dd class="col-sm-8"><?php echo htmlspecialchars($user['country_code'] ?? '-'); ?></dd>
                                <dt class="col-sm-4">City</dt>
                                <dd class="col-sm-8"><?php echo htmlspecialchars($user['city'] ?? '-'); ?></dd>
                                <dt class="col-sm-4">Address</dt>
                                <dd class="col-sm-8"><?php echo htmlspecialchars($user['address'] ?? '-'); ?></dd>
                                <dt class="col-sm-4">State</dt>
                                <dd class="col-sm-8"><?php echo htmlspecialchars($user['state'] ?? '-'); ?></dd>
                                <dt class="col-sm-4">Zip Code</dt>
                                <dd class="col-sm-8"><?php echo htmlspecialchars($user['zipcode'] ?? '-'); ?></dd>
                            </dl>
                            <?php if (!empty($profile_custom_fields)): ?>
                                <hr>
                              
                                <dl class="row mb-0">
                                    <?php foreach ($profile_custom_fields as $cf):
                                        $cf_label = htmlspecialchars($cf['name']);
                                        $cf_value = isset($user_custom_field_values[$cf['id']]) ? $user_custom_field_values[$cf['id']] : '';
                                        if ($cf['type'] === 'checkboxes') {
                                            $cf_value = implode(', ', array_filter(array_map('trim', explode(',', $cf_value))));
                                        }
                                    ?>
                                        <dt class="col-sm-4"><?php echo $cf_label; ?></dt>
                                        <dd class="col-sm-8"><?php echo htmlspecialchars($cf_value); ?></dd>
                                    <?php endforeach; ?>
                                </dl>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
<?php endforeach; ?>

<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form action="<?php echo getCleanUrl('admin/users'); ?>" method="post" enctype="multipart/form-data">
                <?php echo get_csrf_input_field(); ?>
                <div class="modal-header"><h5 class="modal-title" id="addUserModalLabel"><?php echo $lang_admin['ADMIN_USERS_MODAL_ADD_TITLE']; ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?>"></button></div>
                <div class="modal-body">
                    <ul class="nav nav-tabs" id="addUserTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="new-details-tab" data-bs-toggle="tab" data-bs-target="#new-details" type="button" role="tab"><i class="bi bi-person-circle me-2"></i><?php echo $lang_admin['ADMIN_USERS_MODAL_TAB_USER_DETAILS']; ?></button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="new-notifications-tab" data-bs-toggle="tab" data-bs-target="#new-notifications" type="button" role="tab"><i class="bi bi-bell me-2"></i><?php echo $lang_admin['ADMIN_USERS_MODAL_TAB_NOTIFICATION_SETTINGS']; ?></button>
                        </li>
                    </ul>
                    <div class="tab-content mt-3" id="addUserTabContent">
                        <div class="tab-pane fade show active" id="new-details" role="tabpanel">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="mb-3"><label for="new_name" class="form-label"><?php echo $lang_admin['ADMIN_USERS_TH_NAME']; ?></label><input type="text" class="form-control" id="new_name" name="name" required></div>
                                    <div class="mb-3"><label for="new_email" class="form-label"><?php echo $lang_admin['ADMIN_USERS_TH_EMAIL']; ?></label><input type="email" class="form-control" id="new_email" name="email" required></div>
                                    <div class="mb-3"><label for="new_company" class="form-label"><?php echo $lang_admin['ADMIN_USERS_TH_COMPANY']; ?></label><input type="text" class="form-control" id="new_company" name="company"></div>
                                    <div class="mb-3"><label for="new_password" class="form-label"><?php echo $lang_admin['ADMIN_USERS_MODAL_LABEL_PASSWORD']; ?></label><input type="password" class="form-control" id="new_password" name="password" required></div>
                                    <div class="mb-3"><label for="new_role" class="form-label"><?php echo $lang_admin['ADMIN_USERS_TH_ROLE']; ?></label>
                                        <select class="form-select" id="new_role" name="role" required>
                                            <option value="member"><?php echo $lang_admin['ADMIN_USERS_ROLE_MEMBER']; ?></option>
                                            <option value="staff"><?php echo $lang_admin['ADMIN_USERS_ROLE_STAFF']; ?></option>
                                            <option value="admin"><?php echo $lang_admin['ADMIN_USERS_ROLE_ADMIN']; ?></option>
                                        </select>
                                    </div>
                                    <?php if (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS): ?>
                                    <div class="mb-3"><label for="new_country_code" class="form-label"><?php echo $lang_admin['ADMIN_USERS_MODAL_LABEL_COUNTRY']; ?></label>
                                        <select class="form-select" id="new_country_code" name="country_code">
                                            <option value=""><?php echo $lang_admin['ADMIN_USERS_MODAL_SELECT_COUNTRY_PLACEHOLDER']; ?></option>
                                            <?php $countries = get_country_list(); $default_country = defined('DEFAULT_COUNTRY') ? DEFAULT_COUNTRY : 'US';
                                            foreach ($countries as $code => $country_name): ?>
                                                <option value="<?php echo htmlspecialchars($code); ?>" <?php echo ($code === $default_country) ? 'selected' : ''; ?>><?php echo htmlspecialchars($country_name); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="mb-3"><label for="new_city" class="form-label"><?php echo $lang_admin['ADMIN_USERS_MODAL_LABEL_CITY']; ?></label><input type="text" class="form-control" id="new_city" name="city"></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <div class="tab-pane fade" id="new-notifications" role="tabpanel">
                            <p class="text-muted mb-3"><i class="bi bi-info-circle me-2"></i><?php echo $lang_admin['ADMIN_USERS_MODAL_ADD_NOTIFICATIONS_INFO']; ?></p>
                            <?php foreach ($notification_settings_definition as $key => $details): ?>
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" role="switch" id="new_<?php echo $key; ?>" name="new_notifications[<?php echo $key; ?>]" value="1" checked>
                                    <label class="form-check-label" for="new_<?php echo $key; ?>"><strong><?php echo htmlspecialchars($lang_admin[$details['label_key']]); ?></strong>
                                        <?php if ($details['admin_only']): ?><br><small class="text-muted"><span class="badge bg-info text-dark"><?php echo $lang_admin['ADMIN_USERS_MODAL_NOTIFY_ADMIN_STAFF_ONLY']; ?></span></small><?php endif; ?>
                                    </label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?></button>
                    <button type="submit" name="add_user" class="btn btn-success"><i class="bi bi-plus-circle me-2"></i><?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_ADD_USER']; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    const perPageSelect = document.getElementById('per_page');
    if (perPageSelect) {
        perPageSelect.addEventListener('change', function() {
            const form = this.closest('form');
            const pageInput = form.querySelector('input[name="page"]');
            if (pageInput) { pageInput.remove(); }
            form.submit();
        });
    }
    const roleSelect = document.getElementById('role');
    if (roleSelect) {
        roleSelect.addEventListener('change', function() {
            const form = this.closest('form');
            const pageInput = form.querySelector('input[name="page"]');
            if (pageInput) { pageInput.remove(); }
            form.submit();
        });
    }
    const searchInput = document.getElementById('search');
    if (searchInput) {
        let searchTimeout;
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                if (this.value.length >= 3 || this.value.length === 0) {
                    const form = this.closest('form');
                    const pageInput = form.querySelector('input[name="page"]');
                    if (pageInput) { pageInput.remove(); }
                    form.submit();
                }
            }, 500);
        });
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                clearTimeout(searchTimeout);
                const form = this.closest('form');
                const pageInput = form.querySelector('input[name="page"]');
                if (pageInput) { pageInput.remove(); }
                form.submit();
            }
        });
    }
    const filterForm = document.querySelector('form[method="GET"]');
    if (filterForm) {
        filterForm.addEventListener('submit', function() {
            const submitBtn = this.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> <?php echo addslashes($lang_admin['ADMIN_USERS_JS_BTN_FILTERING']); ?>';
                submitBtn.disabled = true;
            }
        });
    }
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('search') || urlParams.get('role')) {
        const filterCard = document.querySelector('.card .card-body');
        if (filterCard) {
            filterCard.style.backgroundColor = '#f8f9fa';
            filterCard.style.border = '2px solid #0d6efd';
        }
    }

    // Edit User Modal population
    document.querySelectorAll('.edit-user-btn').forEach(button => {
        button.addEventListener('click', function() {
            const userId = this.dataset.userId;
            const modal = document.getElementById('editUserModal-' + userId);
            if (!modal) return;

            // Populate basic fields (already done by data attributes in PHP, but good for JS consistency)
            modal.querySelector('input[name="user_id"]').value = userId;
            modal.querySelector('.modal-title').textContent = `<?php echo $lang_admin['ADMIN_USERS_MODAL_EDIT_TITLE_PREFIX'] ?? 'Edit User - '; ?>${this.dataset.userName}`; // Using a prefix key
            modal.querySelector('input[name="name"]').value = this.dataset.userName;
            modal.querySelector('input[name="email"]').value = this.dataset.userEmail;
            modal.querySelector('input[name="company"]').value = this.dataset.userCompany || '';
            modal.querySelector('select[name="role"]').value = this.dataset.userRole;
            
            <?php if (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS): ?>
            const countryDropdown = modal.querySelector('select[name="country_code"]');
            if (countryDropdown) countryDropdown.value = this.dataset.userCountry || '';
            const cityInput = modal.querySelector('input[name="city"]');
            if (cityInput) cityInput.value = this.dataset.userCity || '';
            <?php endif; ?>

            // Populate notification settings
            const notificationContainer = modal.querySelector('#notifications-' + userId + ' #notification-settings-' + userId);
            if (notificationContainer) {
                const notificationSettingsDefinition = <?php echo json_encode($lang_admin['ADMIN_USERS_NOTIFICATION_SETTINGS_DEFINITION']); ?>;
                let notificationHtml = '';

                // Fetch current user preferences (ideally via AJAX if they could change, or use PHP-embedded data)
                // For this example, we'll assume current_user_prefs_modal is available for this user in the loop
                // This part is tricky as the modal is generic now. We need to get current prefs for *this* user.
                // The PHP loop that generates modals should embed these current prefs.
                // Let's assume the PHP loop correctly sets $current_user_prefs_modal for each modal instance.
                // The following JS is a template and would need actual data.

                // This is a placeholder - actual data needs to be passed or fetched for `currentUserPrefsForModal`
                const currentUserPrefsForModal = {}; // Replace with actual data loading for the specific user

                Object.entries(notificationSettingsDefinition).forEach(([key, details]) => {
                    const labelText = `<?php echo $lang_admin['${details.label_key}'] ?? '${details.label_key}'; ?>`; // Fallback to key if not found
                    const isChecked = currentUserPrefsForModal[key] ? 'checked' : '';
                    notificationHtml += `
                        <div class="form-check form-switch mb-3">
                            <input class="form-check-input" type="checkbox" role="switch"
                                   id="${key}-${userId}"
                                   name="notifications[${userId}][${key}]"
                                   value="1" ${isChecked}>
                            <label class="form-check-label" for="${key}-${userId}">
                                <strong>${labelText}</strong>
                                ${details.admin_only ? '<br><small class="text-muted"><span class="badge bg-info text-dark"><?php echo $lang_admin['ADMIN_USERS_MODAL_NOTIFY_ADMIN_STAFF_ONLY']; ?></span></small>' : ''}
                            </label>
                        </div>
                    `;
                });
                notificationContainer.innerHTML = notificationHtml;
            }
        });
    });
});
</script>