<?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/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'];

// Only owners can manage roles
$isOwner = PermissionManager::isOwner($userId, $companyId);

if (!$isOwner) {
    header('Location: /members.php?workspace=' . urlencode($company['username'] ?? $companyId));
    exit;
}

$successMessage = '';
$errorMessage = '';
$editingRole = null;

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

    if ($action === 'create_role') {
        $name = trim($_POST['role_name'] ?? '');
        $description = trim($_POST['role_description'] ?? '');
        $permissions = $_POST['permissions'] ?? [];

        if (empty($name)) {
            $errorMessage = 'Role name is required.';
        } else {
            try {
                // Check if role name already exists
                $stmt = $pdo->prepare("SELECT id FROM workspace_roles WHERE company_id = ? AND name = ?");
                $stmt->execute([$companyId, $name]);
                if ($stmt->fetch()) {
                    $errorMessage = 'A role with this name already exists.';
                } else {
                    // Create the role
                    $stmt = $pdo->prepare("INSERT INTO workspace_roles (company_id, name, description) VALUES (?, ?, ?)");
                    $stmt->execute([$companyId, $name, $description]);
                    $roleId = (int)$pdo->lastInsertId();

                    // Add permissions
                    foreach ($permissions as $permission) {
                        if (array_key_exists($permission, PermissionManager::PERMISSIONS) && !in_array($permission, PermissionManager::OWNER_ONLY)) {
                            $stmt = $pdo->prepare("INSERT INTO role_permissions (role_id, permission_key, allowed) VALUES (?, ?, 1)");
                            $stmt->execute([$roleId, $permission]);
                        }
                    }

                    // Log role creation
                    try {
                        ActivityLog::log(
                            (int) $companyId,
                            $userId,
                            'role_created',
                            'role',
                            (int) $roleId,
                            $name,
                            null,
                            ['permissions' => array_values($permissions)]
                        );
                    } catch (Throwable $e) {
                        // Ignore logging failures
                    }

                    $successMessage = 'Role created successfully!';
                }
            } catch (Exception $e) {
                $errorMessage = 'Failed to create role: ' . $e->getMessage();
            }
        }
    } elseif ($action === 'update_role') {
        $roleId = (int)($_POST['role_id'] ?? 0);
        $name = trim($_POST['role_name'] ?? '');
        $description = trim($_POST['role_description'] ?? '');
        $permissions = $_POST['permissions'] ?? [];

        if (empty($name) || !$roleId) {
            $errorMessage = 'Role name is required.';
        } else {
            try {
                // Check if role name already exists (excluding current role)
                $stmt = $pdo->prepare("SELECT id FROM workspace_roles WHERE company_id = ? AND name = ? AND id != ?");
                $stmt->execute([$companyId, $name, $roleId]);
                if ($stmt->fetch()) {
                    $errorMessage = 'A role with this name already exists.';
                } else {
                    // Update the role
                    $stmt = $pdo->prepare("UPDATE workspace_roles SET name = ?, description = ? WHERE id = ? AND company_id = ?");
                    $stmt->execute([$name, $description, $roleId, $companyId]);

                    // Clear existing permissions
                    $stmt = $pdo->prepare("DELETE FROM role_permissions WHERE role_id = ?");
                    $stmt->execute([$roleId]);

                    // Add new permissions
                    foreach ($permissions as $permission) {
                        if (array_key_exists($permission, PermissionManager::PERMISSIONS) && !in_array($permission, PermissionManager::OWNER_ONLY)) {
                            $stmt = $pdo->prepare("INSERT INTO role_permissions (role_id, permission_key, allowed) VALUES (?, ?, 1)");
                            $stmt->execute([$roleId, $permission]);
                        }
                    }

                    // Log role update
                    try {
                        ActivityLog::log(
                            (int) $companyId,
                            $userId,
                            'role_updated',
                            'role',
                            (int) $roleId,
                            $name,
                            null,
                            ['permissions' => array_values($permissions)]
                        );
                    } catch (Throwable $e) {
                        // Ignore logging failures
                    }

                    PermissionManager::clearCache();
                    $successMessage = 'Role updated successfully!';
                }
            } catch (Exception $e) {
                $errorMessage = 'Failed to update role: ' . $e->getMessage();
            }
        }
    } elseif ($action === 'delete_role') {
        $roleId = (int)($_POST['role_id'] ?? 0);

        if ($roleId) {
            try {
                // Check if any members have this role
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM workspace_members WHERE role_id = ?");
                $stmt->execute([$roleId]);
                $memberCount = (int)$stmt->fetchColumn();

                if ($memberCount > 0) {
                    $errorMessage = "Cannot delete role: {$memberCount} member(s) are using it. Reassign them first.";
                } else {
                    // Fetch role name before deletion for logging
                    $roleStmt = $pdo->prepare("SELECT name FROM workspace_roles WHERE id = ? AND company_id = ?");
                    $roleStmt->execute([$roleId, $companyId]);
                    $roleName = $roleStmt->fetchColumn();

                    // Delete permissions first
                    $stmt = $pdo->prepare("DELETE FROM role_permissions WHERE role_id = ?");
                    $stmt->execute([$roleId]);

                    // Delete the role
                    $stmt = $pdo->prepare("DELETE FROM workspace_roles WHERE id = ? AND company_id = ?");
                    $stmt->execute([$roleId, $companyId]);

                    // Log role deletion
                    try {
                        ActivityLog::log(
                            (int) $companyId,
                            $userId,
                            'role_deleted',
                            'role',
                            (int) $roleId,
                            $roleName ?: null,
                            null,
                            null
                        );
                    } catch (Throwable $e) {
                        // Ignore logging failures
                    }

                    $successMessage = 'Role deleted successfully!';
                }
            } catch (Exception $e) {
                $errorMessage = 'Failed to delete role: ' . $e->getMessage();
            }
        }
    }
}

