@extends('backoffice.layouts.app')

@section('title', 'Aktivite Loglari')

@section('content')
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="mb-1">
                <i class="bi bi-activity me-2"></i>
                Aktivite Loglari
            </h2>
            <p class="text-muted">Sistemde gerceklesen islemleri takip edin</p>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <form id="dateFilterForm" class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label small">Baslangic Tarihi</label>
                    <input type="text" name="date_from" class="form-control form-control-sm datetimepicker" placeholder="dd/mm/yyyy hh:mm">
                </div>
                <div class="col-md-3">
                    <label class="form-label small">Bitis Tarihi</label>
                    <input type="text" name="date_to" class="form-control form-control-sm datetimepicker" placeholder="dd/mm/yyyy hh:mm">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary btn-sm w-100">
                        <i class="bi bi-funnel"></i> Filtrele
                    </button>
                </div>
                <div class="col-md-4">
                    <small class="text-muted">Varsayilan aralik: son 24 saat</small>
                </div>
            </form>
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white border-bottom">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Log Listesi</h5>
                <div class="input-group" style="width: 320px;">
                    <span class="input-group-text bg-white">
                        <i class="bi bi-search"></i>
                    </span>
                    <input type="text" id="searchInput" class="form-control" placeholder="Ara...">
                </div>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table id="activityTable" class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th width="70">ID</th>
                            <th width="110">Tip</th>
                            <th width="200">Kullanici</th>
                            <th width="160">Aksiyon</th>
                            <th width="140">Modul</th>
                            <th>Aciklama</th>
                            <th width="140">IP</th>
                            <th width="170">Tarih</th>
                            <th width="90" class="text-center">Detay</th>
                        </tr>
                    </thead>
                    <thead>
                        <tr class="filters">
                            <th><input type="text" class="form-control form-control-sm" placeholder="#" /></th>
                            <th>
                                <select class="form-select form-select-sm">
                            <option value="">Tumu</option>
                                    <option value="backoffice">Backoffice</option>
                                    <option value="finance">Finans</option>
                                </select>
                            </th>
                            <th><input type="text" class="form-control form-control-sm" placeholder="Kullanici" /></th>
                            <th>
                                <select class="form-select form-select-sm" data-filter="action">
                                    <option value="">Aksiyon</option>
                                </select>
                            </th>
                            <th>
                                <select class="form-select form-select-sm" data-filter="module">
                                    <option value="">Modul</option>
                                </select>
                            </th>
                            <th><input type="text" class="form-control form-control-sm" placeholder="Aciklama" /></th>
                            <th>
                                <select class="form-select form-select-sm" data-filter="ip">
                                    <option value="">IP</option>
                                </select>
                            </th>
                            <th><input type="date" class="form-control form-control-sm" data-filter="date" /></th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data loaded via AJAX -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Detail Modal -->
