<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/ActivityLog.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/navigation.php';

AuthManager::requireAuth();

$user = AuthManager::getCurrentUser();
$company = $company ?? null;

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

$companyId = (int)$company['id'];
$userId = (int)$user['id'];
$canViewActivity = hasPermission('activity_view');

// Load all workspaces this user has access to for workspace switcher
$userCompanies = [];
try {
    $pdo = getPDO();
    $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) {
    // Fallback to current company only
    if ($company) {
        $userCompanies = [$company];
    }
}

// Get filters and pagination
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = (int)($_GET['per_page'] ?? 50);
if (!in_array($perPage, [25, 50, 100, 200], true)) {
    $perPage = 50;
}
$filters = [];

if (!empty($_GET['user_id'])) {
    $filters['user_id'] = (int)$_GET['user_id'];
}
if (!empty($_GET['action'])) {
    $filters['action'] = $_GET['action'];
}
if (!empty($_GET['entity_type'])) {
    $filters['entity_type'] = $_GET['entity_type'];
}
if (!empty($_GET['date_from'])) {
    $filters['date_from'] = $_GET['date_from'];
}
if (!empty($_GET['date_to'])) {
    $filters['date_to'] = $_GET['date_to'];
}

// Handle CSV export (Excel-compatible)
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $exportResult = ActivityLog::getForWorkspace($companyId, 1, 100000, $filters);
    $exportActivities = $exportResult['activities'];

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="activity_log_' . date('Y-m-d') . '.csv"');

    $out = fopen('php://output', 'w');
    // CSV header
    fputcsv($out, ['Timestamp', 'User', 'Action', 'Entity Type', 'Entity Name', 'IP Address']);

    // Entity type labels map for export
    $entityTypeLabels = [
        'proposal_module' => 'Proposal Module',
        'template' => 'Proposal Template',
        'contract_template' => 'Contract Template',
    ];

    foreach ($exportActivities as $activity) {
        $rawType = $activity['entity_type'] ?? '';
        if ($rawType) {
            $label = $entityTypeLabels[$rawType] ?? ucwords(str_replace('_', ' ', $rawType));
        } else {
            $label = '';
        }

        fputcsv($out, [
            $activity['created_at'],
            $activity['user_name'] ?? 'System',
            $activity['action_label'] ?? $activity['action'],
            $label,
            $activity['entity_name'] ?? '',
            $activity['ip_address'] ?? '',
        ]);
    }

    fclose($out);
    exit;
}

$result = ActivityLog::getForWorkspace($companyId, $page, $perPage, $filters);
$activities = $result['activities'];
$totalPages = $result['total_pages'];
$total = $result['total'];

// Get filter options
$actionTypes = ActivityLog::getActionTypes($companyId);
$entityTypes = ActivityLog::getEntityTypes($companyId);

// Human-readable labels for entity types
$entityTypeLabels = [
    'proposal_module' => 'Proposal Module',
    'template' => 'Proposal Template',
    'contract_template' => 'Contract Template',
];

