<?php
require_once __DIR__ . '/includes/base.php';

$breadcrumbs = [['title' => 'Activity Logs', 'url' => '']];

// Fetch activity logs
try {
    // Admin activity
    $adminSql = "SELECT aal.*, u.full_name as admin_name, ar.role_name
                 FROM admin_activity_log aal
                 JOIN users u ON aal.admin_id = u.id
                 LEFT JOIN admin_roles ar ON u.admin_role_id = ar.id
                 ORDER BY aal.created_at DESC
                 LIMIT 500";
    $adminLogs = $db->query($adminSql)->fetchAll(PDO::FETCH_ASSOC);
    
    // User activity
    $userSql = "SELECT al.*, u.full_name as user_name, u.user_type
                FROM activity_log al
                JOIN users u ON al.user_id = u.id
                ORDER BY al.created_at DESC
                LIMIT 500";
    $userLogs = $db->query($userSql)->fetchAll(PDO::FETCH_ASSOC);
    
    // System audit
    $auditSql = "SELECT sal.*, u.full_name as user_name
                 FROM system_audit_log sal
                 LEFT JOIN users u ON sal.user_id = u.id
                 ORDER BY sal.created_at DESC
                 LIMIT 500";
    $auditLogs = $db->query($auditSql)->fetchAll(PDO::FETCH_ASSOC);
    
    // Security events (failed logins, suspicious activity)
    $securitySql = "SELECT * FROM activity_log 
                    WHERE action IN ('failed_login', 'suspicious_activity', 'account_locked', 'password_reset')
                    ORDER BY created_at DESC
                    LIMIT 100";
    $securityLogs = $db->query($securitySql)->fetchAll(PDO::FETCH_ASSOC);
    
    // Statistics
    $stats = [
        'admin_actions_today' => $db->query("SELECT COUNT(*) FROM admin_activity_log WHERE DATE(created_at) = CURDATE()")->fetchColumn(),
        'user_logins_today' => $db->query("SELECT COUNT(*) FROM activity_log WHERE action = 'login' AND DATE(created_at) = CURDATE()")->fetchColumn(),
        'failed_logins_today' => $db->query("SELECT COUNT(*) FROM activity_log WHERE action = 'failed_login' AND DATE(created_at) = CURDATE()")->fetchColumn(),
        'unique_ips_today' => $db->query("SELECT COUNT(DISTINCT ip_address) FROM activity_log WHERE DATE(created_at) = CURDATE()")->fetchColumn()
    ];
    
} catch (PDOException $e) {
    $adminLogs = [];
    $userLogs = [];
    $auditLogs = [];
    $securityLogs = [];
    $stats = ['admin_actions_today' => 0, 'user_logins_today' => 0, 'failed_logins_today' => 0, 'unique_ips_today' => 0];
}

renderAdminHeader('Activity Logs', $breadcrumbs);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">Activity Logs</h2>
        <p class="text-muted mb-0">Monitor all system activity and security events</p>
    </div>
    <div>
        <button class="btn btn-success" onclick="exportLogs()">
            <i class="bi bi-download me-2"></i>Export
        </button>
        <button class="btn btn-danger" onclick="clearOldLogs()">
            <i class="bi bi-trash me-2"></i>Clear Old
        </button>
    </div>
</div>

<!-- Statistics -->
<div class="row mb-4">
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-muted mb-1">Admin Actions Today</h6>
                        <h3 class="mb-0"><?php echo $stats['admin_actions_today']; ?></h3>
                    </div>
                    <div class="bg-primary bg-opacity-10 rounded p-3">
                        <i class="bi bi-shield fs-4 text-primary"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-muted mb-1">User Logins Today</h6>
                        <h3 class="mb-0"><?php echo $stats['user_logins_today']; ?></h3>
                    </div>
                    <div class="bg-success bg-opacity-10 rounded p-3">
                        <i class="bi bi-person-check fs-4 text-success"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-muted mb-1">Failed Logins</h6>
                        <h3 class="mb-0 <?php echo $stats['failed_logins_today'] > 10 ? 'text-danger' : ''; ?>">
                            <?php echo $stats['failed_logins_today']; ?>
                        </h3>
                    </div>
                    <div class="bg-danger bg-opacity-10 rounded p-3">
                        <i class="bi bi-exclamation-triangle fs-4 text-danger"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-muted mb-1">Unique IPs Today</h6>
                        <h3 class="mb-0"><?php echo $stats['unique_ips_today']; ?></h3>
                    </div>
                    <div class="bg-info bg-opacity-10 rounded p-3">
                        <i class="bi bi-globe fs-4 text-info"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Security Alerts -->
