<?php
define('SECURE_ACCESS', true);

$pageTitle = "User Management";
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

requireAdmin();

$currentUser = getCurrentUser();

$error = '';
$success = '';
$activeTab = isset($_GET['tab']) ? $_GET['tab'] : 'users';

if ($activeTab === 'emp_settings') {
    header("Location: settings?tab=employee");
    exit();
}

// Fetch current employee settings
$settings = getSystemSettings();

// Handle Delete User Action
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: users?tab=users");
        exit();
    }
    $deleteId = (int)$_GET['id'];
    if ($deleteId === $currentUser['id']) {
        $_SESSION['flash_error'] = "You cannot delete your own account.";
    } else {
        try {
            // Check for active dependencies before deletion
            $stmt_pending = $pdo->prepare("SELECT COUNT(*) FROM payouts WHERE user_id = ? AND status = 'pending'");
            $stmt_pending->execute([$deleteId]);
            $pending_payouts = (int)$stmt_pending->fetchColumn();

            $stmt_children = $pdo->prepare("SELECT COUNT(*) FROM users WHERE referrer_id = ? OR parent_id = ?");
            $stmt_children->execute([$deleteId, $deleteId]);
            $child_count = (int)$stmt_children->fetchColumn();

            if ($pending_payouts > 0) {
                $_SESSION['flash_error'] = "Cannot delete user: they have $pending_payouts pending payout(s). Please resolve them first.";
            } elseif ($child_count > 0) {
                $_SESSION['flash_error'] = "Cannot delete user: they have $child_count team member(s). Consider deactivating instead.";
            } else {
                // Soft-delete: preserve data integrity
                $pdo->prepare("UPDATE users SET status = 'deleted', email = CONCAT(email, '_deleted_', id) WHERE id = ?")->execute([$deleteId]);
                logAuditEvent('admin_delete_user', 'user', $deleteId, 'Soft-deleted user from admin panel');
                $_SESSION['flash_success'] = "User deactivated and marked as deleted.";
            }
        } catch (PDOException $e) {
            error_log("Admin delete user error: " . $e->getMessage());
            $_SESSION['flash_error'] = "Failed to delete user. Please try again.";
        }
    }
    header("Location: users?tab=users");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: users?tab=" . urlencode($activeTab));
        exit();
    }
}

