@extends('agency.layouts.app')

@section('title', 'İşlem Kayıtları')

@section('content')
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Archivo:wght@500;600;700;800&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">

@php
    $dtColumns = [
        ['key' => 'created_at', 'label' => 'Zaman', 'sortable' => true, 'sort' => 'created_at', 'width' => '150px'],
        ['key' => 'user', 'label' => 'Kullanıcı', 'sortable' => true, 'sort' => 'user_id', 'width' => '210px'],
        ['key' => 'module', 'label' => 'Modül', 'sortable' => true, 'sort' => 'module', 'width' => '140px'],
        ['key' => 'action', 'label' => 'İşlem', 'sortable' => true, 'sort' => 'action', 'width' => '130px'],
        ['key' => 'description', 'label' => 'Açıklama'],
        ['key' => 'route', 'label' => 'Rota', 'width' => '190px', 'visible' => false],
        ['key' => 'ip', 'label' => 'IP Adresi', 'width' => '130px'],
        ['key' => '_actions', 'label' => '', 'fixed' => true, 'align' => 'end', 'width' => '56px'],
    ];

    $dtFilters = [
        ['key' => 'date_from', 'label' => 'Başlangıç', 'type' => 'date', 'value' => request('date_from')],
        ['key' => 'date_to', 'label' => 'Bitiş', 'type' => 'date', 'value' => request('date_to')],
        ['key' => 'user_id', 'label' => 'Kullanıcı', 'value' => request('user_id'),
         'placeholder' => 'Tüm kullanıcılar', 'options' => $users->pluck('full_name', 'id')->all()],
        ['key' => 'module', 'label' => 'Modül', 'value' => request('module'),
         'placeholder' => 'Tüm modüller', 'options' => $modules->all()],
        ['key' => 'action', 'label' => 'İşlem Tipi', 'value' => request('action'),
         'placeholder' => 'Tüm işlemler', 'options' => $actions],
    ];

    $dtStats = [
        ['label' => 'Bugünkü İşlem', 'value' => number_format($logStats['today'], 0, ',', '.'), 'icon' => 'fa-bolt', 'color' => '#0ea5e9'],
        ['label' => 'Son 7 Gün', 'value' => number_format($logStats['week'], 0, ',', '.'), 'icon' => 'fa-calendar-week', 'color' => '#6366f1'],
        ['label' => 'Toplam Kayıt', 'value' => number_format($logStats['total'], 0, ',', '.'), 'icon' => 'fa-database', 'color' => '#0f766e'],
        ['label' => 'Bugün Aktif Kullanıcı', 'value' => number_format($logStats['users_today'], 0, ',', '.'), 'icon' => 'fa-user-check', 'color' => '#d97706'],
    ];
@endphp

