@extends('layouts.dashboard.superadminapp')

@section('title', 'User Activity Log')

@section('styles')
<style>
    .stat-card {
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        color: #fff;
        transition: transform 0.2s;
    }
    .stat-card:hover {
        transform: translateY(-3px);
    }
    .stat-card .stat-value {
        font-size: 1.8rem;
        font-weight: bold;
    }
    .stat-card .stat-label {
        font-size: 0.85rem;
        opacity: 0.9;
    }
    .bg-total { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }
    .bg-users { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-today { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); }
    .bg-pages { background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%); }

    .activity-type-chart, .method-chart {
        height: 250px;
    }
    .user-avatar-sm {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 0.85rem;
    }
    .activity-detail-modal .modal-header {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: #fff;
    }
    .activity-detail-modal .detail-row {
        padding: 10px 0;
        border-bottom: 1px solid #e3e6f0;
    }
    .activity-detail-modal .detail-row:last-child {
        border-bottom: none;
    }
    .activity-detail-modal .detail-label {
        font-weight: 600;
        color: #858796;
        font-size: 0.8rem;
        text-transform: uppercase;
    }
    .activity-detail-modal .detail-value {
        color: #5a5c69;
        word-break: break-all;
    }
    .trend-chart-container {
        height: 200px;
    }
    .top-page-item {
        padding: 8px 12px;
        border-bottom: 1px solid #e3e6f0;
    }
    .top-page-item:last-child {
        border-bottom: none;
    }
    .top-page-item .page-count {
        font-weight: bold;
        color: #4e73df;
    }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | User Activity Log" icon="history" iconColor="info" />

<!-- Summary Statistics -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-total">
            <div class="stat-value">{{ number_format($stats['total_activities']) }}</div>
            <div class="stat-label"><i class="fas fa-chart-line mr-1"></i> Total Activities (30 Days)</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-users">
            <div class="stat-value">{{ $stats['active_users'] }}</div>
            <div class="stat-label"><i class="fas fa-users mr-1"></i> Active Users</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-today">
            <div class="stat-value">{{ number_format($stats['today_activities']) }}</div>
            <div class="stat-label"><i class="fas fa-calendar-day mr-1"></i> Today's Activities</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-pages">
            <div class="stat-value">{{ $stats['most_visited_pages']->count() }}</div>
            <div class="stat-label"><i class="fas fa-file-alt mr-1"></i> Unique Pages Visited</div>
        </div>
    </div>
</div>

<!-- Charts Row -->
<div class="row mb-4">
    <!-- Activity Trend Chart -->
    <div class="col-xl-6 mb-4">
        <div class="card shadow">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-chart-area mr-2"></i> Activity Trend (Last 7 Days)
                </h6>
            </div>
            <div class="card-body">
                <div class="trend-chart-container">
                    <canvas id="activityTrendChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Activity by Type -->
    <div class="col-xl-3 mb-4">
        <div class="card shadow">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-chart-pie mr-2"></i> By Activity Type
                </h6>
            </div>
            <div class="card-body">
                <div class="activity-type-chart">
                    <canvas id="activityTypeChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Activity by Method -->
    <div class="col-xl-3 mb-4">
        <div class="card shadow">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-code mr-2"></i> By HTTP Method
                </h6>
            </div>
            <div class="card-body">
                <div class="method-chart">
                    <canvas id="methodChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Most Active Users & Top Pages -->
<div class="row mb-4">
    <!-- Most Active Users -->
    <div class="col-xl-6 mb-4">
        <div class="card shadow">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-trophy mr-2"></i> Most Active Users
                </h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>User</th>
                            <th>Role</th>
                            <th class="text-center">Activities</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($stats['most_active_users'] as $userActivity)
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="user-avatar-sm mr-2">
                                            {{ strtoupper(substr($userActivity->user->name ?? 'U', 0, 1)) }}
                                        </div>
                                        <div>
                                            <div class="font-weight-bold">{{ $userActivity->user->name ?? 'Unknown' }}</div>
                                        </div>
                                    </div>
                                </td>
                                <td><span class="badge badge-primary">{{ ucfirst($userActivity->user->role ?? 'N/A') }}</span></td>
                                <td class="text-center"><strong>{{ number_format($userActivity->activity_count) }}</strong></td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted py-3">No activity data</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Most Visited Pages -->
    <div class="col-xl-6 mb-4">
        <div class="card shadow">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-fire mr-2"></i> Most Visited Pages
                </h6>
            </div>
            <div class="card-body p-0" style="max-height: 300px; overflow-y: auto;">
                @forelse($stats['most_visited_pages'] as $page)
                    <div class="top-page-item d-flex justify-content-between align-items-center">
                        <div>
                            <i class="fas fa-file-alt text-muted mr-2"></i>
                            <span class="font-weight-bold">{{ $page->page_title ?? 'Unknown Page' }}</span>
                            <br>
                            <small class="text-muted">{{ $page->route_name ?? 'N/A' }}</small>
                        </div>
                        <span class="page-count badge badge-primary px-3 py-2">{{ number_format($page->visit_count) }}</span>
                    </div>
                @empty
                    <div class="text-center text-muted py-4">No page visit data</div>
                @endforelse
            </div>
        </div>
    </div>
