<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/DatabaseHelper.php';
require_once __DIR__ . '/../src/Permissions/PermissionManager.php';
require_once __DIR__ . '/../src/Billing/PlanLimits.php';
require_once __DIR__ . '/../src/ActivityLog.php';

// Get company from session first (most reliable), then URL parameter
$company = null;
$workspaceParam = $_GET['workspace'] ?? null;
$pdo = getPDO();

// Priority 1: Use session company if available
if (isset($_SESSION['current_company_id'])) {
    $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
    $stmt->execute([$_SESSION['current_company_id']]);
    $company = $stmt->fetch();
}

// Priority 2: Use URL parameter if session company not found
if (!$company && $workspaceParam) {
    if (is_string($workspaceParam) && !is_numeric($workspaceParam)) {
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE username = ?");
        $stmt->execute([$workspaceParam]);
        $company = $stmt->fetch();
    } else {
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
        $stmt->execute([(int)$workspaceParam]);
        $company = $stmt->fetch();
    }
}

// Priority 3: Fallback to user's first company
if (!$company) {
    $user = AuthManager::getCurrentUser();
    $stmt = $pdo->prepare("SELECT c.* FROM companies c 
                          JOIN user_company_access uca ON c.id = uca.company_id 
                          WHERE uca.user_id = ? 
                          ORDER BY c.id LIMIT 1");
    $stmt->execute([$user['id']]);
    $company = $stmt->fetch();
}

if (!$company) {
    header('Location: /workspace-plans.php');
    exit;
}

$companyId = (int)$company['id'];
$user = AuthManager::getCurrentUser();
$userId = (int)$user['id'];

// Check if user is owner (only owners can manage members)
$isOwner = PermissionManager::isOwner($userId, $companyId);
$canManageMembers = $isOwner || PermissionManager::hasPermission($userId, $companyId, 'members_manage');
$canViewMembers = $isOwner || PermissionManager::hasPermission($userId, $companyId, 'members_view');

// Get plan limits for members
$planLimits = PlanLimits::getLimits($companyId);
$planUsage = PlanLimits::getUsage($companyId);
$canAddMoreMembers = PlanLimits::canAdd($companyId, 'users');
$remainingMembers = PlanLimits::getRemaining($companyId, 'users');
$memberLimit = $planLimits['users'] ?? 3;

$successMessage = '';
$errorMessage = '';
$showCreateUserModal = false;
$pendingEmail = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $canManageMembers) {
    $action = $_POST['action'] ?? '';

    if ($action === 'invite_member') {
        // Check plan limits first
        if (!$canAddMoreMembers) {
            $errorMessage = "You've reached your plan's member limit ({$memberLimit} members). Please upgrade your plan to add more team members.";
        } else {
            $identifier = trim($_POST['email_or_username'] ?? '');
            $roleId = !empty($_POST['role_id']) ? (int)$_POST['role_id'] : null;

            if (empty($identifier)) {
                $errorMessage = 'Please enter an email or username.';
            } else {
            // Check if user exists
            $existingUser = PermissionManager::findUserByEmailOrUsername($identifier);

            if ($existingUser) {
                // Check if already a member
                $stmt = $pdo->prepare("SELECT id FROM workspace_members WHERE company_id = ? AND user_id = ?");
                $stmt->execute([$companyId, $existingUser['id']]);
                if ($stmt->fetch()) {
                    $errorMessage = 'This user is already a member of this workspace.';
                } else {
                    // Invite the user
                    if (PermissionManager::inviteMember($companyId, (int)$existingUser['id'], $roleId, $userId)) {
                        $successMessage = 'Member invited successfully!';
                    } else {
                        $errorMessage = 'Failed to invite member. Please try again.';
                    }
                }
            } else {
                // User not found - show create user modal
                $showCreateUserModal = true;
                $pendingEmail = $identifier;
                $pendingRoleId = $roleId;
            }
            }
        }
    } elseif ($action === 'create_and_invite') {
        // Check plan limits first
        if (!$canAddMoreMembers) {
            $errorMessage = "You've reached your plan's member limit ({$memberLimit} members). Please upgrade your plan to add more team members.";
        } else {
            $name = trim($_POST['new_user_name'] ?? '');
            $email = trim($_POST['new_user_email'] ?? '');
            $password = $_POST['new_user_password'] ?? '';
            $roleId = !empty($_POST['role_id']) ? (int)$_POST['role_id'] : null;

            if (empty($name) || empty($email) || empty($password)) {
                $errorMessage = 'Please fill in all fields.';
            } elseif (strlen($password) < 6) {
                $errorMessage = 'Password must be at least 6 characters.';
        } else {
            // Check if email already exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $errorMessage = 'A user with this email already exists.';
            } else {
                // Create the user (with company_id for the workspace they're being invited to)
                $newUserId = PermissionManager::createUser($name, $email, $password, $companyId);
                if ($newUserId) {
                    // Invite them to the workspace
                    if (PermissionManager::inviteMember($companyId, $newUserId, $roleId, $userId)) {
                        // Log activity
                        ActivityLog::log(
                            $companyId,
                            $userId,
                            'member_invited',
                            'user',
                            $newUserId,
                            $name,
                            null,
                            ['role_id' => $roleId]
                        );
                        
                        $successMessage = "User created and invited successfully! Their login details are:\n\nEmail: {$email}\nPassword: {$password}";
                    } else {
                        $errorMessage = 'User created but failed to add to workspace.';
                    }
                } else {
                    $errorMessage = 'Failed to create user. Please try again.';
                }
            }
            }
        }
    } elseif ($action === 'update_role') {
        $memberId = (int)($_POST['member_user_id'] ?? 0);
        $roleId = !empty($_POST['role_id']) ? (int)$_POST['role_id'] : null;

        if ($memberId && !PermissionManager::isOwner($memberId, $companyId)) {
            // Get member name for logging
            $memberStmt = $pdo->prepare("SELECT name FROM users WHERE id = ?");
            $memberStmt->execute([$memberId]);
            $memberName = $memberStmt->fetchColumn();
            
            if (PermissionManager::updateMemberRole($companyId, $memberId, $roleId)) {
                // Log activity
                ActivityLog::log(
                    $companyId,
                    $userId,
                    'member_role_changed',
                    'user',
                    $memberId,
                    $memberName,
                    null,
                    ['role_id' => $roleId]
                );
                
                $successMessage = 'Member role updated successfully!';
            } else {
                $errorMessage = 'Failed to update member role.';
            }
        } else {
            $errorMessage = 'Cannot change owner role.';
        }
    } elseif ($action === 'remove_member') {
        $memberId = (int)($_POST['member_user_id'] ?? 0);

        if ($memberId && $memberId !== $userId) {
            // Get member name for logging
            $memberStmt = $pdo->prepare("SELECT name FROM users WHERE id = ?");
            $memberStmt->execute([$memberId]);
            $memberName = $memberStmt->fetchColumn();
            
            if (PermissionManager::removeMember($companyId, $memberId)) {
                // Log activity
                ActivityLog::log(
                    $companyId,
                    $userId,
                    'member_removed',
                    'user',
                    $memberId,
                    $memberName,
                    null,
                    null
                );
                
                $successMessage = 'Member removed successfully!';
            } else {
                $errorMessage = 'Failed to remove member. Owners cannot be removed.';
            }
        } else {
            $errorMessage = 'You cannot remove yourself.';
        }
    }
}