// Handle Add User Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_add'])) {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $role = $_POST['role'] ?? 'user';
    $status = $_POST['status'] ?? 'active';
    $employee_code = trim($_POST['employee_code'] ?? '');
    $designation_id = isset($_POST['designation_id']) && $_POST['designation_id'] !== '' ? (int)$_POST['designation_id'] : null;
    $referrer_username = trim($_POST['referrer_username'] ?? '');

    if (empty($username) || empty($email) || empty($password)) {
        $error = "Please fill in all required fields.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } else {
        try {
            $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ? OR email = ?");
            $check->execute([$username, $email]);
            if ($check->fetchColumn() > 0) {
                $error = "Username or Email already exists.";
            } else {
                $referrer_id = null;
                $parent_id = null;

                if (!empty($referrer_username)) {
                    $stmt_ref = $pdo->prepare("SELECT id, designation_id FROM users WHERE username = ? OR employee_code = ?");
                    $stmt_ref->execute([$referrer_username, $referrer_username]);
                    $referrer = $stmt_ref->fetch();
                    if (!$referrer) {
                        $error = "The referrer/sponsor username or employee code you entered does not exist.";
                    } else {
                        $referrer_id = $referrer['id'];

                        // Fetch matrix config of the sponsor to calculate parent with spillover
                        $m_width = 4;
                        $m_depth = 4;
                        if ($referrer['designation_id']) {
                            $stmt_m = $pdo->prepare("SELECT matrix_width, matrix_depth FROM designations WHERE id = ?");
                            $stmt_m->execute([$referrer['designation_id']]);
                            $des = $stmt_m->fetch();
                            if ($des) {
                                $m_width = (int)$des['matrix_width'];
                                $m_depth = (int)$des['matrix_depth'];
                            }
                        }

                        // Run BFS placement algorithm to find parent_id
                        $parent_id = findMatrixPlacement($referrer_id, $m_width, $m_depth);
                    }
                }

                // Determine Employee Code
                $final_emp_code = '';
                if (empty($error)) {
                    if (!empty($employee_code)) {
                        if (strlen($employee_code) < 5 || strlen($employee_code) > 30) {
                            $error = "Employee code must be between 5 and 30 characters.";
                        } else {
                            $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
                            $check_code->execute([$employee_code]);
                            if ($check_code->fetchColumn() > 0) {
                                $error = "Employee code is already in use.";
                            } else {
                                $final_emp_code = $employee_code;
                            }
                        }
                    } else {
                        // Auto-generate if empty
                        $prefix = $settings['emp_code_prefix'];
                        $length = (int)$settings['emp_code_length'];
                        $default_type = $settings['emp_code_default_type'];
                        $custom_val = $settings['emp_code_custom_value'];

                        if ($default_type === 'generated') {
                            $unique = false;
                            $attempts = 0;
                            while (!$unique && $attempts < 15) {
                                $temp_code = generateEmployeeCode($prefix, $length);
                                $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
                                $check_code->execute([$temp_code]);
                                if ($check_code->fetchColumn() == 0) {
                                    $final_emp_code = $temp_code;
                                    $unique = true;
                                }
                                $attempts++;
                            }
                        } else {
                            $temp_code = $custom_val;
                            $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
                            $check_code->execute([$temp_code]);
                            if ($check_code->fetchColumn() == 0) {
                                $final_emp_code = $temp_code;
                            } else {
                                $unique = false;
                                $suffix = 1;
                                while (!$unique && $suffix < 100) {
                                    $s_code = $temp_code . '-' . $suffix;
                                    $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
                                    $check_code->execute([$s_code]);
                                    if ($check_code->fetchColumn() == 0) {
                                        $final_emp_code = $s_code;
                                        $unique = true;
                                    }
                                    $suffix++;
                                }
                            }
                        }
                    }
                }

                if (empty($error)) {
                    try {
                        $pdo->beginTransaction();
                        $hashedPass = password_hash($password, PASSWORD_DEFAULT);
                        $insert = $pdo->prepare("INSERT INTO users (username, email, password, role, status, employee_code, designation_id, referrer_id, parent_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        $insert->execute([$username, $email, $hashedPass, $role, $status, $final_emp_code, $designation_id, $referrer_id, $parent_id]);
                        $new_user_id = $pdo->lastInsertId('users_id_seq');
                        // Award bonuses INSIDE the transaction so a bonus failure rolls back the user insert
                        require_once __DIR__ . '/../../includes/bonus_helper.php';
                        awardSignupAndReferralBonuses($new_user_id, $referrer_id);
                        $pdo->commit();
                        logAuditEvent('admin_create_user', 'user', $new_user_id, "Created user: $username ($email)");
                        $_SESSION['flash_success'] = "User '$username' created successfully with employee code: $final_emp_code.";
                        header("Location: users?tab=users");
                        exit();
                    } catch (PDOException $e) {
                        if ($pdo->inTransaction()) $pdo->rollBack();
                        $error = "Database error: " . $e->getMessage();
                    }
                }
            }
        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    }
}

// Handle Edit User Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_edit'])) {
    $editId = (int)$_POST['edit_id'];
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $role = $_POST['role'] ?? 'user';
    $status = $_POST['status'] ?? 'active';
    $employee_code = trim($_POST['employee_code'] ?? '');
    $designation_id = isset($_POST['designation_id']) && $_POST['designation_id'] !== '' ? (int)$_POST['designation_id'] : null;
    $referrer_username = trim($_POST['referrer_username'] ?? '');

    if (empty($username) || empty($email)) {
        $error = "Please fill in all required fields.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } else {
        try {
            $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE (username = ? OR email = ?) AND id != ?");
            $check->execute([$username, $email, $editId]);
            if ($check->fetchColumn() > 0) {
                $error = "Username or Email is already taken by another user.";
            } else {
                $referrer_id = null;
                $parent_id = null;

                if (!empty($referrer_username)) {
                    $stmt_ref = $pdo->prepare("SELECT id, designation_id FROM users WHERE (username = ? OR employee_code = ?) AND id != ?");
                    $stmt_ref->execute([$referrer_username, $referrer_username, $editId]);
                    $referrer = $stmt_ref->fetch();
                    if (!$referrer) {
                        $error = "The referrer/sponsor username or employee code you entered does not exist.";
                    } else {
                        $referrer_id = $referrer['id'];

                        // Fetch matrix config of the sponsor to calculate parent with spillover
                        $m_width = 4;
                        $m_depth = 4;
                        if ($referrer['designation_id']) {
                            $stmt_m = $pdo->prepare("SELECT matrix_width, matrix_depth FROM designations WHERE id = ?");
                            $stmt_m->execute([$referrer['designation_id']]);
                            $des = $stmt_m->fetch();
                            if ($des) {
                                $m_width = (int)$des['matrix_width'];
                                $m_depth = (int)$des['matrix_depth'];
                            }
                        }

                        // Run BFS placement algorithm to find parent_id
                        $parent_id = findMatrixPlacement($referrer_id, $m_width, $m_depth);
                    }
                }

                // Determine Employee Code on Edit
                $final_emp_code = $employee_code;
                if (empty($error)) {
                    if (empty($employee_code)) {
                        // Auto-generate a new code matching format configurations if cleared
                        $prefix = $settings['emp_code_prefix'];
                        $length = (int)$settings['emp_code_length'];
                        $default_type = $settings['emp_code_default_type'];
                        $custom_val = $settings['emp_code_custom_value'];

                        if ($default_type === 'generated') {
                            $unique = false;
                            $attempts = 0;
                            while (!$unique && $attempts < 15) {
                                $temp_code = generateEmployeeCode($prefix, $length);
                                $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ? AND id != ?");
                                $check_code->execute([$temp_code, $editId]);
                                if ($check_code->fetchColumn() == 0) {
                                    $final_emp_code = $temp_code;
                                    $unique = true;
                                }
                                $attempts++;
                            }
                        } else {
                            $temp_code = $custom_val;
                            $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ? AND id != ?");
                            $check_code->execute([$temp_code, $editId]);
                            if ($check_code->fetchColumn() == 0) {
                                $final_emp_code = $temp_code;
                            } else {
                                $unique = false;
                                $suffix = 1;
                                while (!$unique && $suffix < 100) {
                                    $s_code = $temp_code . '-' . $suffix;
                                    $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ? AND id != ?");
                                    $check_code->execute([$s_code, $editId]);
                                    if ($check_code->fetchColumn() == 0) {
                                        $final_emp_code = $s_code;
                                        $unique = true;
                                    }
                                    $suffix++;
                                }
                            }
                        }
                    } else {
                        // Validate custom entered code
                        if (strlen($employee_code) < 5 || strlen($employee_code) > 30) {
                            $error = "Employee code must be between 5 and 30 characters.";
                        } else {
                            $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ? AND id != ?");
                            $check_code->execute([$employee_code, $editId]);
                            if ($check_code->fetchColumn() > 0) {
                                $error = "Employee code is already in use.";
                            }
                        }
                    }
                }

                if (empty($error)) {
                    if (!empty($password)) {
                        $hashedPass = password_hash($password, PASSWORD_DEFAULT);
                        $update = $pdo->prepare("UPDATE users SET username = ?, email = ?, password = ?, role = ?, status = ?, employee_code = ?, designation_id = ?, referrer_id = ?, parent_id = ? WHERE id = ?");
                        $update->execute([$username, $email, $hashedPass, $role, $status, $final_emp_code, $designation_id, $referrer_id, $parent_id, $editId]);
                    } else {
                        $update = $pdo->prepare("UPDATE users SET username = ?, email = ?, role = ?, status = ?, employee_code = ?, designation_id = ?, referrer_id = ?, parent_id = ? WHERE id = ?");
                        $update->execute([$username, $email, $role, $status, $final_emp_code, $designation_id, $referrer_id, $parent_id, $editId]);
                    }

                    if ($editId === $currentUser['id']) {
                        $_SESSION['username'] = $username;
                        $_SESSION['email'] = $email;
                        $_SESSION['role'] = $role;
                        $_SESSION['status'] = $status;
                    }

                    $_SESSION['flash_success'] = "User details updated successfully.";
                    header("Location: users?tab=users");
                    exit();
                }
            }
        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    }
}



// Handle User/Employee Invitation Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_user_invite'])) {
    $email = trim($_POST['user_invite_email'] ?? '');
    
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
    } else {
        try {
            $check_user = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
            $check_user->execute([$email]);
            
            $check_invite = $pdo->prepare("SELECT COUNT(*) FROM user_invitations WHERE email = ?");
            $check_invite->execute([$email]);
            
            if ($check_user->fetchColumn() > 0) {
                $error = "This email address is already registered as an active account.";
            } elseif ($check_invite->fetchColumn() > 0) {
                $error = "A registration invitation has already been issued to this email address.";
            } else {
                $token = bin2hex(random_bytes(16));
                $stmt = $pdo->prepare("INSERT INTO user_invitations (email, token, status) VALUES (?, ?, 'pending')");
                $stmt->execute([$email, $token]);
                $_SESSION['flash_success'] = "User registration invitation generated for $email.";
                header("Location: users?tab=user_invites");
                exit();
            }
        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    }
}