</div>

<!-- Filter Card -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-filter mr-2"></i> Filter Options
        </h6>
    </div>
    <div class="card-body">
        <form id="activityFilterForm">
            <div class="row align-items-end">
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">User</label>
                    <select name="user_id" id="user_id" class="form-control">
                        <option value="">All Users</option>
                        @foreach($users as $user)
                            <option value="{{ $user->id }}">{{ $user->name }} ({{ ucfirst($user->role) }})</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">Activity Type</label>
                    <select name="activity_type" id="activity_type" class="form-control">
                        <option value="">All Types</option>
                        <option value="page_visit">Page Visit</option>
                        <option value="login">Login</option>
                        <option value="logout">Logout</option>
                        <option value="create">Create</option>
                        <option value="update">Update</option>
                        <option value="delete">Delete</option>
                    </select>
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">Method</label>
                    <select name="method" id="method" class="form-control">
                        <option value="">All Methods</option>
                        <option value="GET">GET</option>
                        <option value="POST">POST</option>
                        <option value="PUT">PUT</option>
                        <option value="PATCH">PATCH</option>
                        <option value="DELETE">DELETE</option>
                    </select>
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">From Date</label>
                    <input type="date" name="from_date" id="from_date" class="form-control">
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">To Date</label>
                    <input type="date" name="to_date" id="to_date" class="form-control">
                </div>
                <div class="col-md-2 mb-3">
                    <button type="button" class="btn btn-primary btn-sm mr-1" id="applyFilterBtn">
                        <i class="fas fa-search mr-1"></i> Filter
                    </button>
                    <button type="button" class="btn btn-secondary btn-sm mr-1" id="resetFilterBtn">
                        <i class="fas fa-redo mr-1"></i> Reset
                    </button>
                    <button type="button" class="btn btn-success btn-sm" id="exportBtn">
                        <i class="fas fa-file-csv mr-1"></i> Export
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Activity Log Table -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-history mr-2"></i> Activity Log (Last 30 Days)
        </h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="activityTable" class="table table-bordered table-striped table-sm" width="100%">
                <thead class="thead-light">
                    <tr>
                        <th>User</th>
                        <th>Role</th>
                        <th>Activity</th>
                        <th>Page</th>
                        <th>Method</th>
                        <th>IP Address</th>
                        <th>Device</th>
                        <th>Status</th>
                        <th>Time</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Activity Detail Modal -->
<div class="modal fade activity-detail-modal" id="activityDetailModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-info-circle mr-2"></i> Activity Details</h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body" id="activityDetailContent">
                <!-- Content will be loaded dynamically -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