// Check if editing a role
$editRoleId = (int)($_GET['edit'] ?? 0);
if ($editRoleId) {
    $stmt = $pdo->prepare("SELECT * FROM workspace_roles WHERE id = ? AND company_id = ?");
    $stmt->execute([$editRoleId, $companyId]);
    $editingRole = $stmt->fetch();
    if ($editingRole) {
        $editingRole['permissions'] = PermissionManager::getRolePermissions($editRoleId);
    }
}

// Get all roles
$roles = PermissionManager::getWorkspaceRoles($companyId);

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

// Group permissions by category
$permissionGroups = [
    'Dashboard' => ['dashboard_view'],
    'Clients' => ['clients_view', 'clients_create', 'clients_edit', 'clients_delete'],
    'Proposals' => ['proposals_view', 'proposals_create', 'proposals_edit', 'proposals_delete'],
    'Contracts' => ['contracts_view', 'contracts_create', 'contracts_edit', 'contracts_delete'],
    'Invoices' => ['invoices_view', 'invoices_create', 'invoices_edit', 'invoices_delete'],
    'Templates' => ['templates_view', 'templates_create', 'templates_edit', 'templates_delete', 'templates_manage'],
    'Team' => ['members_view', 'members_manage', 'roles_manage'],
];

// Use permission groups from PermissionManager if available
if (defined('PermissionManager::PERMISSION_GROUPS')) {
    $permissionGroups = PermissionManager::PERMISSION_GROUPS;
}

// Load user workspaces for 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;

$roleCount = count($roles);