<div class="container-fluid py-4 alog-page">

    <x-data-table
        module="activity-logs"
        title="İşlem Kayıtları"
        subtitle="Acentenizde yapılan tüm işlemlerin denetim kaydı"
        icon="fa-clipboard-list"
        :columns="$dtColumns"
        :filters="$dtFilters"
        :stats="$dtStats"
        :search="request('search', request('q', ''))"
        search-placeholder="Açıklama, URL, rota ara…"
        :sort="$sort"
        :dir="$dir"
        :paginator="$logs"
    >
        <x-slot:headerActions>
            <span class="alog-live"><span class="alog-live-dot"></span> Kayıt aktif</span>
            <a href="{{ route('agency.settings') }}" class="dt-btn dt-btn-ghost"><i class="fas fa-arrow-left"></i> Ayarlar</a>
        </x-slot:headerActions>

        @forelse($logs as $log)
            <tr class="alog-row" data-action="{{ $log->action }}">
                <td data-col="created_at">
                    <div class="alog-time">{{ $log->created_at->format('H:i:s') }}</div>
                    <div class="alog-date">
                        @if($log->created_at->isToday()) Bugün
                        @elseif($log->created_at->isYesterday()) Dün
                        @else {{ $log->created_at->translatedFormat('d M Y') }}
                        @endif
                    </div>
                </td>

                <td data-col="user">
                    <div class="alog-user">
                        <span class="alog-avatar">
                            {{ $log->user
                                ? mb_strtoupper(mb_substr($log->user->first_name, 0, 1) . mb_substr($log->user->last_name, 0, 1))
                                : '—' }}
                        </span>
                        <span class="alog-uname text-truncate">{{ $log->user->full_name ?? 'Sistem' }}</span>
                    </div>
                </td>

                <td data-col="module"><span class="alog-chip">{{ $log->module_label }}</span></td>

                <td data-col="action">
                    <span class="alog-act"><span class="alog-dot"></span>{{ $log->action_label }}</span>
                </td>

                <td data-col="description">
                    <span class="alog-desc" title="{{ $log->description }}">{{ $log->description }}</span>
                </td>

                <td data-col="route">
                    <span class="alog-mono text-truncate d-inline-block" style="max-width:180px" title="{{ $log->url }}">{{ $log->route_name ?: '—' }}</span>
                </td>

                <td data-col="ip"><span class="alog-mono">{{ $log->ip_address ?: '—' }}</span></td>

                <td data-col="_actions" class="text-end">
                    @if($log->properties)
                        <button type="button" class="alog-expand" onclick="alogToggle(this)" title="Detayları göster">
                            <i class="fas fa-chevron-down"></i>
                        </button>
                    @endif
                </td>
            </tr>

            @if($log->properties)
                <tr class="alog-detail-row" hidden>
                    <td colspan="{{ count($dtColumns) }}">
                        <div class="alog-detail">
                            <div class="alog-detail-meta">
                                <span><i class="fas fa-route me-1"></i>{{ $log->route_name ?: '—' }}</span>
                                <span><i class="fas fa-link me-1"></i>{{ $log->url }}</span>
                            </div>
                            <pre>{{ json_encode($log->properties, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) }}</pre>
                        </div>
                    </td>
                </tr>
            @endif
        @empty
            <tr>
                <td colspan="{{ count($dtColumns) }}">
                    <div class="dt-empty">
                        <i class="fas fa-satellite-dish"></i>
                        <h4>Kayıt bulunamadı</h4>
                        <div>Seçili filtrelerle eşleşen işlem kaydı yok. Filtreleri genişletmeyi deneyin.</div>
                    </div>
                </td>
            </tr>
        @endforelse
    </x-data-table>
</div>