// Get workspace members for filter
$pdo = getPDO();
$stmt = $pdo->prepare('
    SELECT u.id, u.name FROM users u
    JOIN user_company_access uca ON u.id = uca.user_id
    WHERE uca.company_id = ?
    ORDER BY u.name
');
$stmt->execute([$companyId]);
$members = $stmt->fetchAll();

$workspaceQuery = isset($company['username']) ? '?workspace=' . urlencode($company['username']) : '';

$currentTheme = $_GET['theme'] ?? ($_SESSION['theme_preference'] ?? 'dark');
$currentTheme = in_array($currentTheme, ['dark', 'light'], true) ? $currentTheme : 'dark';
?>
<!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>Activity Log · <?= htmlspecialchars($company['name'] ?? 'Keelance') ?></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="activity-page">
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Activity log', $currentTheme); ?>

<div class="main-container">
	<?php
	$workspaceSlug = isset($company['username']) ? urlencode($company['username']) : (string) $companyId;
	$workspaceQuery = '?workspace=' . $workspaceSlug;

	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' => 'Settings',
			'url' => '/settings.php',
			'type' => 'primary',
			'icon' => 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z',
			'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: 'Activity log',
		actions: $actions,
		workspaceQuery: $workspaceQuery
	);
	?>

	<div class="dash-container">
		<div class="dash-section">
			<section class="card" style="margin-bottom: 0;">
				<div class="activity-hero">
					<div class="activity-hero__top">
						<div>
							<p class="section-title">Activity</p>
							<h2 class="activity-hero__title">See everything happening in real time</h2>
							<p class="activity-hero__subtitle">Audit changes, exports, and key workspace actions across <strong><?= htmlspecialchars($company['name'] ?? 'your workspace') ?></strong>.</p>
						</div>
						<div class="activity-hero__meta">
							<span class="status-chip"><?= number_format($total) ?> entries</span>
							<span class="status-chip"><?= max(1, $totalPages) ?> page<?= $totalPages === 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="/activity.php<?= $workspaceQuery ?>">Activity log</a>
			</div>
		</div>

		<?php if (!$canViewActivity): ?>
			<div class="dash-section">
				<section class="card activity-locked" style="margin-bottom: 0;">
					<p class="section-title">Access</p>
					<h3 class="activity-locked__title">Activity log not available</h3>
					<p class="activity-locked__subtitle">You are a member of <strong><?= htmlspecialchars($company['name'] ?? 'this workspace') ?></strong>, but your role does not include access to the activity log.</p>
					<p class="activity-locked__hint">Ask the workspace owner to grant you access via <strong>Manage roles</strong> on the Team page.</p>
				</section>
			</div>
		<?php else: ?>
			<div class="dash-section">
				<section class="card" style="margin-bottom: 0;">
					<div class="activity-filters-header">
						<p class="section-title">Filters</p>
						<p class="activity-filters-subtitle">Narrow down by member, action, entity type, or date range.</p>
					</div>
					<form method="GET" class="activity-filters-grid">
						<input type="hidden" name="workspace" value="<?= htmlspecialchars($company['username'] ?? '') ?>">
						<div>
							<label class="form-label" for="activity-user">Member</label>
							<select id="activity-user" name="user_id" class="input">
								<option value="">All members</option>
								<?php foreach ($members as $member): ?>
									<option value="<?= $member['id'] ?>" <?= ($filters['user_id'] ?? '') == $member['id'] ? 'selected' : '' ?>>
										<?= htmlspecialchars($member['name']) ?>
									</option>
								<?php endforeach; ?>
							</select>
						</div>
						<div>
							<label class="form-label" for="activity-action">Action</label>
							<select id="activity-action" name="action" class="input">
								<option value="">All actions</option>
								<?php foreach ($actionTypes as $key => $label): ?>
									<option value="<?= $key ?>" <?= ($filters['action'] ?? '') === $key ? 'selected' : '' ?>>
										<?= htmlspecialchars($label) ?>
									</option>
								<?php endforeach; ?>
							</select>
						</div>
						<div>
							<label class="form-label" for="activity-entity">Entity type</label>
							<select id="activity-entity" name="entity_type" class="input">
								<option value="">All types</option>
								<?php foreach ($entityTypes as $type): ?>
									<option value="<?= $type ?>" <?= ($filters['entity_type'] ?? '') === $type ? 'selected' : '' ?>>
										<?= htmlspecialchars($entityTypeLabels[$type] ?? ucfirst($type)) ?>
									</option>
								<?php endforeach; ?>
							</select>
						</div>
						<div>
							<label class="form-label" for="activity-from">From</label>
							<input id="activity-from" type="date" name="date_from" value="<?= $filters['date_from'] ?? '' ?>" class="input">
						</div>
						<div>
							<label class="form-label" for="activity-to">To</label>
							<input id="activity-to" type="date" name="date_to" value="<?= $filters['date_to'] ?? '' ?>" class="input">
						</div>
						<div class="activity-filters-actions">
							<button type="submit" class="btn-primary">Filter</button>
							<?php if (!empty($filters)): ?>
								<a href="/activity.php?workspace=<?= htmlspecialchars($company['username'] ?? '') ?>" class="btn-secondary">Clear</a>
							<?php endif; ?>
						</div>
					</form>
				</section>
			</div>

			<div class="dash-section">
				<section class="card" style="margin-bottom: 0;">
					<div class="activity-list-header">
						<div>
							<p class="section-title">Recent activity</p>
							<p class="activity-list-subtitle"><?= number_format($total) ?> total activities</p>
						</div>
						<div class="activity-list-actions">
							<form method="GET" class="activity-perpage">
								<?php foreach ($_GET as $key => $value): ?>
									<?php if (!in_array($key, ['per_page', 'page', 'export'], true)): ?>
										<input type="hidden" name="<?= htmlspecialchars($key) ?>" value="<?= htmlspecialchars((string) $value) ?>">
									<?php endif; ?>
								<?php endforeach; ?>
								<label class="form-label" for="activity-per-page">Show</label>
								<select id="activity-per-page" name="per_page" onchange="this.form.submit()" class="input">
									<?php foreach ([25, 50, 100, 200] as $option): ?>
										<option value="<?= $option ?>" <?= $perPage === $option ? 'selected' : '' ?>><?= $option ?></option>
									<?php endforeach; ?>
								</select>
							</form>
							<form method="GET">
								<?php foreach ($_GET as $key => $value): ?>
									<?php if ($key !== 'export'): ?>
										<input type="hidden" name="<?= htmlspecialchars($key) ?>" value="<?= htmlspecialchars((string) $value) ?>">
									<?php endif; ?>
								<?php endforeach; ?>
								<input type="hidden" name="export" value="csv">
								<button type="submit" class="btn-secondary">Export CSV</button>
							</form>
						</div>
					</div>

					<?php if (empty($activities)): ?>
						<div class="activity-empty">
							<p class="activity-empty__title">No activity found</p>
							<p class="activity-empty__subtitle">Try adjusting your filters or check back later.</p>
						</div>
					<?php else: ?>
						<div class="activity-rows">
							<?php foreach ($activities as $activity): ?>
								<div class="activity-row">
									<div class="activity-avatar">
										<?= strtoupper(substr($activity['user_name'] ?? 'S', 0, 2)) ?>
									</div>
									<div class="activity-main">
										<p class="activity-line">
											<strong><?= htmlspecialchars($activity['user_name'] ?? 'System') ?></strong>
											<span><?= htmlspecialchars($activity['action_label']) ?></span>
											<?php if ($activity['entity_name']): ?>
												<strong><?= htmlspecialchars($activity['entity_name']) ?></strong>
											<?php endif; ?>
										</p>
										<div class="activity-meta">
											<span><?= htmlspecialchars((string) $activity['time_ago']) ?></span>
											<?php if ($activity['entity_type']): ?>
												<?php
												$rawType = $activity['entity_type'];
												$typeLabel = $entityTypeLabels[$rawType] ?? ucwords(str_replace('_', ' ', $rawType));
												?>
												<span class="activity-pill"><?= htmlspecialchars($typeLabel) ?></span>
											<?php endif; ?>
											<?php if ($activity['ip_address']): ?>
												<span>IP: <?= htmlspecialchars($activity['ip_address']) ?></span>
											<?php endif; ?>
										</div>
									</div>
									<div class="activity-time">
										<?= date('M j, Y H:i', strtotime($activity['created_at'])) ?>
									</div>
								</div>
							<?php endforeach; ?>
						</div>
					<?php endif; ?>
				</section>
			</div>

			<?php if ($totalPages > 1): ?>
				<div class="dash-section">
					<div class="activity-pagination">
						<?php
						$queryParams = $_GET;
						for ($i = max(1, $page - 3); $i <= min($totalPages, $page + 3); $i++):
							$queryParams['page'] = $i;
							$isCurrent = $i === $page;
						?>
							<a class="<?= $isCurrent ? 'btn-primary' : 'btn-secondary' ?> btn-sm" href="?<?= http_build_query($queryParams) ?>">
								<?= $i ?>
							</a>
						<?php endfor; ?>
					</div>
				</div>
			<?php endif; ?>
		<?php endif; ?>
	</div>
</div>

</body>
</html>
