@extends('layouts.app')

@section('title', 'System Logs')

@section('content')

@include('logging.activity_log_filter')
@include('logging.laravel_log_filter')
<div class="row">
    <div class="col-12">
        <div class="card">
            {{-- <div class="card-header"> --}}
                {{-- <div class="card-tools"> --}}
                    {{-- <button type="button" class="btn btn-sm btn-danger" onclick="clearLogs('activity')">
                        <i class="fas fa-trash"></i> Clear Activity Logs
                    </button> --}}
                    {{-- <button type="button" class="btn btn-sm btn-danger" onclick="clearLogs('error')">
                        <i class="fas fa-trash"></i> Clear Error Logs
                    </button> --}}

                {{-- </div> --}}
            {{-- </div> --}}
            <div class="card-body">
                  <h4 class="card-title">System Logs Dashboard</h4>

                <!-- Nav tabs -->
                <ul class="nav nav-tabs" id="logTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="log-nav nav-link active" data-filters-id="activityLogFilterAccordion" id="activity-tab" data-bs-toggle="tab" data-bs-target="#activity" type="button" role="tab">
                            <i class="fas fa-history"></i> Activity Logs
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="log-nav nav-link" data-filters-id="laravelLogFilterAccordion" id="laravel-tab" data-bs-toggle="tab" data-bs-target="#laravel" type="button" role="tab">
                            <i class="fas fa-file-alt"></i> Laravel Logs
                        </button>
                    </li>
                    {{-- <li class="nav-item" role="presentation">
                        <button class="nav-link" id="error-tab" data-bs-toggle="tab" data-bs-target="#error" type="button" role="tab">
                            <i class="fas fa-exclamation-triangle"></i> Error Logs
                        </button>
                    </li> --}}
                </ul>

                <!-- Tab panes -->
                <div class="tab-content mt-3" id="logTabContent">
                    <!-- Activity Logs Tab -->
                    <div class="tab-pane fade show active" id="activity" role="tabpanel">
                        <!-- Activity Logs Filters -->

                        <div class="table-responsive">
                            <table class="table table-striped w-100" id="activityLogsTable">
                                <thead>
                                    <tr>
                                        <th style="min-width: 150px;">Timestamp</th>
                                        <th style="min-width: 120px;">User</th>
                                        <th style="min-width: 150px;">Action</th>
                                        <th style="min-width: 150px;">Subject Type</th>
                                        <th style="min-width: 150px;">Subject Name</th>
                                        <th style="min-width: 100px;">Details</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>

                    <!-- Laravel Logs Tab -->
                    <div class="tab-pane fade" id="laravel" role="tabpanel">
                        <!-- Laravel Logs Filters -->

                        <div class="table-responsive">
                            <table class="table table-striped w-100" id="laravelLogsTable">
                                <thead>
                                    <tr>
                                        <th style="min-width: 150px;">Timestamp</th>
                                        <th style="min-width: 100px;">Level</th>
                                        <th style="min-width: 300px;">Message</th>
                                        <th style="min-width: 100px;">Context</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>

                    <!-- Error Logs Tab -->
                    {{-- <div class="tab-pane fade" id="error" role="tabpanel">
                        <div class="table-responsive">
                            <table class="table table-striped" id="errorLogsTable">
                                <thead>
                                    <tr>
                                        <th>Timestamp</th>
                                        <th>Level</th>
                                        <th>Message</th>
                                        <th>Context</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div> --}}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Properties Modal -->
<div class="modal fade" id="propertiesModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Activity Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="propertiesContent"></div>
            </div>
        </div>
    </div>
</div>

<!-- Context Modal -->
<div class="modal fade" id="contextModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Log Context</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <pre id="contextContent"></pre>
            </div>
        </div>
    </div>
</div>
@endsection