<style>
    /* İşlem kayıtları — data-table üzerinde denetim defteri okunabilirliği:
       veri alanları monospace, işlem tipi renk kodlu. */
    .alog-page {
        font-family: 'Archivo', system-ui, sans-serif;
        --c-view: #64748b;
        --c-create: #059669;
        --c-update: #0284c7;
        --c-delete: #e11d48;
        --c-export: #d97706;
        --c-login: #7c3aed;
        --c-failed: #dc2626;
        --c-other: #94a3b8;
    }

    .alog-live {
        font-family: 'IBM Plex Mono', monospace; font-size: .7rem; font-weight: 500;
        color: #059669; background: rgba(16, 185, 129, .1); border: 1px solid rgba(16, 185, 129, .25);
        padding: 7px 14px; border-radius: 999px; display: inline-flex; align-items: center; gap: 7px;
    }
    .alog-live-dot { width: 7px; height: 7px; border-radius: 50%; background: #10b981; animation: alogPulse 1.8s ease-in-out infinite; }
    @keyframes alogPulse {
        0%, 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, .5); }
        50% { box-shadow: 0 0 0 5px rgba(16, 185, 129, 0); }
    }

    /* Satır rengi işlem tipine göre */
    .alog-row[data-action="view"]   { --row-c: var(--c-view); }
    .alog-row[data-action="create"] { --row-c: var(--c-create); }
    .alog-row[data-action="update"] { --row-c: var(--c-update); }
    .alog-row[data-action="delete"] { --row-c: var(--c-delete); }
    .alog-row[data-action="export"] { --row-c: var(--c-export); }
    .alog-row[data-action="login"],
    .alog-row[data-action="logout"] { --row-c: var(--c-login); }
    .alog-row[data-action="other"]  { --row-c: var(--c-other); }
    .alog-row td:first-child { box-shadow: inset 3px 0 0 var(--row-c, #cbd5e1); }

    /* Güvenlik olayları: başarısız giriş ve giriş kilidi göze çarpsın */
    .alog-row[data-action="login_failed"],
    .alog-row[data-action="lockout"] { --row-c: var(--c-failed); }
    .alog-row[data-action="login_failed"] td,
    .alog-row[data-action="lockout"] td { background: #fef6f6; }
    .alog-row[data-action="lockout"] .alog-act { font-weight: 700; }

    .alog-time { font-family: 'IBM Plex Mono', monospace; font-size: .82rem; font-weight: 600; color: #0f172a; letter-spacing: .01em; }
    .alog-date { font-size: .68rem; color: #94a3b8; font-weight: 600; margin-top: 1px; }

    .alog-user { display: flex; align-items: center; gap: 9px; min-width: 0; }
    .alog-avatar {
        width: 28px; height: 28px; border-radius: 9px; flex-shrink: 0;
        display: inline-flex; align-items: center; justify-content: center;
        background: #f1f5f9; color: #475569; border: 1px solid #e2e8f0;
        font-size: .62rem; font-weight: 700; letter-spacing: .04em;
    }
    .alog-uname { font-size: .8rem; font-weight: 600; color: #334155; max-width: 150px; }

    .alog-chip {
        display: inline-block; font-size: .68rem; font-weight: 700; color: #475569;
        background: #f1f5f9; border: 1px solid #e8edf4; border-radius: 8px; padding: 3px 9px; white-space: nowrap;
    }

    .alog-act {
        display: inline-flex; align-items: center; gap: 6px; white-space: nowrap;
        font-family: 'IBM Plex Mono', monospace; font-size: .68rem; font-weight: 600;
        text-transform: uppercase; letter-spacing: .06em; color: var(--row-c, #64748b);
    }
    .alog-dot {
        width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; background: var(--row-c, #cbd5e1);
        box-shadow: 0 0 0 3px color-mix(in srgb, var(--row-c, #cbd5e1) 18%, transparent);
    }

    .alog-desc {
        display: block; font-size: .82rem; color: #1e293b;
        overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 640px;
    }
    .alog-mono { font-family: 'IBM Plex Mono', monospace; font-size: .72rem; color: #64748b; }

    .alog-expand {
        width: 28px; height: 28px; border-radius: 9px; flex-shrink: 0;
        border: 1px solid #e8edf4; background: #fff; color: #94a3b8;
        display: inline-flex; align-items: center; justify-content: center;
        font-size: .62rem; cursor: pointer; transition: all .18s ease;
    }
    .alog-expand:hover { color: #0284c7; border-color: #bae6fd; background: #f0f9ff; }
    .alog-expand.is-open { transform: rotate(180deg); color: #0284c7; border-color: #bae6fd; }

    /* Detay satırı — koyu konsol bloğu */
    .alog-detail-row[hidden] { display: none; }
    .alog-detail-row > td { padding: 0 16px 12px !important; background: #fbfcfe; }
    .alog-detail { border-radius: 12px; background: #0b1526; border: 1px solid rgba(148, 178, 222, .12); overflow: hidden; }
    .alog-detail-meta {
        display: flex; flex-wrap: wrap; gap: 16px; padding: 9px 15px;
        border-bottom: 1px solid rgba(148, 178, 222, .12);
        font-family: 'IBM Plex Mono', monospace; font-size: .64rem; color: #64748b;
    }
    .alog-detail-meta span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; }
    .alog-detail pre {
        margin: 0; padding: 13px 15px; max-height: 280px; overflow: auto;
        font-family: 'IBM Plex Mono', monospace; font-size: .7rem; line-height: 1.6;
        color: #7dd3fc; white-space: pre-wrap; word-break: break-all;
    }

    @media (max-width: 768px) {
        .alog-desc { white-space: normal; }
    }
</style>

<script>
    // Detay satırını aç/kapat (kayıt satırının hemen ardındaki gizli satır)
    function alogToggle(btn) {
        const detail = btn.closest('tr').nextElementSibling;
        if (!detail || !detail.classList.contains('alog-detail-row')) return;
        const open = detail.hasAttribute('hidden');
        detail.toggleAttribute('hidden', !open);
        btn.classList.toggle('is-open', open);
    }
</script>
@endsection