<div class="modal fade" id="activityDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-receipt"></i>
                    Log Detayi
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="activityDetailContent">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Yukleniyor...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<style>
    #activityTable thead tr.filters th {
        background: #fff;
        border-bottom: 1px solid #e9ecef;
        padding: 8px;
    }
    #activityTable thead tr.filters input,
    #activityTable thead tr.filters select {
        min-width: 80px;
    }
    .text-truncate-2 {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }
    pre.json-block {
        background: #f8f9fa;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        padding: 12px;
        font-size: 12px;
        white-space: pre-wrap;
        word-break: break-word;
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
$(document).ready(function() {
    let table;
    const $dateFromInput = $('input[name="date_from"]');
    const $dateToInput = $('input[name="date_to"]');
    const defaultActualDateFrom = @json(now('Europe/Istanbul')->subHours(24)->format('d/m/Y H:i'));
    const defaultActualDateTo = @json(now('Europe/Istanbul')->format('d/m/Y H:i'));

    const datePickers = flatpickr('.datetimepicker', {
        enableTime: true,
        time_24hr: true,
        dateFormat: 'd/m/Y H:i',
        minuteIncrement: 1,
        allowInput: true
    });

    function prettyJson(data) {
        if (!data) return '-';
        try {
            return JSON.stringify(data, null, 2);
        } catch (e) {
            return String(data);
        }
    }

    function normalizeDateTime(value) {
        if (!value) return '';
        const parts = value.split(' ');
        const datePart = parts[0] || '';
        const timePart = parts[1] || '00:00';
        const dateBits = datePart.split('/');
        if (dateBits.length !== 3) return value;
        return `${dateBits[2]}-${dateBits[1]}-${dateBits[0]} ${timePart}`;
    }

    function getDateFilters() {
        const filters = {};
        if ($dateFromInput.val()) {
            filters.date_from = normalizeDateTime($dateFromInput.val());
        }
        if ($dateToInput.val()) {
            filters.date_to = normalizeDateTime($dateToInput.val());
        }
        return filters;
    }

    if (!$dateFromInput.val() && !$dateToInput.val()) {
        if (datePickers[0]) {
            datePickers[0].setDate(defaultActualDateFrom, true, 'd/m/Y H:i');
        }
        if (datePickers[1]) {
            datePickers[1].setDate(defaultActualDateTo, true, 'd/m/Y H:i');
        }
    }

    table = $('#activityTable').DataTable({
        processing: true,
        serverSide: false,
        ajax: {
            url: '{{ route("backoffice.activity-logs.index") }}',
            data: function(d) {
                return Object.assign(d, getDateFilters());
            }
        },
        columns: [
            { data: 'id' },
            {
                data: 'user_type',
                render: function(data) {
                    const label = data === 'finance' ? 'Finans' : 'Backoffice';
                    const cls = data === 'finance' ? 'info' : 'primary';
                    return '<span class="badge bg-' + cls + '">' + label + '</span>';
                }
            },
            { data: 'user_name' },
            { data: 'action' },
            { data: 'module' },
            {
                data: 'description',
                render: function(data) {
                    const text = data || '-';
                    return '<div class="text-truncate-2" title="' + text.replace(/"/g, '&quot;') + '">' + text + '</div>';
                }
            },
            { data: 'ip_address' },
            {
                data: 'created_at',
                render: function(data, type) {
                    if (!data) return '-';
                    if (type === 'display') {
                        return new Date(data).toLocaleString('tr-TR');
                    }
                    return data;
                }
            },
            {
                data: null,
                orderable: false,
                render: function(data) {
                    return '<button class="btn btn-outline-primary btn-sm btn-detail" data-id="' + data.id + '"><i class="bi bi-eye"></i></button>';
                }
            }
        ],
        order: [[7, 'desc']],
        pageLength: 25,
        language: {
            url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json'
        }
    });

    $('#dateFilterForm').on('submit', function(e) {
        e.preventDefault();
        table.ajax.reload();
    });

    // Global search
    $('#searchInput').on('keyup', function() {
        table.search(this.value).draw();
    });

    function buildUniqueOptions(columnIndex, selector) {
        const column = table.column(columnIndex);
        const values = column.data().unique().sort();
        const select = $(selector);
        values.each(function(value) {
            if (!value) return;
            select.append(new Option(value, value));
        });
    }

    table.on('init', function() {
        buildUniqueOptions(3, 'select[data-filter="action"]');
        buildUniqueOptions(4, 'select[data-filter="module"]');
        buildUniqueOptions(6, 'select[data-filter="ip"]');
    });

    // Column filters
    $('#activityTable thead tr.filters th').each(function(i) {
        $('input, select', this).on('keyup change', function() {
            const value = this.value;
            if ($(this).is('select')) {
                const escaped = value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                table.column(i).search(value ? '^' + escaped + '$' : '', true, false).draw();
            } else {
                if (table.column(i).search() !== value) {
                    table.column(i).search(value).draw();
                }
            }
        });
    });

    // Date filter for created_at (column 7)
    $.fn.dataTable.ext.search.push(function(settings, data) {
        if (settings.nTable.id !== 'activityTable') {
            return true;
        }
        const selected = $('input[data-filter="date"]').val();
        if (!selected) return true;
        const raw = data[7] || '';
        return raw.startsWith(selected);
    });

    $('input[data-filter="date"]').on('change', function() {
        table.draw();
    });

    // Detail modal
    $(document).on('click', '.btn-detail', function() {
        const rowData = table.row($(this).closest('tr')).data();
        if (!rowData) return;

        const html = `
            <div class="row g-3">
                <div class="col-md-6">
                    <p class="mb-1 small text-muted">ID</p>
                    <p class="fw-semibold">#${rowData.id}</p>
                </div>
                <div class="col-md-6">
                    <p class="mb-1 small text-muted">Kullanici Tipi</p>
                    <p class="fw-semibold">${rowData.user_type === 'finance' ? 'Finans' : 'Backoffice'}</p>
                </div>
                <div class="col-md-6">
                    <p class="mb-1 small text-muted">Kullanici</p>
                    <p class="fw-semibold">${rowData.user_name || '-'}</p>
                </div>
                <div class="col-md-6">
                    <p class="mb-1 small text-muted">Aksiyon</p>
                    <p class="fw-semibold">${rowData.action || '-'}</p>
                </div>
                <div class="col-md-6">
                    <p class="mb-1 small text-muted">Modul</p>
                    <p class="fw-semibold">${rowData.module || '-'}</p>
                </div>
                <div class="col-md-6">
                    <p class="mb-1 small text-muted">IP Adresi</p>
                    <p class="fw-semibold">${rowData.ip_address || '-'}</p>
                </div>
                <div class="col-12">
                    <p class="mb-1 small text-muted">Aciklama</p>
                    <div class="alert alert-light border mb-0">${rowData.description || '-'}</div>
                </div>
                <div class="col-12">
                    <p class="mb-1 small text-muted">Eski Veri</p>
                    <pre class="json-block">${prettyJson(rowData.old_data)}</pre>
                </div>
                <div class="col-12">
                    <p class="mb-1 small text-muted">Yeni Veri</p>
                    <pre class="json-block">${prettyJson(rowData.new_data)}</pre>
                </div>
                <div class="col-12">
                    <p class="mb-1 small text-muted">User Agent</p>
                    <div class="alert alert-light border mb-0">${rowData.user_agent || '-'}</div>
                </div>
            </div>
        `;

        $('#activityDetailContent').html(html);
        $('#activityDetailModal').modal('show');
    });
});
</script>
@endpush
