@extends('layouts.app')

@section('title', '감사 로그')

@section('content')
<!-- 페이지 헤더 -->
<div class="flex justify-between items-center mb-6">
    <h1 class="text-2xl font-bold text-gray-800">감사 로그</h1>
    <div class="flex items-center gap-2">
        <span class="text-sm text-gray-500">재고 변동 이력을 추적합니다</span>
    </div>
</div>

<!-- 통계 카드 -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
    <div class="bg-white rounded-lg shadow-sm p-4">
        <div class="text-sm text-gray-500">전체 기록</div>
        <div class="text-2xl font-bold text-gray-800">{{ number_format($stats['total']) }}</div>
    </div>
    <div class="bg-white rounded-lg shadow-sm p-4">
        <div class="text-sm text-gray-500">오늘 기록</div>
        <div class="text-2xl font-bold text-blue-600">{{ number_format($stats['today']) }}</div>
    </div>
    @foreach($stats['by_action'] as $action => $count)
    <div class="bg-white rounded-lg shadow-sm p-4">
        <div class="text-sm text-gray-500">{{ $actions[$action] ?? $action }}</div>
        <div class="text-2xl font-bold {{ str_contains($action, 'increase') ? 'text-green-600' : (str_contains($action, 'decrease') ? 'text-red-600' : 'text-yellow-600') }}">
            {{ number_format($count) }}
        </div>
    </div>
    @endforeach
</div>

<!-- 필터 -->
<div class="bg-white rounded-lg shadow-sm p-4 mb-6">
    <form method="GET" class="flex flex-wrap gap-4 items-end">
        <input type="hidden" name="target_type" value="{{ $targetType }}">

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">액션</label>
            <select name="action" onchange="this.form.submit()" class="border rounded-lg px-3 py-2 text-sm">
                <option value="">전체</option>
                @foreach($actions as $key => $label)
                <option value="{{ $key }}" {{ request('action') === $key ? 'selected' : '' }}>{{ $label }}</option>
                @endforeach
            </select>
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">테넌트</label>
            <select name="tenant_id" onchange="this.form.submit()" class="border rounded-lg px-3 py-2 text-sm">
                <option value="">전체</option>
                @foreach($tenants as $tenant)
                <option value="{{ $tenant->id }}" {{ request('tenant_id') == $tenant->id ? 'selected' : '' }}>{{ $tenant->name }}</option>
                @endforeach
            </select>
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">시작일</label>
            <input type="date" name="from" value="{{ request('from') }}"
                   class="border rounded-lg px-3 py-2 text-sm">
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">종료일</label>
            <input type="date" name="to" value="{{ request('to') }}"
                   class="border rounded-lg px-3 py-2 text-sm">
        </div>

        <div class="flex-1">
            <label class="block text-sm font-medium text-gray-700 mb-1">검색 (LOT번호/참조ID)</label>
            <input type="text" name="search" value="{{ request('search') }}"
                   placeholder="LOT 번호 또는 참조 ID 검색..."
                   class="w-full border rounded-lg px-3 py-2 text-sm">
        </div>

        <div>
            <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm">
                검색
            </button>
            <a href="{{ route('audit-logs.index') }}" class="bg-gray-200 hover:bg-gray-300 text-gray-700 px-4 py-2 rounded-lg text-sm ml-1">
                초기화
            </a>
        </div>
    </form>
</div>