$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>Manage Roles · <?= 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="roles-page">
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Roles', $currentTheme); ?>

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

	$actions = [
		[
			'label' => 'Team',
			'url' => '/members.php',
			'type' => 'secondary',
			'icon' => 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z',
			'append_workspace' => true,
		],
		[
			'label' => 'Create role',
			'type' => 'primary',
			'id' => 'create-role-btn',
			'icon' => 'M12 4v16m8-8H4',
		],
	];

	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: 'Roles',
		actions: $actions,
		workspaceQuery: $workspaceQuery
	);
	?>

	<div class="dash-container">
		<div class="dash-section">
			<section class="card" style="margin-bottom: 0;">
				<div class="roles-hero">
					<div class="roles-hero__top">
						<div>
							<p class="section-title">Roles</p>
							<h2 class="roles-hero__title">Define access for <?= htmlspecialchars($workspaceDisplayName) ?></h2>
							<p class="roles-hero__subtitle">Create reusable permission sets for teams and keep control centralized.</p>
						</div>
						<div class="roles-hero__meta">
							<span class="status-chip"><?= (int) $roleCount ?> role<?= $roleCount === 1 ? '' : 's' ?></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" href="/members.php<?= $workspaceQuery ?>">Team</a>
				<a class="members-tab is-active" href="/roles.php<?= $workspaceQuery ?>">Roles</a>
			</div>
		</div>

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

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

		<div class="dash-section">
			<section class="card" style="margin-bottom: 0;">
				<div class="roles-card-header">
					<div>
						<p class="section-title">Workspace roles</p>
						<p class="roles-card-subtitle">Assign roles to members to control access.</p>
					</div>
					<button type="button" class="btn-secondary" data-open-create-role>Create</button>
				</div>

				<div class="roles-grid">
					<?php foreach ($roles as $role): ?>
						<?php $rolePermissions = PermissionManager::getRolePermissions((int) $role['id']); ?>
						<div class="roles-role-card">
							<div class="roles-role-card__header">
								<div>
									<p class="roles-role-card__name"><?= htmlspecialchars($role['name']) ?></p>
									<p class="roles-role-card__desc"><?= htmlspecialchars($role['description'] ?? 'No description') ?></p>
								</div>
								<span class="status-chip"><?= (int) $role['member_count'] ?> member<?= (int) $role['member_count'] === 1 ? '' : 's' ?></span>
							</div>

							<div class="roles-role-card__body">
								<p class="roles-role-card__label">Permissions</p>
								<div class="roles-perms">
									<?php
									$displayPermissions = array_slice($rolePermissions, 0, 6);
									foreach ($displayPermissions as $perm):
									?>
										<span class="roles-perm-chip"><?= htmlspecialchars(PermissionManager::PERMISSIONS[$perm] ?? $perm) ?></span>
									<?php endforeach; ?>
									<?php if (count($rolePermissions) > 6): ?>
										<span class="roles-perm-chip muted">+<?= count($rolePermissions) - 6 ?> more</span>
									<?php endif; ?>
									<?php if (empty($rolePermissions)): ?>
										<span class="roles-perm-empty">No permissions</span>
									<?php endif; ?>
								</div>
							</div>

							<div class="roles-role-card__footer">
								<a class="btn-secondary btn-sm" href="/roles.php<?= $workspaceQuery ?>&edit=<?= $role['id'] ?>">Edit</a>
								<form method="POST" onsubmit="return confirm('Delete this role?')">
									<input type="hidden" name="action" value="delete_role">
									<input type="hidden" name="role_id" value="<?= $role['id'] ?>">
									<button type="submit" class="btn-danger btn-sm">Delete</button>
								</form>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
			</section>
		</div>

		<div class="dash-section">
			<section class="card roles-note" style="margin-bottom: 0;">
				<p><strong>Note:</strong> Billing and workspace settings remain owner-only and cannot be delegated via roles.</p>
			</section>
		</div>
	</div>
</div>

<div id="createRoleModal" class="roles-modal-overlay is-hidden">
	<div class="roles-modal" role="dialog" aria-modal="true" aria-labelledby="roles-create-title">
		<div class="roles-modal-header">
			<h3 id="roles-create-title" class="roles-modal-title">Create new role</h3>
			<p class="roles-modal-subtitle">Add a reusable set of permissions for your workspace.</p>
		</div>
		<form method="POST" class="roles-modal-body">
			<input type="hidden" name="action" value="create_role">
			<div>
				<label class="form-label" for="role_name">Role name</label>
				<input id="role_name" type="text" name="role_name" required class="input" placeholder="e.g., Sales Manager">
			</div>
			<div>
				<label class="form-label" for="role_description">Description</label>
				<input id="role_description" type="text" name="role_description" class="input" placeholder="What can this role do?">
			</div>
			<div>
				<label class="form-label">Permissions</label>
				<div class="roles-permission-groups">
					<?php foreach ($permissionGroups as $groupName => $groupPermissions): ?>
						<div class="roles-permission-group">
							<p class="roles-permission-group__title"><?= htmlspecialchars((string) $groupName) ?></p>
							<div class="roles-permission-grid">
								<?php foreach ($groupPermissions as $perm): ?>
									<?php if (!in_array($perm, PermissionManager::OWNER_ONLY)): ?>
										<label class="roles-permission-item">
											<input type="checkbox" name="permissions[]" value="<?= $perm ?>">
											<span><?= htmlspecialchars(PermissionManager::PERMISSIONS[$perm] ?? $perm) ?></span>
										</label>
									<?php endif; ?>
								<?php endforeach; ?>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
			</div>
			<div class="roles-modal-actions">
				<button type="button" class="btn-secondary" data-close-create-role>Cancel</button>
				<button type="submit" class="btn-primary">Create role</button>
			</div>
		</form>
	</div>