// Handle Revoke User Invitation Action
if (isset($_GET['action']) && $_GET['action'] === 'revoke_user_invite' && isset($_GET['invite_id'])) {
    $inviteId = (int)$_GET['invite_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM user_invitations WHERE id = ?");
        $stmt->execute([$inviteId]);
        $_SESSION['flash_success'] = "Registration invitation revoked.";
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to revoke invitation.";
    }
    header("Location: users?tab=user_invites");
    exit();
}

// Handle Speaker Invitation Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_invite'])) {
    $email = trim($_POST['invite_email'] ?? '');
    
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
    } else {
        try {
            $check_user = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
            $check_user->execute([$email]);
            
            $check_invite = $pdo->prepare("SELECT COUNT(*) FROM speaker_invitations WHERE email = ?");
            $check_invite->execute([$email]);
            
            if ($check_user->fetchColumn() > 0) {
                $error = "This email address is already registered as an active account.";
            } elseif ($check_invite->fetchColumn() > 0) {
                $error = "An invitation has already been issued to this email address.";
            } else {
                $token = bin2hex(random_bytes(16));
                $stmt = $pdo->prepare("INSERT INTO speaker_invitations (email, token, status) VALUES (?, ?, 'pending')");
                $stmt->execute([$email, $token]);
                $_SESSION['flash_success'] = "Speaker invitation generated successfully for $email.";
                header("Location: users?tab=invites");
                exit();
            }
        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    }
}

// Handle Revoke Speaker Invitation Action
if (isset($_GET['action']) && $_GET['action'] === 'revoke_invite' && isset($_GET['invite_id'])) {
    $inviteId = (int)$_GET['invite_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM speaker_invitations WHERE id = ?");
        $stmt->execute([$inviteId]);
        $_SESSION['flash_success'] = "Speaker invitation revoked.";
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to revoke speaker invitation.";
    }
    header("Location: users?tab=invites");
    exit();
}

// Handle Organizer Invitation Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_org_invite'])) {
    $email = trim($_POST['org_invite_email'] ?? '');
    
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
    } else {
        try {
            $check_user = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
            $check_user->execute([$email]);
            
            $check_invite = $pdo->prepare("SELECT COUNT(*) FROM organizer_invitations WHERE email = ?");
            $check_invite->execute([$email]);
            
            if ($check_user->fetchColumn() > 0) {
                $error = "This email address is already registered as an active account.";
            } elseif ($check_invite->fetchColumn() > 0) {
                $error = "An organizer invitation has already been issued to this email address.";
            } else {
                $token = bin2hex(random_bytes(16));
                $stmt = $pdo->prepare("INSERT INTO organizer_invitations (email, token, status) VALUES (?, ?, 'pending')");
                $stmt->execute([$email, $token]);
                $_SESSION['flash_success'] = "Organizer invitation generated successfully for $email.";
                header("Location: users?tab=org_invites");
                exit();
            }
        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    }
}

// Handle Revoke Organizer Invitation Action
if (isset($_GET['action']) && $_GET['action'] === 'revoke_org_invite' && isset($_GET['invite_id'])) {
    $inviteId = (int)$_GET['invite_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM organizer_invitations WHERE id = ?");
        $stmt->execute([$inviteId]);
        $_SESSION['flash_success'] = "Organizer invitation revoked.";
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to revoke organizer invitation.";
    }
    header("Location: users?tab=org_invites");
    exit();
}

// Handle Sponsor Invitation Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_sponsor_invite'])) {
    $email = trim($_POST['sponsor_invite_email'] ?? '');
    
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
    } else {
        try {
            $check_user = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
            $check_user->execute([$email]);
            
            $check_invite = $pdo->prepare("SELECT COUNT(*) FROM sponsor_invitations WHERE email = ?");
            $check_invite->execute([$email]);
            
            if ($check_user->fetchColumn() > 0) {
                $error = "This email address is already registered as an active account.";
            } elseif ($check_invite->fetchColumn() > 0) {
                $error = "A sponsor invitation has already been issued to this email address.";
            } else {
                $token = bin2hex(random_bytes(16));
                $stmt = $pdo->prepare("INSERT INTO sponsor_invitations (email, token, status) VALUES (?, ?, 'pending')");
                $stmt->execute([$email, $token]);
                $_SESSION['flash_success'] = "Sponsor invitation generated successfully for $email.";
                header("Location: users?tab=sponsor_invites");
                exit();
            }
        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    }
}

// Handle Revoke Sponsor Invitation Action
if (isset($_GET['action']) && $_GET['action'] === 'revoke_sponsor_invite' && isset($_GET['invite_id'])) {
    $inviteId = (int)$_GET['invite_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM sponsor_invitations WHERE id = ?");
        $stmt->execute([$inviteId]);
        $_SESSION['flash_success'] = "Sponsor invitation revoked.";
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to revoke sponsor invitation.";
    }
    header("Location: users?tab=sponsor_invites");
    exit();
}

