@extends('layouts.default')
@section('title', $page_title)
@section('content')
<div class="container-fluid">
    @include('admin.partials.page-header')

    @if(session('success'))
        <div class="alert alert-success">{{ session('success') }}</div>
    @endif
    @if(session('error'))
        <div class="alert alert-danger">{{ session('error') }}</div>
    @endif

    <div class="card">
        <div class="card-header">
            <h4 class="card-title mb-0">Önizleme Filtresi</h4>
        </div>
        <div class="card-body">
            <form method="GET" action="{{ route('admin.integrations.preview.index') }}" class="row g-3 align-items-end">
                <div class="col-lg-3">
                    <label class="form-label">Müşteri</label>
                    <select name="client_id" class="form-control">
                        <option value="">Tüm müşteriler</option>
                        @foreach($clients as $client)
                            <option value="{{ $client->id }}" @selected((string) request('client_id') === (string) $client->id)>{{ $client->company_name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-lg-3">
                    <label class="form-label">Platform</label>
                    <select name="platform" class="form-control">
                        <option value="">Tüm platformlar</option>
                        @foreach(['google_ads' => 'Google Ads', 'meta_ads' => 'Meta Ads', 'search_console' => 'Search Console', 'ga4' => 'GA4'] as $key => $label)
                            <option value="{{ $key }}" @selected(request('platform') === $key)>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-lg-4">
                    <label class="form-label">Bağlantı</label>
                    <select name="connection_id" class="form-control">
                        <option value="">Bağlantı seç</option>
                        @foreach($connections as $connection)
                            <option value="{{ $connection->id }}" @selected((string) request('connection_id') === (string) $connection->id)>
                                #{{ $connection->id }} · {{ strtoupper(str_replace('_', ' ', $connection->platform)) }} · {{ $connection->client?->company_name }} · {{ $connection->connection_name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-lg-2">
                    <button class="btn btn-primary w-100">Seç</button>
                </div>
            </form>
        </div>
    </div>

    @if($selectedConnection)
        <div class="row">
            <div class="col-xl-4">
                <div class="card">
                    <div class="card-header"><h4 class="card-title mb-0">Bağlantı Bilgisi</h4></div>
                    <div class="card-body">
                        <dl class="row mb-0">
                            <dt class="col-5">Müşteri</dt><dd class="col-7">{{ $selectedConnection->client?->company_name }}</dd>
                            <dt class="col-5">Platform</dt><dd class="col-7">{{ strtoupper(str_replace('_', ' ', $selectedConnection->platform)) }}</dd>
                            <dt class="col-5">Bağlantı</dt><dd class="col-7">{{ $selectedConnection->connection_name }}</dd>
                            <dt class="col-5">Hesap ID</dt><dd class="col-7">{{ $selectedConnection->account_id ?: '-' }}</dd>
                            <dt class="col-5">Durum</dt><dd class="col-7">@include('admin.partials.status-badge', ['status' => $selectedConnection->status])</dd>
                            <dt class="col-5">Token</dt><dd class="col-7">{{ $selectedConnection->secureCredential ? 'Var' : 'Yok' }}</dd>
                        </dl>
                        <a href="{{ route('admin.accounts.'.str_replace('_', '-', $selectedConnection->platform).'.show', $selectedConnection) }}" class="btn btn-outline-primary btn-sm mt-3">Bağlantı Detayına Git</a>
                    </div>
                </div>
            </div>
            <div class="col-xl-8">
                <div class="card">
                    <div class="card-header"><h4 class="card-title mb-0">Canlı Veri Önizlemesi Al</h4></div>
                    <div class="card-body">
                        <form method="POST" action="{{ route('admin.integrations.preview.run') }}" class="row g-3 align-items-end">
                            @csrf
                            <input type="hidden" name="connection_id" value="{{ $selectedConnection->id }}">
                            <div class="col-md-3">
                                <label class="form-label">Başlangıç</label>
                                <input type="date" name="from" class="form-control" value="{{ now()->subDays(7)->toDateString() }}" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Bitiş</label>
                                <input type="date" name="to" class="form-control" value="{{ now()->subDay()->toDateString() }}" required>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Limit</label>
                                <input type="number" name="limit" class="form-control" value="10" min="1" max="50">
                            </div>
                            <div class="col-md-4">
                                <button class="btn btn-primary w-100">Canlı Veriyi Önizle</button>
                            </div>
                        </form>
                        <div class="alert alert-light border mt-3 mb-0">
                            Bu işlem snapshot kaydetmez. Sadece API yetkisi, tarih aralığı ve seçilen hesabın veri döndürüp döndürmediğini kontrol eder.
                        </div>
                    </div>
                </div>
            </div>
        </div>
    @endif

    @if($lastPreview)
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h4 class="card-title mb-0">Son Önizleme Sonucu</h4>
                <span class="badge {{ !empty($lastPreview['ok']) ? 'badge-success' : 'badge-danger' }}">{{ !empty($lastPreview['ok']) ? 'Başarılı' : 'Hatalı' }}</span>
            </div>
            <div class="card-body">
                <div class="row g-3 mb-4">
                    <div class="col-md-3"><strong>Platform:</strong><br>{{ strtoupper(str_replace('_', ' ', $lastPreview['platform'] ?? '-')) }}</div>
                    <div class="col-md-3"><strong>Tarih:</strong><br>{{ $lastPreview['from'] ?? '-' }} / {{ $lastPreview['to'] ?? '-' }}</div>
                    <div class="col-md-3"><strong>Süre:</strong><br>{{ $lastPreview['duration_ms'] ?? 0 }} ms</div>
                    <div class="col-md-3"><strong>Zaman:</strong><br>{{ $lastPreview['previewed_at'] ?? '-' }}</div>
                </div>

                <div class="alert {{ !empty($lastPreview['ok']) ? 'alert-success' : 'alert-danger' }}">
                    <strong>{{ $lastPreview['message'] ?? '-' }}</strong>
                    @if(!empty($lastPreview['error']))
                        <div class="mt-2">{{ $lastPreview['error'] }}</div>
                    @endif
                </div>

                @if(!empty($lastPreview['totals']))
                    <div class="row g-3 mb-4">
                        @foreach($lastPreview['totals'] as $metric => $value)
                            <div class="col-xl-2 col-md-3 col-6">
                                <div class="border p-3 h-100">
                                    <div class="text-muted small">{{ strtoupper(str_replace('_', ' ', $metric)) }}</div>
                                    <div class="fs-5 fw-bold">{{ is_numeric($value) ? number_format((float) $value, 2, ',', '.') : $value }}</div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                @endif

                @if(!empty($lastPreview['rows']))
                    @php($headers = array_keys($lastPreview['rows'][0]))
                    <div class="table-responsive mb-4">
                        <table class="table table-bordered table-striped align-middle">
                            <thead>
                                <tr>
                                    @foreach($headers as $header)
                                        <th>{{ strtoupper(str_replace('_', ' ', $header)) }}</th>
                                    @endforeach
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($lastPreview['rows'] as $row)
                                    <tr>
                                        @foreach($headers as $header)
                                            <td>{{ is_numeric($row[$header] ?? null) ? number_format((float) $row[$header], 2, ',', '.') : ($row[$header] ?? '-') }}</td>
                                        @endforeach
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @endif

                @if(!empty($lastPreview['diagnostics']))
                    <h5>Tanılama</h5>
                    <pre class="bg-light p-3 mb-0" style="white-space: pre-wrap;">{{ json_encode($lastPreview['diagnostics'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) }}</pre>
                @endif
            </div>
        </div>
    @endif
</div>
@endsection