// Get workspace members and roles
$members = PermissionManager::getWorkspaceMembers($companyId);
$roles = PermissionManager::getWorkspaceRoles($companyId);

// If no roles exist, create defaults
if (empty($roles)) {
    PermissionManager::createDefaultRoles($companyId);
    $roles = PermissionManager::getWorkspaceRoles($companyId);
}

// Load all workspaces this user has access to for workspace switcher
$userCompanies = [];
try {
    $stmt = $pdo->prepare('SELECT c.* FROM companies c
                            JOIN user_company_access uca ON c.id = uca.company_id
                            WHERE uca.user_id = ?
                            ORDER BY c.name ASC');
    $stmt->execute([$userId]);
    $userCompanies = $stmt->fetchAll() ?: [];
} catch (Exception $e) {
    if ($company) {
        $userCompanies = [$company];
    }
}

// Build workspace query for links
$workspaceSlug = urlencode($company['username'] ?? (string) $companyId);
$workspaceQuery = '?workspace=' . $workspaceSlug;

$memberCount = count($members);

$currentTheme = $_GET['theme'] ?? ($_SESSION['theme_preference'] ?? 'dark');
$currentTheme = in_array($currentTheme, ['dark', 'light'], true) ? $currentTheme : 'dark';
$workspaceDisplayName = $company['name'] ?? 'Workspace';

?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= htmlspecialchars($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Team · <?= htmlspecialchars($workspaceDisplayName) ?></title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <script>
        (function() {
            var saved = localStorage.getItem('theme') || '<?= $currentTheme ?>';
            document.documentElement.setAttribute('data-theme', saved);
        })();
    </script>
</head>
<body class="members-page">
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Team', $currentTheme); ?>

<div class="main-container">
    <?php
    require_once __DIR__ . '/components/headers/page-header.php';

    $actions = [];
    if ($canManageMembers) {
        $actions[] = [
            'label' => 'Invite member',
            'type' => 'primary',
            'id' => 'invite-member-btn',
            'icon' => 'M12 4v16m8-8H4',
        ];
    }
    if ($isOwner) {
        $actions[] = [
            'label' => 'Roles',
            'url' => '/roles.php',
            'type' => 'secondary',
            'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z',
            'append_workspace' => true,
        ];
    }

    renderPageHeader(
        breadcrumbs: [
            ['label' => 'Home', 'url' => '/index.php', 'icon' => 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6'],
        ],
        currentPage: 'Team',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container">
        <div class="dash-section">
            <section class="card" style="margin-bottom: 0;">
                <div class="members-hero">
                    <div class="members-hero__top">
                        <div>
                            <p class="section-title">Team</p>
                            <h2 class="members-hero__title">Manage teammates for <?= htmlspecialchars($workspaceDisplayName) ?></h2>
                            <p class="members-hero__subtitle">Invite collaborators, adjust roles, and stay within your plan’s limits.</p>
                        </div>
                        <div class="members-hero__meta">
                            <span class="status-chip"><?= (int) $memberCount ?> member<?= $memberCount === 1 ? '' : 's' ?></span>
                            <span class="status-chip"><?php if ($memberLimit === -1): ?>Unlimited plan<?php else: ?><?= (int) $planUsage['users'] ?>/<?= (int) $memberLimit ?> seats<?php endif; ?></span>
                        </div>
                    </div>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <div class="members-tabs">
                <a class="members-tab" href="/settings.php<?= $workspaceQuery ?>">Workspace settings</a>
                <a class="members-tab is-active" href="/members.php<?= $workspaceQuery ?>">Team</a>
                <a class="members-tab" href="/activity.php<?= $workspaceQuery ?>">Activity log</a>
            </div>
        </div>

        <?php if ($successMessage): ?>
            <div class="dash-section">
                <div class="status-banner success">
                    <span style="white-space: pre-line;"><?= htmlspecialchars($successMessage) ?></span>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($errorMessage): ?>
            <div class="dash-section">
                <div class="status-banner error">
                    <span style="white-space: pre-line;"><?= htmlspecialchars($errorMessage) ?></span>
                </div>
            </div>
        <?php endif; ?>

        <?php if (!$canViewMembers): ?>
            <div class="dash-section">
                <section class="card" style="margin-bottom: 0; padding: 28px; text-align: center;">
                    <p class="section-title">Access</p>
                    <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 4px 0;">Members not available</h2>
                    <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">You don’t have permission to view workspace members.</p>
                </section>
            </div>
        <?php else: ?>
            <?php if ($canManageMembers): ?>
                <div class="dash-section">
                    <section class="card" style="margin-bottom: 0;">
                        <div class="members-limit">
                            <div class="members-limit__copy">
                                <p class="section-title">Member limit</p>
                                <p class="members-limit__desc">
                                    <?php if ($memberLimit === -1): ?>
                                        Unlimited members on your plan.
                                    <?php else: ?>
                                        <?= (int) $planUsage['users'] ?> of <?= (int) $memberLimit ?> members used<?= !$canAddMoreMembers ? ' — Limit reached' : '' ?>
                                    <?php endif; ?>
                                </p>
                            </div>
                            <?php if ($memberLimit !== -1): ?>
                                <div class="members-limit__progress">
                                    <div class="members-progress-track">
                                        <div class="members-progress-fill" style="width: <?= min(100, ($planUsage['users'] / max(1, $memberLimit)) * 100) ?>%"></div>
                                    </div>
                                    <?php if (!$canAddMoreMembers): ?>
                                        <a href="/billing.php<?= $workspaceQuery ?>" class="members-upgrade-link">Upgrade</a>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </section>
                </div>
            <?php endif; ?>

            <div class="dash-section">
                <section class="card" style="margin-bottom: 0;">
                    <div class="members-card-header">
                        <div>
                            <p class="section-title">Workspace members</p>
                            <p class="members-card-subtitle"><?= (int) $memberCount ?> member<?= $memberCount === 1 ? '' : 's' ?></p>
                        </div>
                        <?php if ($canManageMembers): ?>
                            <button type="button" class="btn-secondary" data-open-invite>Invite</button>
                        <?php endif; ?>
                    </div>

                    <?php if (empty($members)): ?>
                        <div class="members-empty">
                            <p>No members yet. Invite someone to get started.</p>
                        </div>
                    <?php else: ?>
                        <div class="members-list">
                            <?php foreach ($members as $member): ?>
                                <div class="members-row">
                                    <div class="members-user">
                                        <div class="members-avatar">
                                            <span><?= strtoupper(substr($member['user_name'] ?? 'U', 0, 2)) ?></span>
                                        </div>
                                        <div class="members-user__meta">
                                            <p class="members-user__name"><?= htmlspecialchars($member['user_name'] ?? 'Unknown') ?></p>
                                            <p class="members-user__email"><?= htmlspecialchars($member['user_email'] ?? '') ?></p>
                                        </div>
                                    </div>
                                    <div class="members-actions">
                                        <?php if ((int) $member['is_owner'] === 1): ?>
                                            <span class="members-owner-pill">Owner</span>
                                        <?php else: ?>
                                            <?php if ($canManageMembers): ?>
                                                <form method="POST" class="members-role-form">
                                                    <input type="hidden" name="action" value="update_role">
                                                    <input type="hidden" name="member_user_id" value="<?= $member['user_id'] ?>">
                                                    <select name="role_id" onchange="this.form.submit()" class="members-role-select">
                                                        <option value="">No role</option>
                                                        <?php foreach ($roles as $role): ?>
                                                            <option value="<?= $role['id'] ?>" <?= (int) $member['role_id'] === (int) $role['id'] ? 'selected' : '' ?>>
                                                                <?= htmlspecialchars($role['name']) ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </form>
                                                <form method="POST" onsubmit="return confirm('Remove this member from the workspace?')">
                                                    <input type="hidden" name="action" value="remove_member">
                                                    <input type="hidden" name="member_user_id" value="<?= $member['user_id'] ?>">
                                                    <button type="submit" class="members-remove-btn" title="Remove member">Remove</button>
                                                </form>
                                            <?php else: ?>
                                                <span class="status-chip"><?= htmlspecialchars($member['role_name'] ?? 'No role') ?></span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </section>
            </div>

            <div class="dash-section">
                <section class="card" style="margin-bottom: 0;">
                    <div class="members-card-header">
                        <div>
                            <p class="section-title">Roles</p>
                            <p class="members-card-subtitle">Define what each role can access.</p>
                        </div>
                        <?php if ($isOwner): ?>
                            <a href="/roles.php<?= $workspaceQuery ?>" class="btn-secondary">Manage roles</a>
                        <?php endif; ?>
                    </div>

                    <?php if (empty($roles)): ?>
                        <div class="members-empty"><p>No roles yet.</p></div>
                    <?php else: ?>
                        <div class="members-roles">
                            <?php foreach ($roles as $role): ?>
                                <div class="members-role-row">
                                    <div>
                                        <p class="members-role-name"><?= htmlspecialchars($role['name']) ?></p>
                                        <p class="members-role-desc"><?= htmlspecialchars($role['description'] ?? 'No description provided') ?></p>
                                    </div>
                                    <div class="members-role-meta">
                                        <span><?= (int) $role['member_count'] ?> member<?= (int) $role['member_count'] === 1 ? '' : 's' ?></span>
                                        <span class="members-dot"></span>
                                        <span><?= count(PermissionManager::getRolePermissions((int) $role['id'])) ?> permissions</span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </section>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Invite Member Modal -->
<div id="inviteModal" class="members-modal-overlay <?= $showCreateUserModal ? '' : 'is-hidden' ?>">
    <div class="members-modal" role="dialog" aria-modal="true" aria-labelledby="members-modal-title">
        <?php if ($showCreateUserModal): ?>
            <div class="members-modal-header">
                <h3 id="members-modal-title" class="members-modal-title">User not found</h3>
                <p class="members-modal-subtitle">Create a new user account and invite them.</p>
            </div>
            <form method="POST" class="members-modal-body">
                <input type="hidden" name="action" value="create_and_invite">
                <input type="hidden" name="role_id" value="<?= $pendingRoleId ?? '' ?>">

                <div>
                    <label class="form-label" for="new_user_name">Full name</label>
                    <input id="new_user_name" class="input" type="text" name="new_user_name" required>
                </div>
                <div>
                    <label class="form-label" for="new_user_email">Email</label>
                    <input id="new_user_email" class="input" type="email" name="new_user_email" value="<?= htmlspecialchars($pendingEmail) ?>" required>
                </div>
                <div>
                    <label class="form-label" for="new_user_password">Password</label>
                    <input id="new_user_password" class="input" type="text" name="new_user_password" required minlength="6" placeholder="Create a password for them">
                    <p class="form-hint">You'll need to share these credentials with the user.</p>
                </div>
                <div>
                    <label class="form-label" for="new_user_role">Role</label>
                    <select id="new_user_role" name="role_id" class="members-role-select">
                        <option value="">Select a role</option>
                        <?php foreach ($roles as $role): ?>
                            <option value="<?= $role['id'] ?>" <?= ($pendingRoleId ?? '') == $role['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($role['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="members-modal-actions">
                    <button type="button" class="btn-secondary" data-close-invite>Cancel</button>
                    <button type="submit" class="btn-primary">Create & invite</button>
                </div>
            </form>
        <?php else: ?>
            <div class="members-modal-header">
                <h3 id="members-modal-title" class="members-modal-title">Invite member</h3>
                <p class="members-modal-subtitle">Add someone to your workspace.</p>
            </div>
            <form method="POST" class="members-modal-body">
                <input type="hidden" name="action" value="invite_member">
                <div>
                    <label class="form-label" for="email_or_username">Email or username</label>
                    <input id="email_or_username" class="input" type="text" name="email_or_username" required placeholder="Enter email or username">
                </div>
                <div>
                    <label class="form-label" for="invite_role">Role</label>
                    <select id="invite_role" name="role_id" class="members-role-select">
                        <option value="">Select a role</option>
                        <?php foreach ($roles as $role): ?>
                            <option value="<?= $role['id'] ?>"><?= htmlspecialchars($role['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="members-modal-actions">
                    <button type="button" class="btn-secondary" data-close-invite>Cancel</button>
                    <button type="submit" class="btn-primary">Invite</button>
                </div>
            </form>
        <?php endif; ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var inviteModal = document.getElementById('inviteModal');
    var inviteBtn = document.getElementById('invite-member-btn');
    var openInlineBtn = document.querySelector('[data-open-invite]');

    function openInvite() {
        if (inviteModal) {
            inviteModal.classList.remove('is-hidden');
        }
    }

    function closeInvite() {
        if (inviteModal) {
            inviteModal.classList.add('is-hidden');
        }
    }

    if (inviteBtn) {
        inviteBtn.addEventListener('click', openInvite);
    }

    if (openInlineBtn) {
        openInlineBtn.addEventListener('click', openInvite);
    }

    document.querySelectorAll('[data-close-invite]').forEach(function (btn) {
        btn.addEventListener('click', closeInvite);
    });

    if (inviteModal) {
        inviteModal.addEventListener('click', function (e) {
            if (e.target === inviteModal) {
                closeInvite();
            }
        });
    }

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') {
            closeInvite();
        }
    });
});
</script>

</body>
</html>