<!-- 로그 목록 -->
<div class="bg-white rounded-lg shadow-sm overflow-hidden">
    <table class="min-w-full divide-y divide-gray-200 table-fixed">
        <thead class="bg-gray-50">
            <tr>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase w-32">시간</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase w-24">액션</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase w-32">LOT 번호</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase w-20">수량</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase w-24">사유</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase w-24">참조</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase w-24">테넌트</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase w-24">수행자</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase w-12"></th>
            </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
            @forelse($logs as $log)
            <tr class="hover:bg-gray-50 cursor-pointer" onclick="toggleAccordion({{ $log->id }})">
                <td class="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                    {{ $log->created_at->format('m/d H:i:s') }}
                </td>
                <td class="px-4 py-2 whitespace-nowrap">
                    @php
                        $actionColors = [
                            'stock_increase' => 'bg-green-100 text-green-800',
                            'stock_decrease' => 'bg-red-100 text-red-800',
                            'stock_reserve' => 'bg-yellow-100 text-yellow-800',
                            'stock_release' => 'bg-blue-100 text-blue-800',
                        ];
                    @endphp
                    <span class="px-2 py-1 text-xs font-medium rounded {{ $actionColors[$log->action] ?? 'bg-gray-100 text-gray-800' }}">
                        {{ $log->action_label }}
                    </span>
                </td>
                <td class="px-4 py-2 text-sm text-gray-900 font-mono">
                    {{ $log->lot_no ?? '-' }}
                </td>
                <td class="px-4 py-2 whitespace-nowrap text-sm font-medium {{ $log->qty_change > 0 ? 'text-green-600' : ($log->qty_change < 0 ? 'text-red-600' : 'text-gray-500') }}">
                    @if($log->qty_change > 0)
                        +{{ number_format($log->qty_change, 2) }}
                    @elseif($log->qty_change < 0)
                        {{ number_format($log->qty_change, 2) }}
                    @else
                        -
                    @endif
                </td>
                <td class="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                    {{ $log->reason_label ?? '-' }}
                </td>
                <td class="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                    @if($log->reference_id)
                        <span class="text-blue-600">#{{ $log->reference_id }}</span>
                    @else
                        -
                    @endif
                </td>
                <td class="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                    @if($log->tenant)
                        <span title="{{ $log->tenant->company_name }}">{{ Str::limit($log->tenant->company_name, 10) }}</span>
                    @else
                        <span class="text-gray-400">-</span>
                    @endif
                </td>
                <td class="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                    @if($log->actor)
                        <span title="{{ $log->actor->email }}">{{ $log->actor->name ?? $log->actor->email }}</span>
                    @else
                        <span class="text-gray-400">시스템</span>
                    @endif
                </td>
                <td class="px-4 py-2 whitespace-nowrap text-sm">
                    <a href="{{ route('audit-logs.show', $log->id) }}"
                       class="p-1 text-gray-600 hover:text-gray-800 hover:bg-gray-50 rounded"
                       title="상세 보기"
                       onclick="event.stopPropagation()">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                        </svg>
                    </a>
                </td>
            </tr>
            <!-- 아코디언 컨텐츠 -->
            <tr id="accordion-{{ $log->id }}" class="hidden">
                <td colspan="9" class="px-4 py-4 bg-slate-50 border-t border-b border-slate-200">
                    <div class="grid grid-cols-2 gap-4">
                        <!-- Before -->
                        <div>
                            <h4 class="text-sm font-semibold text-gray-700 mb-2">변경 전 (Before)</h4>
                            <div class="bg-gray-900 rounded-lg p-3 overflow-x-auto max-h-48">
                                <pre class="text-yellow-400 text-xs font-mono whitespace-pre-wrap">{{ json_encode($log->before, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) ?: '{}' }}</pre>
                            </div>
                        </div>
                        <!-- After -->
                        <div>
                            <h4 class="text-sm font-semibold text-gray-700 mb-2">변경 후 (After)</h4>
                            <div class="bg-gray-900 rounded-lg p-3 overflow-x-auto max-h-48">
                                <pre class="text-green-400 text-xs font-mono whitespace-pre-wrap">{{ json_encode($log->after, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) ?: '{}' }}</pre>
                            </div>
                        </div>
                    </div>
                    <!-- 추가 정보 -->
                    <div class="mt-3 flex gap-4 text-xs text-gray-500">
                        <span><strong>IP:</strong> {{ $log->ip ?? '-' }}</span>
                        <span><strong>Target:</strong> {{ $log->target_type }}#{{ $log->target_id }}</span>
                    </div>
                </td>
            </tr>
            @empty
            <tr>
                <td colspan="9" class="px-4 py-8 text-center text-gray-500">
                    감사 로그가 없습니다.
                </td>
            </tr>
            @endforelse
        </tbody>
    </table>

    <!-- 페이지네이션 -->
    @if($logs->hasPages())
    <div class="px-4 py-3 border-t">
        {{ $logs->links() }}
    </div>
    @endif
</div>

<script>
function toggleAccordion(id) {
    const accordion = document.getElementById('accordion-' + id);
    if (accordion) {
        accordion.classList.toggle('hidden');
    }
}
</script>
@endsection