<?php
/**
 * Activity Logs / Audit Trail Viewer - System Admin only
 */

require_once __DIR__ . '/../../includes/auth.php';
requireAuth();
requireSystemAdmin();

$pageTitle = 'Activity Logs';
$currentPage = 'system';

// Ensure table exists
$tableExists = false;
try {
    $pdo->query('SELECT 1 FROM activity_logs LIMIT 1');
    $tableExists = true;
    
    // Check if ip_address index exists, add if missing
    try {
        $indexCheck = $pdo->query("SHOW INDEX FROM activity_logs WHERE Key_name = 'idx_ip_address'");
        if ($indexCheck->rowCount() == 0) {
            $pdo->exec('ALTER TABLE activity_logs ADD INDEX idx_ip_address (ip_address)');
        }
    } catch (PDOException $e) {
        // Index might already exist or error, ignore
    }
} catch (PDOException $e) {
    // Table doesn't exist, create it
    try {
        // Check MySQL version for JSON support
        $versionStmt = $pdo->query('SELECT VERSION()');
        $version = $versionStmt->fetchColumn();
        $mysqlVersion = (float)substr($version, 0, 3);
        
        // Use JSON for MySQL 5.7.8+, TEXT for older versions
        $detailsType = ($mysqlVersion >= 5.7) ? 'JSON' : 'TEXT';
        
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS activity_logs (
                id INT AUTO_INCREMENT PRIMARY KEY,
                action VARCHAR(100) NOT NULL,
                description TEXT NOT NULL,
                details $detailsType NULL,
                user_id INT NULL,
                username VARCHAR(50) NULL,
                ip_address VARCHAR(45) NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_action (action),
                INDEX idx_user_id (user_id),
                INDEX idx_created_at (created_at),
                INDEX idx_ip_address (ip_address),
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $tableExists = true;
    } catch (PDOException $e2) {
        // If creation fails, we'll handle it in queries below
        error_log('Failed to create activity_logs table: ' . $e2->getMessage());
        $tableExists = false;
    }
}

// Filters
$filterAction = $_GET['action'] ?? '';
$filterUser = $_GET['user'] ?? '';
$filterDateFrom = $_GET['date_from'] ?? '';
$filterDateTo = $_GET['date_to'] ?? '';
$searchTerm = trim($_GET['search'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 50;
$offset = ($page - 1) * $perPage;

// Build query
$where = [];
$params = [];

if ($filterAction) {
    $where[] = 'al.action = ?';
    $params[] = $filterAction;
}

if ($filterUser) {
    $where[] = '(al.username = ? OR al.user_id = ?)';
    $params[] = $filterUser;
    $params[] = (int)$filterUser;
}

if ($filterDateFrom) {
    $where[] = 'DATE(al.created_at) >= ?';
    $params[] = $filterDateFrom;
}

if ($filterDateTo) {
    $where[] = 'DATE(al.created_at) <= ?';
    $params[] = $filterDateTo;
}

if ($searchTerm) {
    $where[] = '(al.description LIKE ? OR al.details LIKE ?)';
    $searchParam = '%' . $searchTerm . '%';
    $params[] = $searchParam;
    $params[] = $searchParam;
}

$whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// Initialize variables
$totalLogs = 0;
$totalPages = 0;
$logs = [];
$availableActions = [];
$availableUsers = [];
$stats = ['total' => 0, 'today' => 0, 'failed_logins' => 0, 'user_actions' => 0];

if ($tableExists) {
    try {
        // Get total count
        $countStmt = $pdo->prepare("SELECT COUNT(*) FROM activity_logs al $whereClause");
        $countStmt->execute($params);
        $totalLogs = (int)$countStmt->fetchColumn();
        $totalPages = ceil($totalLogs / $perPage);
        
        // Get logs
        $perPageInt = (int)$perPage;
        $offsetInt = (int)$offset;
        $stmt = $pdo->prepare("
            SELECT al.*, u.full_name
            FROM activity_logs al
            LEFT JOIN users u ON al.user_id = u.id
            $whereClause
            ORDER BY al.created_at DESC
            LIMIT $perPageInt OFFSET $offsetInt
        ");
        $stmt->execute($params);
        $logs = $stmt->fetchAll();
        
        // Get unique actions for filter
        $actionsStmt = $pdo->query("SELECT DISTINCT action FROM activity_logs ORDER BY action");
        $availableActions = $actionsStmt->fetchAll(PDO::FETCH_COLUMN);
        
        // Get unique users for filter
        $usersStmt = $pdo->query("SELECT DISTINCT username FROM activity_logs WHERE username IS NOT NULL ORDER BY username");
        $availableUsers = $usersStmt->fetchAll(PDO::FETCH_COLUMN);
        
        // Statistics
        $stats['total'] = (int)$pdo->query('SELECT COUNT(*) FROM activity_logs')->fetchColumn();
        $stats['today'] = (int)$pdo->query("SELECT COUNT(*) FROM activity_logs WHERE DATE(created_at) = CURDATE()")->fetchColumn();
        $stats['failed_logins'] = (int)$pdo->query("SELECT COUNT(*) FROM activity_logs WHERE action = 'login_failed' AND DATE(created_at) = CURDATE()")->fetchColumn();
        $stats['user_actions'] = (int)$pdo->query("SELECT COUNT(*) FROM activity_logs WHERE action IN ('user_created', 'user_updated', 'user_deleted') AND DATE(created_at) = CURDATE()")->fetchColumn();
    } catch (PDOException $e) {
        error_log('Activity logs query error: ' . $e->getMessage());
    }
}

require_once __DIR__ . '/../../includes/system-header.php';
?>

<div class="header">
    <h1>Activity Logs / Audit Trail</h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/system" class="link-muted">← Dashboard</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<!-- Statistics -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Total Logs</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= number_format($stats['total']) ?></div>
    </div>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Today's Activity</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= number_format($stats['today']) ?></div>
    </div>
    <div class="card" style="background: <?= $stats['failed_logins'] > 0 ? '#fef2f2' : '#f8fafc' ?>;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Failed Logins (Today)</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: <?= $stats['failed_logins'] > 0 ? '#991b1b' : '#1e293b' ?>;"><?= number_format($stats['failed_logins']) ?></div>
    </div>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">User Actions (Today)</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= number_format($stats['user_actions']) ?></div>
    </div>
</div>

<!-- Filters -->
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Filters</h2>
    <form method="get" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; align-items: end;">
        <div>
            <label for="action" style="display: block; margin-bottom: 0.5rem; font-size: 0.875rem; color: #64748b;">Action</label>
            <select id="action" name="action" style="width: 100%; padding: 0.5rem; border: 1px solid var(--border); border-radius: 4px;">
                <option value="">All Actions</option>
                <?php foreach ($availableActions as $action): ?>
                <option value="<?= htmlspecialchars($action) ?>" <?= $filterAction === $action ? 'selected' : '' ?>>
                    <?= htmlspecialchars(ucfirst(str_replace('_', ' ', $action))) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label for="user" style="display: block; margin-bottom: 0.5rem; font-size: 0.875rem; color: #64748b;">User</label>
            <select id="user" name="user" style="width: 100%; padding: 0.5rem; border: 1px solid var(--border); border-radius: 4px;">
                <option value="">All Users</option>
                <?php foreach ($availableUsers as $user): ?>
                <option value="<?= htmlspecialchars($user) ?>" <?= $filterUser === $user ? 'selected' : '' ?>>
                    <?= htmlspecialchars($user) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label for="date_from" style="display: block; margin-bottom: 0.5rem; font-size: 0.875rem; color: #64748b;">From Date</label>
            <input type="date" id="date_from" name="date_from" value="<?= htmlspecialchars($filterDateFrom) ?>" style="width: 100%; padding: 0.5rem; border: 1px solid var(--border); border-radius: 4px;">
        </div>
        <div>
            <label for="date_to" style="display: block; margin-bottom: 0.5rem; font-size: 0.875rem; color: #64748b;">To Date</label>
            <input type="date" id="date_to" name="date_to" value="<?= htmlspecialchars($filterDateTo) ?>" style="width: 100%; padding: 0.5rem; border: 1px solid var(--border); border-radius: 4px;">
        </div>
        <div>
            <label for="search" style="display: block; margin-bottom: 0.5rem; font-size: 0.875rem; color: #64748b;">Search</label>
            <input type="text" id="search" name="search" value="<?= htmlspecialchars($searchTerm) ?>" placeholder="Search description..." style="width: 100%; padding: 0.5rem; border: 1px solid var(--border); border-radius: 4px;">
        </div>
        <div>
            <button type="submit" class="btn" style="width: 100%;">Apply Filters</button>
        </div>
    </form>
    <?php if ($filterAction || $filterUser || $filterDateFrom || $filterDateTo || $searchTerm): ?>
    <p style="margin-top: 1rem;">
        <a href="<?= BASE_PATH ?>/system/activity" class="btn btn-sm btn-ghost">Clear Filters</a>
    </p>
    <?php endif; ?>
</div>

<!-- Activity Logs Table -->
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">
        Activity Logs
        <span style="font-size: 0.875rem; font-weight: 400; color: #64748b; margin-left: 0.5rem;">
            (<?= number_format($totalLogs) ?> total<?= $totalLogs !== $stats['total'] ? ' filtered' : '' ?>)
        </span>
    </h2>
    
    <?php if (empty($logs)): ?>
    <p class="text-muted">No activity logs found.</p>
    <?php else: ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Timestamp</th>
                    <th>Action</th>
                    <th>Description</th>
                    <th>User</th>
                    <th>IP Address</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($logs as $log): ?>
                <tr>
                    <td style="white-space: nowrap; color: #64748b; font-size: 0.875rem;">
                        <?= date('Y-m-d H:i:s', strtotime($log['created_at'])) ?>
                    </td>
                    <td>
                        <span style="padding: 0.25rem 0.5rem; background: #f1f5f9; border-radius: 4px; font-size: 0.8125rem;">
                            <?= htmlspecialchars(ucfirst(str_replace('_', ' ', $log['action']))) ?>
                        </span>
                    </td>
                    <td><?= htmlspecialchars($log['description']) ?></td>
                    <td>
                        <?php if ($log['username']): ?>
                        <div>
                            <strong><?= htmlspecialchars($log['username']) ?></strong>
                            <?php if ($log['full_name']): ?>
                            <br><span style="font-size: 0.75rem; color: #64748b;"><?= htmlspecialchars($log['full_name']) ?></span>
                            <?php endif; ?>
                        </div>
                        <?php else: ?>
                        <span style="color: #94a3b8;">System</span>
                        <?php endif; ?>
                    </td>
                    <td style="font-family: monospace; font-size: 0.875rem; color: #64748b;">
                        <?= htmlspecialchars($log['ip_address'] ?? '—') ?>
                    </td>
                    <td>
                        <?php if (!empty($log['details'])): ?>
                        <?php
                        $detailsData = $log['details'];
                        // Handle JSON column type (MySQL 5.7+)
                        if (is_string($detailsData)) {
                            $decoded = @json_decode($detailsData, true);
                            if (json_last_error() === JSON_ERROR_NONE) {
                                $detailsData = $decoded;
                            }
                        }
                        $detailsJson = json_encode($detailsData, JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES);
                        ?>
                        <button onclick="showDetails(<?= (int)$log['id'] ?>, <?= $detailsJson ?>)" class="btn-icon" title="View Details">
                            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                            </svg>
                        </button>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    
    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <div style="margin-top: 1.5rem; display: flex; justify-content: center; align-items: center; gap: 0.5rem;">
        <?php if ($page > 1): ?>
        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>" class="btn btn-sm btn-outline">← Previous</a>
        <?php endif; ?>
        <span style="color: #64748b;">Page <?= $page ?> of <?= $totalPages ?></span>
        <?php if ($page < $totalPages): ?>
        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>" class="btn btn-sm btn-outline">Next →</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    <?php endif; ?>
</div>

<!-- Details Modal -->
<div id="detailsModal" class="modal" hidden>
    <div class="modal-backdrop" onclick="closeDetails()"></div>
    <div class="modal-content" style="max-width: 600px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
            <h3 style="margin: 0;">Activity Details</h3>
            <button onclick="closeDetails()" class="btn-icon" style="background: transparent; border: none;">
                <svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>
        <pre id="detailsContent" style="background: #f8fafc; padding: 1rem; border-radius: 6px; overflow-x: auto; font-size: 0.875rem; max-height: 400px; overflow-y: auto;"></pre>
    </div>
</div>

<script>
function showDetails(id, details) {
    const modal = document.getElementById('detailsModal');
    const content = document.getElementById('detailsContent');
    if (!modal || !content) return;
    
    try {
        // Try to parse as JSON and pretty print
        let parsed = details;
        if (typeof details === 'string') {
            try {
                parsed = JSON.parse(details);
            } catch (e) {
                // Not JSON, use as-is
                parsed = details;
            }
        }
        content.textContent = typeof parsed === 'object' ? JSON.stringify(parsed, null, 2) : String(parsed);
    } catch (e) {
        content.textContent = String(details);
    }
    modal.hidden = false;
}

function closeDetails() {
    document.getElementById('detailsModal').hidden = true;
}
</script>

<?php require_once __DIR__ . '/../../includes/system-footer.php'; ?>
