<?= $this->extend('admin/layout/default') ?>
<li class="nav-item">
    <a class="nav-link" id="tab-analytics" href="<?= site_url('admin/api-logs/analytics') ?>">
        <i class="fas fa-chart-bar"></i> Log Analizleri
    </a>
</li>

<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">API Logları</h3>
                </div>
                <div class="card-body">
                    <!-- Filtreler -->
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <div class="card card-outline card-info">
                                <div class="card-header">
                                    <h3 class="card-title">Filtreler</h3>
                                    <div class="card-tools">
                                        <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                            <i class="fas fa-minus"></i>
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <form id="filter-form">
                                        <div class="row">
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label>Başlangıç Tarihi:</label>
                                                    <input type="date" class="form-control" id="start_date" name="start_date">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label>Bitiş Tarihi:</label>
                                                    <input type="date" class="form-control" id="end_date" name="end_date">
                                                </div>
                                            </div>
                                            <div class="col-md-2">
                                                <div class="form-group">
                                                    <label>Kullanıcı ID:</label>
                                                    <input type="number" class="form-control" id="user_id" name="user_id">
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label>URL:</label>
                                                    <input type="text" class="form-control" id="uri" name="uri">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <div class="custom-control custom-checkbox">
                                                        <input class="custom-control-input" type="checkbox" id="error_only" name="error_only" value="1">
                                                        <label for="error_only" class="custom-control-label">Sadece Hataları Göster</label>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-9 text-right">
                                                <button type="button" class="btn btn-primary" id="filter-button">Filtrele</button>
                                                <button type="button" class="btn btn-secondary" id="reset-button">Sıfırla</button>
                                                <a href="<?= site_url('admin/api-logs/export') ?>" class="btn btn-success" id="export-button">
                                                    <i class="fas fa-file-csv"></i> CSV Dışa Aktar
                                                </a>
                                                <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#purge-modal">
                                                    <i class="fas fa-trash"></i> Eski Kayıtları Temizle
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                
                    <div class="table-responsive">
                        <table id="logs-table" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Tarih</th>
                                    <th>URL</th>
                                    <th>Method</th>
                                    <th>IP Adresi</th>
                                    <th>Durum Kodu</th>
                                    <th>Süre (sn)</th>
                                    <th>Kullanıcı ID</th>
                                    <th>İşlemler</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Purge Modal -->
<div class="modal fade" id="purge-modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Eski Kayıtları Temizle</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Kapat">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form action="<?= site_url('admin/api-logs/purge') ?>" method="post">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="days_to_keep">Kaç günden eski kayıtlar silinsin?</label>
                        <input type="number" class="form-control" id="days_to_keep" name="days_to_keep" value="30" min="1">
                    </div>
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle"></i> Dikkat: Bu işlem geri alınamaz!
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">İptal</button>
                    <button type="submit" class="btn btn-danger">Temizle</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('js') ?>
<script>
$(function () {
    let table = $('#logs-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '<?= site_url('admin/api-logs/get-logs') ?>',
            type: 'GET',
            data: function(d) {
                d.start_date = $('#start_date').val();
                d.end_date = $('#end_date').val();
                d.user_id = $('#user_id').val();
                d.uri = $('#uri').val();
                d.error_only = $('#error_only').is(':checked') ? '1' : '';
                return d;
            }
        },
        columns: [
            {data: 'id'},
            {data: 'request_time'},
            {data: 'uri'},
            {data: 'method'},
            {data: 'ip_address'},
            {
                data: 'response_code',
                render: function(data, type, row) {
                    let className = 'badge badge-success';
                    if (data >= 400 && data < 500) {
                        className = 'badge badge-warning';
                    } else if (data >= 500) {
                        className = 'badge badge-danger';
                    }
                    return '<span class="' + className + '">' + data + '</span>';
                }
            },
            {
                data: 'execution_time',
                render: function(data, type, row) {
                    return parseFloat(data).toFixed(3);
                }
            },
            {data: 'user_id'},
            {
                data: null,
                orderable: false,
                render: function(data, type, row) {
                    return '<a href="<?= site_url('admin/api-logs/view/') ?>' + row.id + '" class="btn btn-sm btn-info"><i class="fas fa-eye"></i> Detay</a>';
                }
            }
        ],
        order: [[1, 'desc']],
        language: {
            url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Turkish.json'
        },
        responsive: true,
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Tümü"]]
    });
    
    $('#filter-button').click(function() {
        table.ajax.reload();
        
        // Export URL'sini güncelle
        updateExportUrl();
    });
    
    $('#reset-button').click(function() {
        $('#filter-form')[0].reset();
        table.ajax.reload();
        updateExportUrl();
    });
    
    function updateExportUrl() {
        let baseUrl = '<?= site_url('admin/api-logs/export') ?>';
        let params = {
            start_date: $('#start_date').val(),
            end_date: $('#end_date').val(),
            user_id: $('#user_id').val(),
            uri: $('#uri').val(),
            error_only: $('#error_only').is(':checked') ? '1' : ''
        };
        
        let queryString = Object.keys(params)
            .filter(key => params[key] !== '' && params[key] !== null)
            .map(key => key + '=' + encodeURIComponent(params[key]))
            .join('&');
        
        let url = baseUrl;
        if (queryString) {
            url += '?' + queryString;
        }
        
        $('#export-button').attr('href', url);
    }
});
</script>
<?= $this->endSection() ?>