// Fetch single user if editing
$editUser = null;
if (isset($_GET['edit_id'])) {
    $editId = (int)$_GET['edit_id'];
    try {
        $stmt = $pdo->prepare("SELECT u.*, COALESCE(ref.employee_code, ref.username) as referrer_username 
                               FROM users u 
                               LEFT JOIN users ref ON u.referrer_id = ref.id 
                               WHERE u.id = ?");
        $stmt->execute([$editId]);
        $editUser = $stmt->fetch();
        $activeTab = 'users';
    } catch (PDOException $e) {
        $error = "Failed to load user details for editing.";
    }
}

// Fetch Users List
$search = trim($_GET['search'] ?? '');
$roleFilter = trim($_GET['role'] ?? '');

$user_query = "SELECT u.id, u.username, u.email, u.role, u.status, u.employee_code, u.created_at,
                      d.title as designation_title,
                      ref.username as referrer_username,
                      par.username as parent_username,
                      COALESCE((SELECT COUNT(*) FROM users WHERE referrer_id = u.id), 0) AS team_size,
                      COALESCE((SELECT SUM(amount) FROM earnings WHERE user_id = u.id), 0.00) AS total_earnings,
                      COALESCE((SELECT SUM(amount) FROM payouts WHERE user_id = u.id AND status = 'paid'), 0.00) AS total_withdrawn,
                      GREATEST(0.00, COALESCE((SELECT SUM(amount) FROM earnings WHERE user_id = u.id), 0.00) - COALESCE((SELECT SUM(amount) FROM payouts WHERE user_id = u.id AND (status = 'paid' OR status = 'pending')), 0.00)) AS balance
               FROM users u
               LEFT JOIN designations d ON u.designation_id = d.id
               LEFT JOIN users ref ON u.referrer_id = ref.id
               LEFT JOIN users par ON u.parent_id = par.id
               WHERE 1=1";
$user_params = [];

// Count query builder to support pagination
$count_query = "SELECT COUNT(*) FROM users u WHERE 1=1";
$count_params = [];

if (!empty($search)) {
    $user_query .= " AND (u.username ILIKE ? OR u.email ILIKE ? OR u.employee_code ILIKE ?)";
    $user_params[] = "%$search%";
    $user_params[] = "%$search%";
    $user_params[] = "%$search%";

    $count_query .= " AND (u.username ILIKE ? OR u.email ILIKE ? OR u.employee_code ILIKE ?)";
    $count_params[] = "%$search%";
    $count_params[] = "%$search%";
    $count_params[] = "%$search%";
}

if (!empty($roleFilter)) {
    $user_query .= " AND u.role = ?";
    $user_params[] = $roleFilter;

    $count_query .= " AND u.role = ?";
    $count_params[] = $roleFilter;
}

$user_query .= " ORDER BY u.id DESC";

// Pagination variables
$limit = 10;
$page = isset($_GET['page']) && $activeTab === 'users' ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;
$total_records = 0;
$total_pages = 0;

try {
    if ($pdo) {
        $stmt_count = $pdo->prepare($count_query);
        $stmt_count->execute($count_params);
        $total_records = (int)$stmt_count->fetchColumn() ?: 0;
        $total_pages = ceil($total_records / $limit);

        $paginated_user_query = $user_query . " LIMIT $limit OFFSET $offset";
        $stmt = $pdo->prepare($paginated_user_query);
        $stmt->execute($user_params);
        $users = $stmt->fetchAll();
    }
} catch (PDOException $e) {
    $users = [];
    $error = "Failed to load users: " . $e->getMessage();
}

// Fetch all designations for option mapping
$designation_options = [];
try {
    $stmt = $pdo->query("SELECT id, title FROM designations ORDER BY id ASC");
    $designation_options = $stmt->fetchAll();
} catch (PDOException $e) {
    // Ignore / empty
}

// Fetch User/Employee Invitations
$user_invitations = [];
try {
    $stmt = $pdo->query("SELECT * FROM user_invitations ORDER BY id DESC");
    $user_invitations = $stmt->fetchAll();
} catch (PDOException $e) {
    $error = "Failed to load user invitations.";
}

// Fetch Speaker Invitations
$invitations = [];
try {
    $stmt = $pdo->query("SELECT * FROM speaker_invitations ORDER BY id DESC");
    $invitations = $stmt->fetchAll();
} catch (PDOException $e) {
    $error = "Failed to load speaker invitations.";
}

// Fetch Organizer Invitations
$org_invitations = [];
try {
    $stmt = $pdo->query("SELECT * FROM organizer_invitations ORDER BY id DESC");
    $org_invitations = $stmt->fetchAll();
} catch (PDOException $e) {
    $error = "Failed to load organizer invitations.";
}

// Fetch Sponsor Invitations
$sponsor_invitations = [];
try {
    $stmt = $pdo->query("SELECT * FROM sponsor_invitations ORDER BY id DESC");
    $sponsor_invitations = $stmt->fetchAll();
} catch (PDOException $e) {
    $error = "Failed to load sponsor invitations.";
}

// Fetch Pending KYC count for badge
$pending_kyc_count = 0;
try {
    $stmt_p = $pdo->query("SELECT COUNT(*) FROM kyc_records WHERE doc1_status = 'pending' OR doc2_status = 'pending' OR bank_status = 'initiated'");
    $pending_kyc_count = $stmt_p->fetchColumn();
} catch (PDOException $e) {
    // Ignore / empty
}

include __DIR__ . '/../../includes/header.php';
?>

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
    <div>
        <h1 class="h2 fw-bold text-dark mb-1">User & Access Management</h1>
        <p class="text-muted mb-0">Manage accounts, configure employee codes, or issue role-based onboarding invitations.</p>
    </div>
    <?php if ($activeTab === 'users'): ?>
        <div>
            <button type="button" class="btn btn-primary px-4 py-2.5 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#userModal">
                <i class="bi bi-person-plus-fill me-1"></i> Add New User
            </button>
        </div>
    <?php endif; ?>
</div>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0 mb-4" role="alert">
        <i class="bi bi-x-circle-fill me-2"></i>
        <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<!-- Tabs Navigation -->
<div class="table-responsive mb-4">
    <ul class="nav nav-tabs flex-nowrap" id="managementTabs" role="tablist" style="border-bottom: 2px solid #dee2e6;">
        <li class="nav-item" role="presentation">
            <a class="nav-link <?php echo $activeTab === 'users' ? 'active fw-bold text-primary' : 'text-muted'; ?>" href="users?tab=users">
                <i class="bi bi-people-fill me-1"></i> User Accounts
            </a>
        </li>

        <li class="nav-item" role="presentation">
            <a class="nav-link <?php echo $activeTab === 'user_invites' ? 'active fw-bold text-primary' : 'text-muted'; ?>" href="users?tab=user_invites">
                <i class="bi bi-person-fill-add me-1"></i> User Invites <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace ms-1"><?php echo count($user_invitations); ?></span>
            </a>
        </li>
        <li class="nav-item" role="presentation">
            <a class="nav-link <?php echo $activeTab === 'invites' ? 'active fw-bold text-primary' : 'text-muted'; ?>" href="users?tab=invites">
                <i class="bi bi-person-workspace me-1"></i> Speaker Invites <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace ms-1"><?php echo count($invitations); ?></span>
            </a>
        </li>
        <li class="nav-item" role="presentation">
            <a class="nav-link <?php echo $activeTab === 'org_invites' ? 'active fw-bold text-primary' : 'text-muted'; ?>" href="users?tab=org_invites">
                <i class="bi bi-envelope-paper-fill me-1"></i> Organizer Invites <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace ms-1"><?php echo count($org_invitations); ?></span>
            </a>
        </li>
        <li class="nav-item" role="presentation">
            <a class="nav-link <?php echo $activeTab === 'sponsor_invites' ? 'active fw-bold text-primary' : 'text-muted'; ?>" href="users?tab=sponsor_invites">
                <i class="bi bi-award-fill me-1"></i> Sponsor Invites <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace ms-1"><?php echo count($sponsor_invitations); ?></span>
            </a>
        </li>
    </ul>
</div>

<div class="row g-4">
    
    <!-- Tab 1: User Accounts -->
    <?php if ($activeTab === 'users'): ?>
        <!-- Users Table (Full Width) -->
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <!-- Search & Filters -->
                <div class="card-header bg-white border-bottom py-3">
                    <form method="GET" action="users" class="row g-2">
                        <input type="hidden" name="tab" value="users">
                        <div class="col-12 col-md-6">
                            <div class="input-group">
                                <span class="input-group-text bg-white text-muted"><i class="bi bi-search"></i></span>
                                <input type="text" class="form-control" name="search" placeholder="Search by name, email, or code..." value="<?php echo htmlspecialchars($search); ?>">
                            </div>
                        </div>
                        <div class="col-12 col-sm-8 col-md-4">
                            <select class="form-select" name="role">
                                <option value="">All Roles</option>
                                <option value="user" <?php echo $roleFilter === 'user' ? 'selected' : ''; ?>>User (Attendee)</option>
                                <option value="speaker" <?php echo $roleFilter === 'speaker' ? 'selected' : ''; ?>>Speaker</option>
                                <option value="organizer" <?php echo $roleFilter === 'organizer' ? 'selected' : ''; ?>>Organizer</option>
                                <option value="sponsor" <?php echo $roleFilter === 'sponsor' ? 'selected' : ''; ?>>Sponsor</option>
                                <option value="admin" <?php echo $roleFilter === 'admin' ? 'selected' : ''; ?>>Administrator</option>
                            </select>
                        </div>
                        <div class="col-12 col-sm-4 col-md-2 d-grid">
                            <button type="submit" class="btn btn-outline-secondary">Filter</button>
                        </div>
                    </form>
                </div>
                
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                                <tr>
                                    <th class="ps-4">User</th>
                                    <th>Email</th>
                                    <th>Employee Code</th>
                                    <th>Designation Rank</th>
                                    <th>Organization Placement</th>
                                    <th>Team Size</th>
                                    <th>Earnings</th>
                                    <th>Withdraw</th>
                                    <th>Balance</th>
                                    <th>Role</th>
                                    <th>Status</th>
                                    <th class="text-end pe-4">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($users)): ?>
                                    <tr>
                                        <td colspan="12" class="text-center py-5 text-muted">
                                            <i class="bi bi-people fs-1 mb-2"></i>
                                            <p class="mb-0">No users found.</p>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($users as $u): ?>
                                        <tr>
                                            <td class="ps-4">
                                                <div class="d-flex align-items-center">
                                                    <div class="p-2 bg-light rounded-circle text-secondary me-3 d-none d-sm-block">
                                                        <i class="bi bi-person fs-5"></i>
                                                    </div>
                                                    <div>
                                                        <strong class="text-dark"><?php echo htmlspecialchars($u['username']); ?></strong>
                                                        <?php if ($u['id'] === $currentUser['id']): ?>
                                                            <span class="badge bg-secondary ms-1 small">You</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="text-secondary"><?php echo htmlspecialchars($u['email']); ?></span>
                                            </td>
                                            <td>
                                                <span class="font-monospace small bg-light border px-2 py-1 rounded text-dark">
                                                    <?php echo htmlspecialchars($u['employee_code'] ? $u['employee_code'] : 'NONE'); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-secondary bg-opacity-10 text-secondary border px-2.5 py-1 text-uppercase font-monospace" style="font-size: 0.75rem;">
                                                    <i class="bi bi-award-fill me-1"></i><?php echo htmlspecialchars($u['designation_title'] ? $u['designation_title'] : 'NO RANK'); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <div class="small text-secondary">
                                                    <div>Referrer: <strong class="text-dark"><?php echo htmlspecialchars($u['referrer_username'] ? $u['referrer_username'] : 'NONE'); ?></strong></div>
                                                    <div>Parent: <strong class="text-dark"><?php echo htmlspecialchars($u['parent_username'] ? $u['parent_username'] : 'NONE'); ?></strong></div>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="badge bg-secondary font-monospace"><?php echo $u['team_size']; ?></span>
                                            </td>
                                            <td>
                                                <strong class="text-dark">₹<?php echo number_format($u['total_earnings'], 2); ?></strong>
                                            </td>
                                            <td>
                                                <span class="text-secondary">₹<?php echo number_format($u['total_withdrawn'], 2); ?></span>
                                            </td>
                                            <td>
                                                <strong class="text-success">₹<?php echo number_format($u['balance'], 2); ?></strong>
                                            </td>
                                            <td>
                                                <span class="badge <?php 
                                                    if ($u['role'] === 'admin') echo 'bg-danger bg-opacity-10 text-danger';
                                                    elseif ($u['role'] === 'speaker') echo 'bg-warning bg-opacity-10 text-warning-emphasis';
                                                    elseif ($u['role'] === 'organizer') echo 'bg-info bg-opacity-10 text-info-emphasis';
                                                    elseif ($u['role'] === 'sponsor') echo 'bg-success bg-opacity-10 text-success-emphasis';
                                                    else echo 'bg-primary bg-opacity-10 text-primary'; 
                                                ?> px-2.5 py-1 text-uppercase font-monospace" style="font-size: 0.75rem;">
                                                    <?php echo strtoupper($u['role']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge <?php echo $u['status'] === 'active' ? 'bg-success' : 'bg-secondary'; ?> rounded-pill" style="font-size: 0.75rem;">
                                                    <?php echo htmlspecialchars($u['status']); ?>
                                                </span>
                                            </td>
                                            <td class="text-end pe-4">
                                                <div class="d-flex justify-content-end gap-2">
                                                    <a href="../reports?tab=ledger&filter_user=<?php echo $u['id']; ?>" class="btn btn-sm btn-outline-info" title="View User Ledger">
                                                        <i class="bi bi-journal-text"></i>
                                                    </a>
                                                    <a href="../documents?user_id=<?php echo $u['id']; ?>" class="btn btn-sm btn-outline-primary" title="View Appointment & ID Card">
                                                        <i class="bi bi-file-earmark-person"></i>
                                                    </a>
                                                    <a href="users?edit_id=<?php echo $u['id']; ?>" class="btn btn-sm btn-outline-warning" title="Edit User">
                                                        <i class="bi bi-pencil-fill"></i>
                                                    </a>
                                                    <?php if ($u['id'] !== $currentUser['id']): ?>
                                                        <a href="users?action=delete&id=<?php echo $u['id']; ?>&csrf_token=<?php echo getCSRFToken(); ?>" class="btn btn-sm btn-outline-danger" title="Delete User" onclick="return confirm('Delete user <?php echo htmlspecialchars($u['username']); ?>?');">
                                                            <i class="bi bi-trash3-fill"></i>
                                                        </a>
                                                    <?php else: ?>
                                                        <button class="btn btn-sm btn-outline-secondary" disabled>
                                                            <i class="bi bi-trash3-fill"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php if ($total_pages > 1): ?>
                    <div class="card-footer bg-light border-top py-3 d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
                        <div class="small text-secondary font-monospace">
                            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_records); ?> of <?php echo $total_records; ?> users
                        </div>
                        <nav aria-label="Page navigation">
                            <ul class="pagination pagination-sm mb-0">
                                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>"><i class="bi bi-chevron-left"></i></a>
                                </li>
                                <?php
                                    $start = max(1, $page - 2);
                                    $end = min($total_pages, $page + 2);
                                    for ($i = $start; $i <= $end; $i++):
                                ?>
                                    <li class="page-item <?php echo $page === $i ? 'active' : ''; ?>">
                                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                                    </li>
                                <?php endfor; ?>
                                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>"><i class="bi bi-chevron-right"></i></a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Refactored Add/Edit User Modal Dialog -->
        <div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <form method="POST" action="users?tab=users" class="modal-content">
                    <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                    <div class="modal-header">
                        <h5 class="modal-title fw-bold" id="userModalLabel">
                            <?php if ($editUser): ?>
                                <i class="bi bi-person-fill-gear me-2 text-warning"></i>Edit User Account
                            <?php else: ?>
                                <i class="bi bi-person-plus-fill me-2 text-primary"></i>Add New User Account
                            <?php endif; ?>
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <?php if ($editUser): ?>
                            <input type="hidden" name="edit_id" value="<?php echo $editUser['id']; ?>">
                        <?php endif; ?>

                        <div class="mb-3">
                            <label for="username" class="form-label">Username <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="username" name="username" required value="<?php echo htmlspecialchars($editUser['username'] ?? ''); ?>">
                        </div>

                        <div class="mb-3">
                            <label for="email" class="form-label">Email Address <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="email" name="email" required value="<?php echo htmlspecialchars($editUser['email'] ?? ''); ?>">
                        </div>

                        <div class="mb-3">
                            <label for="password" class="form-label">
                                Password 
                                <?php if ($editUser): ?>
                                    <span class="text-muted small">(Leave blank to keep current)</span>
                                <?php else: ?>
                                    <span class="text-danger">*</span>
                                <?php endif; ?>
                            </label>
                            <input type="password" class="form-control" id="password" name="password" <?php echo $editUser ? '' : 'required'; ?>>
                        </div>

                        <div class="mb-3">
                            <label for="employee_code" class="form-label">Employee Code <span class="text-muted small">(Optional)</span></label>
                            <input type="text" class="form-control" id="employee_code" name="employee_code" placeholder="Leave blank to auto-generate" value="<?php echo htmlspecialchars($editUser['employee_code'] ?? ''); ?>">
                        </div>

                        <div class="mb-3">
                            <label for="designation_id" class="form-label">Corporate Designation Rank</label>
                            <select class="form-select" id="designation_id" name="designation_id">
                                <option value="">None / Standard Rank</option>
                                <?php foreach ($designation_options as $opt): ?>
                                    <option value="<?php echo $opt['id']; ?>" <?php echo isset($editUser) && (int)$editUser['designation_id'] === (int)$opt['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($opt['title']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label for="referrer_username" class="form-label">Sponsor / Referrer (Username or Employee Code) <span class="text-muted small">(Optional)</span></label>
                            <input type="text" class="form-control" id="referrer_username" name="referrer_username" placeholder="e.g. sponsor_username or REPL..." value="<?php echo htmlspecialchars($editUser['referrer_username'] ?? ''); ?>">
                            <span class="text-muted small">Specifying a sponsor automatically computes and places them inside the Corporate Hierarchy Org Tree.</span>
                        </div>

                        <div class="mb-3">
                            <label for="role" class="form-label">Role <span class="text-danger">*</span></label>
                            <select class="form-select" id="role" name="role" required>
                                <option value="user" <?php echo isset($editUser) && $editUser['role'] === 'user' ? 'selected' : ''; ?>>User (Attendee)</option>
                                <option value="speaker" <?php echo isset($editUser) && $editUser['role'] === 'speaker' ? 'selected' : ''; ?>>Speaker</option>
                                <option value="organizer" <?php echo isset($editUser) && $editUser['role'] === 'organizer' ? 'selected' : ''; ?>>Organizer</option>
                                <option value="sponsor" <?php echo isset($editUser) && $editUser['role'] === 'sponsor' ? 'selected' : ''; ?>>Sponsor</option>
                                <option value="admin" <?php echo isset($editUser) && $editUser['role'] === 'admin' ? 'selected' : ''; ?>>Administrator</option>
                            </select>
                        </div>

                        <div class="mb-2">
                            <label for="status" class="form-label">Status <span class="text-danger">*</span></label>
                            <select class="form-select" id="status" name="status" required>
                                <option value="active" <?php echo isset($editUser) && $editUser['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="inactive" <?php echo isset($editUser) && $editUser['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                        <?php if ($editUser): ?>
                            <button type="submit" name="submit_edit" class="btn btn-warning px-4 fw-bold">
                                <i class="bi bi-save me-1"></i> Save Changes
                            </button>
                        <?php else: ?>
                            <button type="submit" name="submit_add" class="btn btn-primary px-4 fw-bold">
                                <i class="bi bi-person-plus-fill me-1"></i> Add User
                            </button>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>



    <!-- Tab 3: User Invitations (Invite-Only Registration) -->
    <?php if ($activeTab === 'user_invites'): ?>
        <!-- User Invite Form Sidebar -->
        <div class="col-12 col-lg-4">
            <div class="card border-0 shadow-sm sticky-lg-top" style="top: 24px;">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-envelope-plus me-2 text-primary"></i>Invite Attendee</h5>
                </div>
                <div class="card-body">
                    <p class="text-muted small">Send secure registration tokens to attendees or employees. Invited emails can onboard via a dedicated registration page.</p>
                    <form method="POST" action="users?tab=user_invites">
                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                        <div class="mb-4">
                            <label for="user_invite_email" class="form-label">Attendee Email Address <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="user_invite_email" name="user_invite_email" required placeholder="employee@company.com">
                        </div>
                        <div class="d-grid">
                            <button type="submit" name="submit_user_invite" class="btn btn-primary py-2 fw-bold">
                                <i class="bi bi-send-fill me-1"></i> Generate User Invitation
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- User Invitations Table -->
        <div class="col-12 col-lg-8">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-list-stars me-2 text-primary"></i>User Onboarding Invitations</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                                <tr>
                                    <th class="ps-4">Email</th>
                                    <th>Status</th>
                                    <th>Sent Date</th>
                                    <th>Registration Link (Click to Copy/Test)</th>
                                    <th class="text-end pe-4">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($user_invitations)): ?>
                                    <tr>
                                        <td colspan="5" class="text-center py-5 text-muted">
                                            <i class="bi bi-envelope-exclamation fs-1 mb-2"></i>
                                            <p class="mb-0">No user invitations found.</p>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($user_invitations as $ui): ?>
                                        <?php 
                                            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
                                            $onboardUrl = $protocol . $_SERVER['HTTP_HOST'] . "/yt/register?token=" . $ui['token'];
                                        ?>
                                        <tr>
                                            <td class="ps-4">
                                                <strong class="text-dark"><?php echo htmlspecialchars($ui['email']); ?></strong>
                                            </td>
                                            <td>
                                                <span class="badge <?php echo $ui['status'] === 'accepted' ? 'bg-success' : 'bg-warning text-dark'; ?> px-2.5 py-1">
                                                    <?php echo strtoupper($ui['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="text-muted small"><?php echo date('Y-m-d H:i', strtotime($ui['created_at'])); ?></span>
                                            </td>
                                            <td>
                                                <?php if ($ui['status'] === 'pending'): ?>
                                                    <div class="input-group input-group-sm" style="max-width: 320px;">
                                                        <input type="text" class="form-control form-control-sm bg-light font-monospace small" readonly value="<?php echo htmlspecialchars($onboardUrl); ?>" id="inviteUrl-<?php echo $ui['id']; ?>">
                                                        <button class="btn btn-outline-secondary" type="button" onclick="copyLink('inviteUrl-<?php echo $ui['id']; ?>')" title="Copy Link">
                                                            <i class="bi bi-clipboard"></i>
                                                        </button>
                                                        <a href="<?php echo $onboardUrl; ?>" class="btn btn-outline-primary" target="_blank" title="Open Link">
                                                            <i class="bi bi-box-arrow-up-right"></i>
                                                        </a>
                                                    </div>
                                                <?php else: ?>
                                                    <span class="text-muted small font-monospace">Used - Profile Onboarded</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-end pe-4">
                                                <a href="users?tab=user_invites&action=revoke_user_invite&invite_id=<?php echo $ui['id']; ?>" class="btn btn-sm btn-outline-danger" title="Revoke Invite" onclick="return confirm('Revoke user invitation?');">
                                                    <i class="bi bi-x-circle-fill"></i> Revoke
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- Tab 4: Speaker Invitations -->
    <?php if ($activeTab === 'invites'): ?>
        <!-- Invite Form Sidebar -->
        <div class="col-12 col-lg-4">
            <div class="card border-0 shadow-sm sticky-lg-top" style="top: 24px;">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-person-plus-fill me-2 text-primary"></i>Invite Speaker</h5>
                </div>
                <div class="card-body">
                    <p class="text-muted small">Invite speakers to join the platform. Only invited email addresses will be allowed to access the speaker registration and onboarding flow.</p>
                    <form method="POST" action="users?tab=invites">
                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                        <div class="mb-4">
                            <label for="invite_email" class="form-label">Speaker Email Address <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="invite_email" name="invite_email" required placeholder="speaker@domain.com">
                        </div>
                        <div class="d-grid">
                            <button type="submit" name="submit_invite" class="btn btn-primary py-2 fw-bold">
                                <i class="bi bi-envelope-plus-fill me-1"></i> Send Invite Token
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Invitations List Table -->
        <div class="col-12 col-lg-8">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-list-stars me-2 text-primary"></i>Speaker Onboarding Invitations</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                                <tr>
                                    <th class="ps-4">Email</th>
                                    <th>Status</th>
                                    <th>Sent Date</th>
                                    <th>Registration Link (Click to Copy/Test)</th>
                                    <th class="text-end pe-4">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($invitations)): ?>
                                    <tr>
                                        <td colspan="5" class="text-center py-5 text-muted">
                                            <i class="bi bi-envelope-exclamation fs-1 mb-2"></i>
                                            <p class="mb-0">No speaker invitations found.</p>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($invitations as $inv): ?>
                                        <?php 
                                            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
                                            $onboardUrl = $protocol . $_SERVER['HTTP_HOST'] . "/yt/onboard_speaker?token=" . $inv['token'];
                                        ?>
                                        <tr>
                                            <td class="ps-4">
                                                <strong class="text-dark"><?php echo htmlspecialchars($inv['email']); ?></strong>
                                            </td>
                                            <td>
                                                <span class="badge <?php echo $inv['status'] === 'accepted' ? 'bg-success' : 'bg-warning text-dark'; ?> px-2.5 py-1 text-uppercase font-monospace" style="font-size: 0.75rem;">
                                                    <?php echo strtoupper($inv['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="text-muted small"><?php echo date('Y-m-d H:i', strtotime($inv['created_at'])); ?></span>
                                            </td>
                                            <td>
                                                <?php if ($inv['status'] === 'pending'): ?>
                                                    <div class="input-group input-group-sm" style="max-width: 320px;">
                                                        <input type="text" class="form-control form-control-sm bg-light font-monospace small" readonly value="<?php echo htmlspecialchars($onboardUrl); ?>" id="inviteUrl-<?php echo $inv['id']; ?>">
                                                        <button class="btn btn-outline-secondary" type="button" onclick="copyLink('inviteUrl-<?php echo $inv['id']; ?>')" title="Copy Link">
                                                            <i class="bi bi-clipboard"></i>
                                                        </button>
                                                        <a href="<?php echo $onboardUrl; ?>" class="btn btn-outline-primary" target="_blank" title="Open Link">
                                                            <i class="bi bi-box-arrow-up-right"></i>
                                                        </a>
                                                    </div>
                                                <?php else: ?>
                                                    <span class="text-muted small font-monospace">Used - Profile Onboarded</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-end pe-4">
                                                <a href="users?tab=invites&action=revoke_invite&invite_id=<?php echo $inv['id']; ?>" class="btn btn-sm btn-outline-danger" title="Revoke Invite" onclick="return confirm('Revoke invitation?');">
                                                    <i class="bi bi-x-circle-fill"></i> Revoke
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- Tab 5: Organizer Invitations -->
    <?php if ($activeTab === 'org_invites'): ?>
        <!-- Organizer Invite Sidebar -->
        <div class="col-12 col-lg-4">
            <div class="card border-0 shadow-sm sticky-lg-top" style="top: 24px;">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-send-fill me-2 text-primary"></i>Invite Organizer</h5>
                </div>
                <div class="card-body">
                    <p class="text-muted small">Invite event managers / organizers to join the platform. Organizers will have permission to manage events and timelines, but cannot edit other users.</p>
                    <form method="POST" action="users?tab=org_invites">
                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                        <div class="mb-4">
                            <label for="org_invite_email" class="form-label">Organizer Email Address <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="org_invite_email" name="org_invite_email" required placeholder="manager@domain.com">
                        </div>
                        <div class="d-grid">
                            <button type="submit" name="submit_org_invite" class="btn btn-primary py-2 fw-bold">
                                <i class="bi bi-envelope-plus-fill me-1"></i> Send Organizer Invite
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Organizer Invitations Table -->
        <div class="col-12 col-lg-8">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-list-task me-2 text-primary"></i>Organizer Onboarding Invitations</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                                <tr>
                                    <th class="ps-4">Email</th>
                                    <th>Status</th>
                                    <th>Sent Date</th>
                                    <th>Registration Link (Click to Copy/Test)</th>
                                    <th class="text-end pe-4">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($org_invitations)): ?>
                                    <tr>
                                        <td colspan="5" class="text-center py-5 text-muted">
                                            <i class="bi bi-envelope-exclamation fs-1 mb-2"></i>
                                            <p class="mb-0">No organizer invitations found.</p>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($org_invitations as $oi): ?>
                                        <?php 
                                            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
                                            $onboardUrl = $protocol . $_SERVER['HTTP_HOST'] . "/yt/onboard_organizer?token=" . $oi['token'];
                                        ?>
                                        <tr>
                                            <td class="ps-4">
                                                <strong class="text-dark"><?php echo htmlspecialchars($oi['email']); ?></strong>
                                            </td>
                                            <td>
                                                <span class="badge <?php echo $oi['status'] === 'accepted' ? 'bg-success' : 'bg-warning text-dark'; ?> px-2.5 py-1 text-uppercase font-monospace" style="font-size: 0.75rem;">
                                                    <?php echo strtoupper($oi['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="text-muted small"><?php echo date('Y-m-d H:i', strtotime($oi['created_at'])); ?></span>
                                            </td>
                                            <td>
                                                <?php if ($oi['status'] === 'pending'): ?>
                                                    <div class="input-group input-group-sm" style="max-width: 320px;">
                                                        <input type="text" class="form-control form-control-sm bg-light font-monospace small" readonly value="<?php echo htmlspecialchars($onboardUrl); ?>" id="inviteUrl-<?php echo $oi['id']; ?>">
                                                        <button class="btn btn-outline-secondary" type="button" onclick="copyLink('inviteUrl-<?php echo $oi['id']; ?>')" title="Copy Link">
                                                            <i class="bi bi-clipboard"></i>
                                                        </button>
                                                        <a href="<?php echo $onboardUrl; ?>" class="btn btn-outline-primary" target="_blank" title="Open Link">
                                                            <i class="bi bi-box-arrow-up-right"></i>
                                                        </a>
                                                    </div>
                                                <?php else: ?>
                                                    <span class="text-muted small font-monospace">Used - Profile Onboarded</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-end pe-4">
                                                <a href="users?tab=org_invites&action=revoke_org_invite&invite_id=<?php echo $oi['id']; ?>" class="btn btn-sm btn-outline-danger" title="Revoke Invite" onclick="return confirm('Revoke organizer invitation?');">
                                                    <i class="bi bi-x-circle-fill"></i> Revoke
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- Tab 6: Sponsor Invitations -->
    <?php if ($activeTab === 'sponsor_invites'): ?>
        <!-- Sponsor Invite Sidebar -->
        <div class="col-12 col-lg-4">
            <div class="card border-0 shadow-sm sticky-lg-top" style="top: 24px;">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-send-fill me-2 text-primary"></i>Invite Sponsor</h5>
                </div>
                <div class="card-body">
                    <p class="text-muted small">Invite companies to register as sponsors. Sponsors can populate their company details (logo, website, tier, and bio) and will be featured on events they sponsor.</p>
                    <form method="POST" action="users?tab=sponsor_invites">
                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                        <div class="mb-4">
                            <label for="sponsor_invite_email" class="form-label">Sponsor Email Address <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="sponsor_invite_email" name="sponsor_invite_email" required placeholder="sponsor@company.com">
                        </div>
                        <div class="d-grid">
                            <button type="submit" name="submit_sponsor_invite" class="btn btn-primary py-2 fw-bold">
                                <i class="bi bi-envelope-plus-fill me-1"></i> Send Sponsor Invite
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Sponsor Invitations Table -->
        <div class="col-12 col-lg-8">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-award-fill me-2 text-primary"></i>Sponsor Onboarding Invitations</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                                <tr>
                                    <th class="ps-4">Email</th>
                                    <th>Status</th>
                                    <th>Sent Date</th>
                                    <th>Registration Link (Click to Copy/Test)</th>
                                    <th class="text-end pe-4">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($sponsor_invitations)): ?>
                                    <tr>
                                        <td colspan="5" class="text-center py-5 text-muted">
                                            <i class="bi bi-envelope-exclamation fs-1 mb-2"></i>
                                            <p class="mb-0">No sponsor invitations found.</p>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($sponsor_invitations as $si): ?>
                                        <?php 
                                            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
                                            $onboardUrl = $protocol . $_SERVER['HTTP_HOST'] . "/yt/onboard_sponsor?token=" . $si['token'];
                                        ?>
                                        <tr>
                                            <td class="ps-4">
                                                <strong class="text-dark"><?php echo htmlspecialchars($si['email']); ?></strong>
                                            </td>
                                            <td>
                                                <span class="badge <?php echo $si['status'] === 'accepted' ? 'bg-success' : 'bg-warning text-dark'; ?> px-2.5 py-1 text-uppercase font-monospace" style="font-size: 0.75rem;">
                                                    <?php echo strtoupper($si['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="text-muted small"><?php echo date('Y-m-d H:i', strtotime($si['created_at'])); ?></span>
                                            </td>
                                            <td>
                                                <?php if ($si['status'] === 'pending'): ?>
                                                    <div class="input-group input-group-sm" style="max-width: 320px;">
                                                        <input type="text" class="form-control form-control-sm bg-light font-monospace small" readonly value="<?php echo htmlspecialchars($onboardUrl); ?>" id="inviteUrl-<?php echo $si['id']; ?>">
                                                        <button class="btn btn-outline-secondary" type="button" onclick="copyLink('inviteUrl-<?php echo $si['id']; ?>')" title="Copy Link">
                                                            <i class="bi bi-clipboard"></i>
                                                        </button>
                                                        <a href="<?php echo $onboardUrl; ?>" class="btn btn-outline-primary" target="_blank" title="Open Link">
                                                            <i class="bi bi-box-arrow-up-right"></i>
                                                        </a>
                                                    </div>
                                                <?php else: ?>
                                                    <span class="text-muted small font-monospace">Used - Profile Onboarded</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-end pe-4">
                                                <a href="users?tab=sponsor_invites&action=revoke_sponsor_invite&invite_id=<?php echo $si['id']; ?>" class="btn btn-sm btn-outline-danger" title="Revoke Invite" onclick="return confirm('Revoke sponsor invitation?');">
                                                    <i class="bi bi-x-circle-fill"></i> Revoke
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>



</div>

<script>
    function copyLink(elementId) {
        const copyText = document.getElementById(elementId);
        copyText.select();
        copyText.setSelectionRange(0, 99999);
        navigator.clipboard.writeText(copyText.value);
        alert("Registration link copied: " + copyText.value);
    }

    // Modal lifecycle cleanup
    document.addEventListener('DOMContentLoaded', function() {
        const userModalEl = document.getElementById('userModal');
        if (userModalEl) {
            userModalEl.addEventListener('hidden.bs.modal', function () {
                if (window.location.search.includes('edit_id=')) {
                    window.location.href = 'users?tab=users';
                }
            });
        }
    });
</script>

<!-- PHP Auto-Open Modal Trigger -->
<?php if ($editUser): ?>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const userModal = new bootstrap.Modal(document.getElementById('userModal'));
        userModal.show();
    });
</script>
<?php endif; ?>

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