@extends('layouts.app')
@section('title', 'Laravel Logs')

@section('content')
@php
    $formatBytes = function (int $bytes): string {
        if ($bytes <= 0) return '0 B';
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $power = min((int) floor(log($bytes, 1024)), count($units) - 1);
        return number_format($bytes / (1024 ** $power), $power === 0 ? 0 : 2).' '.$units[$power];
    };
@endphp

<x-ui.page-toolbar
    title="Laravel Logs"
    description="Inspect application log files, download diagnostics and safely clear old entries from protected server storage."
    :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Administration'],['label'=>'Laravel Logs']]"
>
    <x-slot:actions>
        <a class="mf-btn" href="{{ route('admin.laravel-logs.index', array_filter(['file' => $selected['filename'] ?? null, 'lines' => $lines])) }}">Refresh</a>
    </x-slot:actions>
</x-ui.page-toolbar>

<div class="space-y-5">
    <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">Log files</div>
            <div class="mt-1 text-xl font-semibold">{{ number_format($summary['count']) }}</div>
        </div>
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">Total log size</div>
            <div class="mt-1 text-xl font-semibold">{{ $formatBytes($summary['total_size']) }}</div>
        </div>
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">Latest activity</div>
            <div class="mt-1 text-sm font-semibold">
                {{ $summary['latest'] ? \Carbon\CarbonImmutable::createFromTimestamp($summary['latest']['modified_at'])->format('d M Y H:i:s') : 'No logs yet' }}
            </div>
        </div>
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">Storage status</div>
            <div class="mt-1 text-sm font-semibold">{{ $summary['directory_writable'] ? 'Writable' : 'Read only' }}</div>
            <div class="mt-0.5 text-xs text-muted-foreground">storage/logs</div>
        </div>
    </div>

    @if(!$summary['directory_writable'])
        <div class="mf-alert mf-alert-danger">The storage/logs directory is not writable. Laravel may be unable to write new application logs until server permissions are corrected.</div>
    @endif

    <div class="grid gap-5 xl:grid-cols-[320px_minmax(0,1fr)]">
        <section class="mf-card min-w-0">
            <div class="mf-card-body border-b border-border">
                <h2 class="text-sm font-semibold">Log files</h2>
                <p class="mt-1 text-xs text-muted-foreground">Select a file to inspect its most recent entries.</p>
            </div>

            <div class="divide-y divide-border">
                @forelse($logs as $log)
                    <a
                        href="{{ route('admin.laravel-logs.index', ['file' => $log['filename'], 'lines' => $lines]) }}"
                        class="block px-4 py-3 transition-colors hover:bg-muted/30 {{ ($selected['filename'] ?? null) === $log['filename'] ? 'bg-muted/40' : '' }}"
                    >
                        <div class="flex items-start justify-between gap-3">
                            <div class="min-w-0">
                                <div class="truncate text-sm font-medium">{{ $log['filename'] }}</div>
                                <div class="mt-1 text-xs text-muted-foreground">{{ \Carbon\CarbonImmutable::createFromTimestamp($log['modified_at'])->format('d M Y H:i:s') }}</div>
                            </div>
                            <span class="mf-badge mf-badge-muted shrink-0">{{ $formatBytes($log['size']) }}</span>
                        </div>
                    </a>
                @empty
                    <div class="px-4 py-8 text-center text-sm text-muted-foreground">No .log files currently exist in storage/logs.</div>
                @endforelse
            </div>
        </section>

        <section class="mf-card min-w-0">
            @if($selected)
                <div class="mf-card-body border-b border-border">
                    <div class="flex flex-wrap items-start justify-between gap-3">
                        <div class="min-w-0">
                            <h2 class="truncate text-sm font-semibold">{{ $selected['filename'] }}</h2>
                            <p class="mt-1 text-xs text-muted-foreground">
                                {{ $formatBytes($selected['size']) }} · modified {{ \Carbon\CarbonImmutable::createFromTimestamp($selected['modified_at'])->format('d M Y H:i:s') }}
                            </p>
                        </div>

                        <div class="flex flex-wrap gap-2">
                            <a class="mf-btn mf-btn-sm" href="{{ route('admin.laravel-logs.download', $selected['filename']) }}">Download</a>
                            <form method="POST" action="{{ route('admin.laravel-logs.clear', $selected['filename']) }}" onsubmit="return confirm('Clear all content from this log file?');">
                                @csrf
                                <button class="mf-btn mf-btn-sm" type="submit" @disabled(!$selected['writable'])>Clear log</button>
                            </form>
                            @if($selected['filename'] !== 'laravel.log')
                                <form method="POST" action="{{ route('admin.laravel-logs.destroy', $selected['filename']) }}" onsubmit="return confirm('Delete this log file permanently?');">
                                    @csrf
                                    @method('DELETE')
                                    <button class="mf-btn mf-btn-sm" type="submit">Delete</button>
                                </form>
                            @endif
                        </div>
                    </div>

                    <form method="GET" action="{{ route('admin.laravel-logs.index') }}" class="mt-4 flex flex-wrap items-end gap-2">
                        <input type="hidden" name="file" value="{{ $selected['filename'] }}">
                        <div>
                            <label class="mf-field-label" for="log-lines">Lines to display</label>
                            <select id="log-lines" class="mf-input" name="lines" onchange="this.form.submit()">
                                @foreach($lineOptions as $option)
                                    <option value="{{ $option }}" @selected($lines === $option)>Last {{ number_format($option) }} lines</option>
                                @endforeach
                            </select>
                        </div>
                        @if($viewer['truncated'] ?? false)
                            <span class="mf-badge mf-badge-muted mb-1">Older entries hidden</span>
                        @endif
                    </form>
                </div>

                <div class="p-3">
                    @if(($viewer['content'] ?? '') !== '')
                        <pre class="max-h-[720px] min-h-[360px] overflow-auto rounded-md border border-border bg-muted/20 p-4 font-mono text-xs leading-5 text-foreground whitespace-pre">{{ $viewer['content'] }}</pre>
                    @else
                        <div class="flex min-h-[300px] items-center justify-center rounded-md border border-dashed border-border bg-muted/10 p-6 text-center text-sm text-muted-foreground">This log file is empty.</div>
                    @endif
                </div>
            @else
                <div class="flex min-h-[420px] items-center justify-center p-8 text-center">
                    <div>
                        <div class="text-sm font-semibold">No Laravel logs found</div>
                        <p class="mt-1 text-xs text-muted-foreground">A log file will appear here after Laravel writes its first application log entry.</p>
                    </div>
                </div>
            @endif
        </section>
    </div>
</div>
@endsection