</div>

<?php if ($editingRole): ?>
<div id="editRoleDrawer" class="roles-drawer">
	<div class="roles-drawer__overlay" data-close-edit-drawer></div>
	<div class="roles-drawer__panel" role="dialog" aria-modal="true" aria-labelledby="roles-edit-title">
		<div class="roles-drawer__header">
			<div>
				<p class="section-title">Edit role</p>
				<h3 id="roles-edit-title" class="roles-drawer__title"><?= htmlspecialchars($editingRole['name']) ?></h3>
			</div>
			<a class="btn-secondary btn-sm" href="/roles.php<?= $workspaceQuery ?>">Close</a>
		</div>
		<form method="POST" class="roles-drawer__body">
			<input type="hidden" name="action" value="update_role">
			<input type="hidden" name="role_id" value="<?= $editingRole['id'] ?>">
			<div class="roles-drawer__section">
				<div>
					<label class="form-label" for="edit_role_name">Role name</label>
					<input id="edit_role_name" type="text" name="role_name" required value="<?= htmlspecialchars($editingRole['name']) ?>" class="input">
				</div>
				<div>
					<label class="form-label" for="edit_role_description">Description</label>
					<textarea id="edit_role_description" name="role_description" rows="2" class="input" placeholder="Optional summary"><?= htmlspecialchars($editingRole['description'] ?? '') ?></textarea>
				</div>
			</div>
			<div class="roles-drawer__section">
				<div class="roles-drawer__section-header">
					<div>
						<p class="roles-drawer__section-title">Permissions</p>
						<p class="roles-drawer__section-subtitle">Enable what this role can touch.</p>
					</div>
					<a href="/roles.php<?= $workspaceQuery ?>" class="btn-secondary btn-sm">Reset</a>
				</div>
				<div class="roles-permission-groups">
					<?php foreach ($permissionGroups as $groupName => $groupPermissions): ?>
						<div class="roles-permission-group">
							<p class="roles-permission-group__title"><?= htmlspecialchars((string) $groupName) ?></p>
							<div class="roles-permission-grid">
								<?php foreach ($groupPermissions as $perm): ?>
									<?php if (!in_array($perm, PermissionManager::OWNER_ONLY)): ?>
										<label class="roles-permission-item">
											<input type="checkbox" name="permissions[]" value="<?= $perm ?>" <?= in_array($perm, $editingRole['permissions']) ? 'checked' : '' ?>>
											<span><?= htmlspecialchars(PermissionManager::PERMISSIONS[$perm] ?? $perm) ?></span>
										</label>
									<?php endif; ?>
								<?php endforeach; ?>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
			</div>
			<div class="roles-drawer__footer">
				<a href="/roles.php<?= $workspaceQuery ?>" class="btn-secondary">Cancel</a>
				<button type="submit" class="btn-primary">Save changes</button>
			</div>
		</form>
	</div>
</div>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function () {
	var createModal = document.getElementById('createRoleModal');
	var createBtn = document.getElementById('create-role-btn');
	var openInlineBtn = document.querySelector('[data-open-create-role]');

	function openCreate() {
		if (createModal) {
			createModal.classList.remove('is-hidden');
		}
	}

	function closeCreate() {
		if (createModal) {
			createModal.classList.add('is-hidden');
		}
	}

	if (createBtn) {
		createBtn.addEventListener('click', openCreate);
	}

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

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

	if (createModal) {
		createModal.addEventListener('click', function (e) {
			if (e.target === createModal) {
				closeCreate();
			}
		});
	}

	var editOverlay = document.querySelector('[data-close-edit-drawer]');
	if (editOverlay) {
		editOverlay.addEventListener('click', function () {
			window.location.href = '/roles.php<?= $workspaceQuery ?>';
		});
	}

	document.addEventListener('keydown', function (e) {
		if (e.key === 'Escape') {
			if (createModal && !createModal.classList.contains('is-hidden')) {
				closeCreate();
				return;
			}
			if (document.getElementById('editRoleDrawer')) {
				window.location.href = '/roles.php<?= $workspaceQuery ?>';
			}
		}
	});
});
</script>

</body>
</html>