<?php if (!empty($securityLogs) && count($securityLogs) > 0): ?>
<div class="alert alert-warning alert-dismissible fade show mb-4">
    <h6 class="alert-heading"><i class="bi bi-shield-exclamation me-2"></i>Recent Security Events</h6>
    <div class="small">
        <?php foreach (array_slice($securityLogs, 0, 3) as $log): ?>
        <div class="mb-1">
            <strong><?php echo htmlspecialchars($log['action']); ?>:</strong> 
            <?php echo htmlspecialchars($log['description'] ?? 'No description'); ?> 
            <span class="text-muted">(<?php echo date('H:i', strtotime($log['created_at'])); ?>)</span>
        </div>
        <?php endforeach; ?>
    </div>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Tabs -->
<ul class="nav nav-tabs mb-4">
    <li class="nav-item">
        <a class="nav-link active" data-bs-toggle="tab" href="#admin">
            <i class="bi bi-shield me-1"></i>Admin Activity
            <span class="badge bg-primary ms-1"><?php echo count($adminLogs); ?></span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#user">
            <i class="bi bi-people me-1"></i>User Activity
            <span class="badge bg-success ms-1"><?php echo count($userLogs); ?></span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#audit">
            <i class="bi bi-journal-text me-1"></i>System Audit
            <span class="badge bg-info ms-1"><?php echo count($auditLogs); ?></span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#security">
            <i class="bi bi-shield-exclamation me-1"></i>Security Events
            <span class="badge bg-danger ms-1"><?php echo count($securityLogs); ?></span>
        </a>
    </li>
</ul>