@push('plugin-scripts')
<script>
$(document).ready(function() {
     $('.log-nav').on('click', function() {
    var filterId = $(this).data('filters-id'); // clicked nav's filter ID
    if(filterId == 'activityLogFilterAccordion'){
        $('#laravelLogFilterAccordion').addClass('d-none');
        $('#activityLogFilterAccordion').removeClass('d-none');
    }else{
        $('#laravelLogFilterAccordion').removeClass('d-none');
        $('#activityLogFilterAccordion').addClass('d-none');

    }
 });

    // Initialize DataTables
    var activityTable = $('#activityLogsTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '{{ route("logging.activity") }}',
            data: function(d) {
                d.user_id = $('#activity_user_filter').val();
                d.action_type = $('#activity_action_filter').val();
                d.date_from = $('#activity_date_from').val();
                d.date_to = $('#activity_date_to').val();
            }
        },
        columns: [
            {data: 'created_at', name: 'created_at'},
            {data: 'user', name: 'user'},
            {data: 'description', name: 'description'},
            {data: 'subject_type', name: 'subject_type'},
            {data: 'subject_name', name: 'subject_name'},
            {data: 'properties', name: 'properties', orderable: false, searchable: false}
        ],
        order: [[0, 'desc']], // Latest records on top
        pageLength: 25
    });

    var laravelTable = $('#laravelLogsTable').DataTable({
        processing: true,
        serverSide: false,
        ajax: {
            url: '{{ route("logging.laravel") }}',
            data: function(d) {
                d.log_level = $('#laravel_level_filter').val();
                d.date_from = $('#laravel_date_from').val();
                d.date_to = $('#laravel_date_to').val();
            }
        },
        columns: [
            {data: 'timestamp', name: 'timestamp'},
            {data: 'level_badge', name: 'level', orderable: false},
            {data: 'message', name: 'message'},
            {data: 'context', name: 'context', orderable: false, searchable: false}
        ],
        order: [[0, 'desc']], // Latest records on top
        pageLength: 25
    });

    // var errorTable = $('#errorLogsTable').DataTable({
    //     processing: true,
    //     serverSide: false,
    //     ajax: '{{ route("logging.error") }}',
    //     columns: [
    //         {data: 'timestamp', name: 'timestamp'},
    //         {data: 'level_badge', name: 'level', orderable: false},
    //         {data: 'message', name: 'message'},
    //         {data: 'context', name: 'context', orderable: false, searchable: false}
    //     ],
    //     order: [[0, 'desc']],
    //     pageLength: 25
    // });

    // Filter functionality for Activity Logs
    $('#apply_activity_filters').on('click', function() {
        activityTable.ajax.reload();
    });

    $('#reset_activity_filters').on('click', function() {
        // Reset select2 dropdowns if they exist
        if ($.fn.select2) {
            $('#activity_user_filter, #activity_action_filter').each(function() {
                if ($(this).hasClass('select2-hidden-accessible')) {
                    $(this).val('').trigger('change');
                } else {
                    $(this).val('');
                }
            });
        } else {
            $('#activity_user_filter').val('');
            $('#activity_action_filter').val('');
        }

        // Reset date inputs
        $('#activity_date_from').val('');
        $('#activity_date_to').val('');

        // Reload table with cleared filters
        activityTable.search('').columns().search('').draw();
    });

    // Filter functionality for Laravel Logs
    $('#apply_laravel_filters').on('click', function() {
        laravelTable.ajax.reload();
    });

    $('#reset_laravel_filters').on('click', function() {
        // Reset select2 dropdowns if they exist
        if ($.fn.select2) {
            $('#laravel_level_filter').each(function() {
                if ($(this).hasClass('select2-hidden-accessible')) {
                    $(this).val('').trigger('change');
                } else {
                    $(this).val('');
                }
            });
        } else {
            $('#laravel_level_filter').val('');
        }

        // Reset date inputs
        $('#laravel_date_from').val('');
        $('#laravel_date_to').val('');

        // Reload table with cleared filters
        laravelTable.search('').columns().search('').draw();
    });

    // Refresh tables when switching tabs
    $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
        var target = $(e.target).attr('data-bs-target');
        if (target === '#activity') {
            activityTable.ajax.reload();
        } else if (target === '#laravel') {
            laravelTable.ajax.reload();
        }
        // else if (target === '#error') {
        //     errorTable.ajax.reload();
        // }
    });
});

// View activity properties
    function viewProperties(activityId) {
        $.get('{{ route("logging.properties", ["id" => ":id"]) }}'.replace(':id', activityId), function(data) {
            var content = '';
            var hasProperties = data.properties && Object.keys(data.properties).length > 0;
            var hasChanges = data.changes && Object.keys(data.changes).length > 0;

            if (hasProperties && hasChanges) {
                // Both properties and changes exist - show in two columns
                content = '<div class="row">';
                content += '<div class="col-md-6"><h6>Properties:</h6><pre>' + JSON.stringify(data.properties, null, 2) + '</pre></div>';
                content += '<div class="col-md-6"><h6>Changes:</h6><pre>' + JSON.stringify(data.changes, null, 2) + '</pre></div>';
                content += '</div>';
            } else if (hasProperties) {
                // Only properties exist - show full width
                content = '<div class="row"><div class="col-12"><h6>Properties:</h6><pre>' + JSON.stringify(data.properties, null, 2) + '</pre></div></div>';
            } else if (hasChanges) {
                // Only changes exist - show full width
                content = '<div class="row"><div class="col-12"><h6>Changes:</h6><pre>' + JSON.stringify(data.changes, null, 2) + '</pre></div></div>';
            } else {
                // No data available
                content = '<div class="alert alert-info">No additional details available for this activity.</div>';
            }

            $('#propertiesContent').html(content);
            $('#propertiesModal').modal('show');
        }).fail(function(xhr, status, error) {
            console.error('Failed to load activity properties:', error);
            $('#propertiesContent').html('<div class="alert alert-danger">Failed to load activity properties. Please try again.</div>');
            $('#propertiesModal').modal('show');
        });
    }

// View log context
    function viewContext(context) {
        try {
            $('#contextContent').text(JSON.stringify(JSON.parse(context), null, 2));
            $('#contextModal').modal('show');
        } catch (error) {
            console.error('Failed to parse context:', error);
            $('#contextContent').text('Error: Invalid JSON context data');
            $('#contextModal').modal('show');
        }
    }

// Clear logs
function clearLogs(type) {
    if (confirm('Are you sure you want to clear all ' + type + ' logs? This action cannot be undone.')) {
        $.post('{{ route("logging.clear") }}', {
            type: type,
            _token: '{{ csrf_token() }}'
        }, function(response) {
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: response.message,
                    timer: 2000,
                    showConfirmButton: false
                });
                // Reload the appropriate table
                if (type === 'activity') {
                    $('#activityLogsTable').DataTable().ajax.reload();
                } else if (type === 'laravel') {
                    $('#laravelLogsTable').DataTable().ajax.reload();
                }
                // else if (type === 'error') {
                //     $('#errorLogsTable').DataTable().ajax.reload();
                // }
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: response.message
                });
            }
        }).fail(function() {
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Failed to clear logs'
            });
        });
    }
}
</script>
@endpush