$(document).ready(function() {
    // Initialize DataTable
    var activityTable = $('#activityTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '{{ route("superadmin.activity.list") }}',
            data: function(d) {
                d.user_id = $('#user_id').val();
                d.activity_type = $('#activity_type').val();
                d.method = $('#method').val();
                d.from_date = $('#from_date').val();
                d.to_date = $('#to_date').val();
            },
            error: function(xhr, error, thrown) {
                console.error('DataTables Ajax Error:', xhr.responseText);
                if (xhr.status === 401 || xhr.status === 419) {
                    alert('Session expired. Please refresh the page and login again.');
                } else {
                    alert('Error loading data: ' + (xhr.responseJSON?.message || thrown || 'Unknown error'));
                }
            }
        },
        columns: [
            { data: 'user_name', name: 'user.name' },
            { data: 'user_role', name: 'user.role' },
            { data: 'activity_badge', name: 'activity_type' },
            { data: 'page_title', name: 'page_title' },
            { data: 'method_badge', name: 'method' },
            { data: 'ip_address', name: 'ip_address' },
            { data: 'device_info', name: 'browser' },
            { data: 'response_info', name: 'response_status' },
            { data: 'time_ago', name: 'created_at' },
            {
                data: 'id',
                orderable: false,
                searchable: false,
                render: function(data) {
                    return '<button class="btn btn-info btn-sm view-detail-btn" data-id="' + data + '" title="View Details"><i class="fas fa-eye"></i></button>';
                }
            }
        ],
        order: [[8, 'desc']],
        pageLength: 25,
        responsive: true,
        language: {
            emptyTable: "No activity records found"
        }
    });

    // Apply filter
    $('#applyFilterBtn').click(function() {
        activityTable.ajax.reload();
    });

    // Reset filter
    $('#resetFilterBtn').click(function() {
        $('#activityFilterForm')[0].reset();
        activityTable.ajax.reload();
    });

    // Export
    $('#exportBtn').click(function() {
        var params = new URLSearchParams({
            user_id: $('#user_id').val(),
            activity_type: $('#activity_type').val(),
            method: $('#method').val(),
            from_date: $('#from_date').val(),
            to_date: $('#to_date').val()
        });
        window.location.href = '{{ route("superadmin.activity.export") }}?' + params.toString();
    });

    // View activity detail
    $(document).on('click', '.view-detail-btn', function() {
        var activityId = $(this).data('id');

        $.ajax({
            url: '{{ url("superadmin/activity") }}/' + activityId,
            type: 'GET',
            success: function(response) {
                if (response.success) {
                    var activity = response.activity;
                    var html = `
                        <div class="row">
                            <div class="col-md-6">
                                <div class="detail-row">
                                    <div class="detail-label">User</div>
                                    <div class="detail-value">${activity.user.name} (${activity.user.email})</div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Role</div>
                                    <div class="detail-value">${activity.user.role}</div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Activity Type</div>
                                    <div class="detail-value">${activity.activity_type}</div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Page Title</div>
                                    <div class="detail-value">${activity.page_title || 'N/A'}</div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Route Name</div>
                                    <div class="detail-value">${activity.route_name || 'N/A'}</div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Method</div>
                                    <div class="detail-value"><span class="badge badge-info">${activity.method}</span></div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Response Status</div>
                                    <div class="detail-value">${activity.response_status || 'N/A'}</div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Response Time</div>
                                    <div class="detail-value">${activity.response_time ? activity.response_time + ' ms' : 'N/A'}</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="detail-row">
                                    <div class="detail-label">IP Address</div>
                                    <div class="detail-value">${activity.ip_address || 'N/A'}</div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Browser</div>
                                    <div class="detail-value">${activity.browser || 'N/A'}</div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Platform</div>
                                    <div class="detail-value">${activity.platform || 'N/A'}</div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Device</div>
                                    <div class="detail-value">${activity.device || 'N/A'}</div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Timestamp</div>
                                    <div class="detail-value">${activity.created_at}</div>
                                </div>
                                <div class="detail-row">
                                    <div class="detail-label">Relative Time</div>
                                    <div class="detail-value">${activity.time_ago}</div>
                                </div>
                            </div>
                        </div>
                        <div class="detail-row mt-3">
                            <div class="detail-label">Full URL</div>
                            <div class="detail-value"><small>${activity.url}</small></div>
                        </div>
                        ${activity.request_data ? `
                        <div class="detail-row">
                            <div class="detail-label">Request Data</div>
                            <div class="detail-value"><pre class="bg-light p-2 rounded" style="max-height: 150px; overflow-y: auto;"><code>${JSON.stringify(activity.request_data, null, 2)}</code></pre></div>
                        </div>
                        ` : ''}
                        <div class="detail-row">
                            <div class="detail-label">User Agent</div>
                            <div class="detail-value"><small class="text-muted">${activity.user_agent || 'N/A'}</small></div>
                        </div>
                    `;
                    $('#activityDetailContent').html(html);
                    $('#activityDetailModal').modal('show');
                }
            },
            error: function() {
                alert('Failed to load activity details');
            }
        });
    });

    // Initialize Charts
    // Activity Trend Chart
    var trendData = @json($stats['activity_trend']);
    var trendLabels = Object.keys(trendData).map(function(date) {
        return new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    });
    var trendValues = Object.values(trendData);

    new Chart(document.getElementById('activityTrendChart'), {
        type: 'line',
        data: {
            labels: trendLabels,
            datasets: [{
                label: 'Activities',
                data: trendValues,
                borderColor: '#4e73df',
                backgroundColor: 'rgba(78, 115, 223, 0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: { beginAtZero: true }
            }
        }
    });

    // Activity Type Chart
    var typeData = @json($stats['activity_by_type']);
    new Chart(document.getElementById('activityTypeChart'), {
        type: 'doughnut',
        data: {
            labels: Object.keys(typeData).map(function(t) { return t.replace('_', ' ').toUpperCase(); }),
            datasets: [{
                data: Object.values(typeData),
                backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b', '#858796']
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: { boxWidth: 12, font: { size: 10 } }
                }
            }
        }
    });

    // Method Chart
    var methodData = @json($stats['activity_by_method']);
    new Chart(document.getElementById('methodChart'), {
        type: 'doughnut',
        data: {
            labels: Object.keys(methodData),
            datasets: [{
                data: Object.values(methodData),
                backgroundColor: ['#36b9cc', '#1cc88a', '#f6c23e', '#fd7e14', '#e74a3b']
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: { boxWidth: 12, font: { size: 10 } }
                }
            }
        }
    });
});
</script>
@endsection