<div class="tab-content">
    <!-- Admin Activity Tab -->
    <div class="tab-pane fade show active" id="admin">
        <div class="card shadow-sm border-0">
            <div class="card-body p-0">
                <table class="table table-hover mb-0" id="adminTable">
                    <thead class="table-light">
                        <tr>
                            <th>Admin</th>
                            <th>Role</th>
                            <th>Action Type</th>
                            <th>Description</th>
                            <th>Table/Entity</th>
                            <th>IP Address</th>
                            <th>Timestamp</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($adminLogs as $log): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($log['admin_name']); ?></td>
                            <td><span class="badge bg-primary"><?php echo htmlspecialchars($log['role_name'] ?? 'Admin'); ?></span></td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo $log['action_type'] === 'delete' ? 'danger' : 
                                        ($log['action_type'] === 'create' ? 'success' : 'info'); 
                                ?>">
                                    <?php echo ucfirst($log['action_type']); ?>
                                </span>
                            </td>
                            <td><small><?php echo htmlspecialchars($log['action_description'] ?? 'N/A'); ?></small></td>
                            <td><code><?php echo htmlspecialchars($log['affected_table'] ?? 'N/A'); ?></code></td>
                            <td><small class="text-muted"><?php echo htmlspecialchars($log['ip_address'] ?? 'N/A'); ?></small></td>
                            <td><small class="text-muted"><?php echo date('M d, Y H:i:s', strtotime($log['created_at'])); ?></small></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- User Activity Tab -->
    <div class="tab-pane fade" id="user">
        <div class="card shadow-sm border-0">
            <div class="card-body p-0">
                <table class="table table-hover mb-0" id="userTable">
                    <thead class="table-light">
                        <tr>
                            <th>User</th>
                            <th>Type</th>
                            <th>Action</th>
                            <th>Description</th>
                            <th>IP Address</th>
                            <th>User Agent</th>
                            <th>Timestamp</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($userLogs as $log): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($log['user_name']); ?></td>
                            <td><span class="badge bg-success"><?php echo ucfirst($log['user_type']); ?></span></td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo $log['action'] === 'login' ? 'success' : 
                                        ($log['action'] === 'logout' ? 'secondary' : 'info'); 
                                ?>">
                                    <?php echo ucfirst($log['action']); ?>
                                </span>
                            </td>
                            <td><small><?php echo htmlspecialchars($log['description'] ?? 'N/A'); ?></small></td>
                            <td><small class="text-muted"><?php echo htmlspecialchars($log['ip_address'] ?? 'N/A'); ?></small></td>
                            <td><small class="text-muted" title="<?php echo htmlspecialchars($log['user_agent'] ?? ''); ?>">
                                <?php echo substr($log['user_agent'] ?? 'N/A', 0, 30) . '...'; ?>
                            </small></td>
                            <td><small class="text-muted"><?php echo date('M d, Y H:i:s', strtotime($log['created_at'])); ?></small></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- System Audit Tab -->
    <div class="tab-pane fade" id="audit">
        <div class="card shadow-sm border-0">
            <div class="card-body p-0">
                <table class="table table-hover mb-0" id="auditTable">
                    <thead class="table-light">
                        <tr>
                            <th>Event Type</th>
                            <th>User</th>
                            <th>Entity</th>
                            <th>Entity ID</th>
                            <th>Changes</th>
                            <th>IP Address</th>
                            <th>Timestamp</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($auditLogs as $log): ?>
                        <tr>
                            <td>
                                <span class="badge bg-<?php 
                                    echo $log['event_type'] === 'delete' ? 'danger' : 
                                        ($log['event_type'] === 'create' ? 'success' : 'warning'); 
                                ?>">
                                    <?php echo ucfirst($log['event_type']); ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($log['user_name'] ?? 'System'); ?></td>
                            <td><code><?php echo htmlspecialchars($log['entity_type'] ?? 'N/A'); ?></code></td>
                            <td><?php echo htmlspecialchars($log['entity_id'] ?? 'N/A'); ?></td>
                            <td>
                                <?php if ($log['old_data'] || $log['new_data']): ?>
                                <button class="btn btn-sm btn-outline-info" onclick='showChanges(<?php echo json_encode($log); ?>)'>
                                    <i class="bi bi-eye"></i> View
                                </button>
                                <?php else: ?>
                                <small class="text-muted">No data</small>
                                <?php endif; ?>
                            </td>
                            <td><small class="text-muted"><?php echo htmlspecialchars($log['ip_address'] ?? 'N/A'); ?></small></td>
                            <td><small class="text-muted"><?php echo date('M d, Y H:i:s', strtotime($log['created_at'])); ?></small></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Security Events Tab -->
    <div class="tab-pane fade" id="security">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-danger text-white">
                <h6 class="mb-0"><i class="bi bi-shield-exclamation me-2"></i>Security-Related Events</h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-hover mb-0" id="securityTable">
                    <thead class="table-light">
                        <tr>
                            <th>Event</th>
                            <th>Description</th>
                            <th>IP Address</th>
                            <th>User Agent</th>
                            <th>Timestamp</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($securityLogs as $log): ?>
                        <tr class="table-<?php echo $log['action'] === 'failed_login' ? 'danger' : 'warning'; ?>">
                            <td>
                                <span class="badge bg-danger">
                                    <?php echo ucwords(str_replace('_', ' ', $log['action'])); ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($log['description'] ?? 'N/A'); ?></td>
                            <td><code><?php echo htmlspecialchars($log['ip_address'] ?? 'N/A'); ?></code></td>
                            <td><small><?php echo substr($log['user_agent'] ?? 'N/A', 0, 30) . '...'; ?></small></td>
                            <td><small><?php echo date('M d, Y H:i:s', strtotime($log['created_at'])); ?></small></td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-outline-danger" onclick="blockIP('<?php echo htmlspecialchars($log['ip_address']); ?>')">
                                    <i class="bi bi-ban"></i> Block IP
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Changes Modal -->
<div class="modal fade" id="changesModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-file-diff me-2"></i>Data Changes</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>Before (Old Data)</h6>
                        <pre id="oldData" class="bg-light p-3 rounded"></pre>
                    </div>
                    <div class="col-md-6">
                        <h6>After (New Data)</h6>
                        <pre id="newData" class="bg-light p-3 rounded"></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#adminTable, #userTable, #auditTable, #securityTable').DataTable({
        pageLength: 50,
        order: [[6, 'desc']]
    });
});

function showChanges(log) {
    $('#oldData').text(log.old_data ? JSON.stringify(JSON.parse(log.old_data), null, 2) : 'No data');
    $('#newData').text(log.new_data ? JSON.stringify(JSON.parse(log.new_data), null, 2) : 'No data');
    new bootstrap.Modal(document.getElementById('changesModal')).show();
}

function blockIP(ip) {
    Swal.fire({
        title: 'Block IP Address?',
        text: `Block all traffic from ${ip}?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        confirmButtonText: 'Yes, block'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post(APP_URL + '/api/admin.php', {action: 'block_ip', ip: ip})
            .done(function(r) {
                if (r.success) {
                    showToast('IP blocked successfully', 'success');
                } else {
                    showToast(r.message, 'error');
                }
            });
        }
    });
}

function exportLogs() {
    window.location.href = APP_URL + '/api/admin.php?action=export_logs';
    showToast('Export started...', 'info');
}

function clearOldLogs() {
    Swal.fire({
        title: 'Clear Old Logs?',
        text: 'This will delete logs older than 90 days',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post(APP_URL + '/api/admin.php', {action: 'clear_old_logs'})
            .done(function(r) {
                if (r.success) {
                    showToast(r.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                }
            });
        }
    });
}
</script>

<?php renderAdminFooter(); ?>