@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">Kalite Kontrol Filtresi</h4>
        </div>
        <div class="card-body">
            <form method="GET" action="{{ route('admin.sync.quality') }}" 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) $filters['client_id'] === (string) $client->id)>{{ $client->company_name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-lg-2">
                    <label class="form-label">Platform</label>
                    <select name="platform" class="form-control">
                        <option value="">Tümü</option>
                        @foreach(['google_ads' => 'Google Ads', 'meta_ads' => 'Meta Ads', 'search_console' => 'Search Console', 'ga4' => 'GA4'] as $key => $label)
                            <option value="{{ $key }}" @selected($filters['platform'] === $key)>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-lg-3">
                    <label class="form-label">Bağlantı</label>
                    <select name="connection_id" class="form-control">
                        <option value="">Tüm bağlantılar</option>
                        @foreach($connections as $connection)
                            <option value="{{ $connection->id }}" @selected((string) $filters['connection_id'] === (string) $connection->id)>
                                #{{ $connection->id }} · {{ strtoupper(str_replace('_', ' ', $connection->platform)) }} · {{ $connection->connection_name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-lg-2">
                    <label class="form-label">Başlangıç</label>
                    <input type="date" name="from" class="form-control" value="{{ $filters['from'] }}">
                </div>
                <div class="col-lg-2">
                    <label class="form-label">Bitiş</label>
                    <input type="date" name="to" class="form-control" value="{{ $filters['to'] }}">
                </div>
                <div class="col-lg-3">
                    <label class="form-label d-block">Sonucu Kaydet</label>
                    <label class="form-check form-switch mb-0">
                        <input type="checkbox" name="save" value="1" class="form-check-input">
                        <span class="form-check-label">Bağlantı meta alanına yaz</span>
                    </label>
                </div>
                <div class="col-lg-3">
                    <button class="btn btn-primary w-100">Kalite Kontrolü Çalıştır</button>
                </div>
            </form>
        </div>
    </div>

    @php($summary = $report['summary'])
    <div class="row">
        <div class="col-xl-2 col-sm-6">
            <div class="card"><div class="card-body"><p class="text-muted mb-1">Bağlantı</p><h3 class="mb-0">{{ number_format($summary['connections'], 0, ',', '.') }}</h3></div></div>
        </div>
        <div class="col-xl-2 col-sm-6">
            <div class="card"><div class="card-body"><p class="text-muted mb-1">Hazır</p><h3 class="mb-0 text-success">{{ number_format($summary['ok'], 0, ',', '.') }}</h3></div></div>
        </div>
        <div class="col-xl-2 col-sm-6">
            <div class="card"><div class="card-body"><p class="text-muted mb-1">Kontrol</p><h3 class="mb-0 text-warning">{{ number_format($summary['warning'], 0, ',', '.') }}</h3></div></div>
        </div>
        <div class="col-xl-2 col-sm-6">
            <div class="card"><div class="card-body"><p class="text-muted mb-1">Sorun</p><h3 class="mb-0 text-danger">{{ number_format($summary['danger'], 0, ',', '.') }}</h3></div></div>
        </div>
        <div class="col-xl-2 col-sm-6">
            <div class="card"><div class="card-body"><p class="text-muted mb-1">Snapshot Satırı</p><h3 class="mb-0">{{ number_format($summary['rows'], 0, ',', '.') }}</h3></div></div>
        </div>
        <div class="col-xl-2 col-sm-6">
            <div class="card"><div class="card-body"><p class="text-muted mb-1">Ortalama Skor</p><h3 class="mb-0">{{ number_format($summary['average_score'], 1, ',', '.') }}</h3></div></div>
        </div>
    </div>

    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <div>
                <h4 class="card-title mb-0">Bağlantı Kalite Sonuçları</h4>
                <small class="text-muted">{{ $report['from'] }} / {{ $report['to'] }} aralığı · beklenen gün: {{ $report['expected_days'] }}</small>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Müşteri</th>
                            <th>Platform</th>
                            <th>Bağlantı</th>
                            <th>Durum</th>
                            <th>Skor</th>
                            <th>Satır</th>
                            <th>Eksik Gün</th>
                            <th>Son Veri</th>
                            <th style="width:180px;">İşlem</th>
                        </tr>
                    </thead>
                    <tbody>
                    @forelse($report['items'] as $item)
                        @php
                            $badgeClass = $item['status'] === 'ok' ? 'badge-success' : ($item['status'] === 'warning' ? 'badge-warning' : 'badge-danger');
                            $collapseId = 'quality-'.$item['connection_id'];
                        @endphp
                        <tr>
                            <td>{{ $item['client_name'] }}</td>
                            <td>{{ $item['platform_label'] }}</td>
                            <td>
                                <strong>{{ $item['connection_name'] }}</strong><br>
                                <small class="text-muted">{{ $item['account_id'] ?: 'Hesap ID yok' }}</small>
                            </td>
                            <td><span class="badge {{ $badgeClass }}">{{ $item['status_label'] }}</span></td>
                            <td><strong>{{ $item['score'] }}/100</strong></td>
                            <td>{{ number_format($item['total_rows'], 0, ',', '.') }}</td>
                            <td>{{ number_format($item['missing_days_total'], 0, ',', '.') }}</td>
                            <td>{{ $item['latest_snapshot_date'] ?: '-' }}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#{{ $collapseId }}">Detay</button>
                                <form method="POST" action="{{ route('admin.sync.quality.connection', $item['connection_id']) }}" class="d-inline">
                                    @csrf
                                    <input type="hidden" name="from" value="{{ $report['from'] }}">
                                    <input type="hidden" name="to" value="{{ $report['to'] }}">
                                    <input type="hidden" name="save" value="1">
                                    <button class="btn btn-sm btn-outline-success">Kaydet</button>
                                </form>
                            </td>
                        </tr>
                        <tr class="collapse" id="{{ $collapseId }}">
                            <td colspan="9" class="bg-light">
                                @if(!empty($item['messages']))
                                    <div class="alert {{ $item['status'] === 'danger' ? 'alert-danger' : 'alert-warning' }} mb-3">
                                        <strong>Tanılama:</strong>
                                        <ul class="mb-0 mt-2">
                                            @foreach($item['messages'] as $message)
                                                <li>{{ $message }}</li>
                                            @endforeach
                                        </ul>
                                    </div>
                                @endif

                                <div class="table-responsive">
                                    <table class="table table-bordered bg-white mb-0">
                                        <thead>
                                            <tr>
                                                <th>Tablo</th>
                                                <th>Durum</th>
                                                <th>Satır</th>
                                                <th>Tarih</th>
                                                <th>Eksik Gün</th>
                                                <th>Toplamlar</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        @foreach($item['table_checks'] as $check)
                                            @php($checkBadge = $check['status'] === 'ok' ? 'badge-success' : ($check['status'] === 'warning' ? 'badge-warning' : 'badge-danger'))
                                            <tr>
                                                <td>
                                                    <strong>{{ $check['label'] }}</strong><br>
                                                    <small class="text-muted">{{ $check['table'] }}</small>
                                                </td>
                                                <td><span class="badge {{ $checkBadge }}">{{ $check['status'] }}</span></td>
                                                <td>{{ number_format($check['row_count'], 0, ',', '.') }}</td>
                                                <td>{{ $check['first_date'] ?: '-' }} / {{ $check['latest_date'] ?: '-' }}</td>
                                                <td>
                                                    {{ count($check['missing_dates']) }}
                                                    @if(!empty($check['missing_dates']))
                                                        <br><small class="text-muted">{{ implode(', ', array_slice($check['missing_dates'], 0, 8)) }}{{ count($check['missing_dates']) > 8 ? '...' : '' }}</small>
                                                    @endif
                                                </td>
                                                <td>
                                                    @forelse($check['totals'] as $metric => $value)
                                                        <span class="d-inline-block me-2"><small>{{ $metric }}:</small> <strong>{{ number_format((float) $value, 2, ',', '.') }}</strong></span>
                                                    @empty
                                                        <span class="text-muted">-</span>
                                                    @endforelse
                                                    @if(!empty($check['zero_metric_dates']))
                                                        <br><small class="text-warning">Sıfır metrik günleri: {{ implode(', ', array_slice($check['zero_metric_dates'], 0, 5)) }}{{ count($check['zero_metric_dates']) > 5 ? '...' : '' }}</small>
                                                    @endif
                                                </td>
                                            </tr>
                                        @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr><td colspan="9" class="text-center text-muted py-4">Filtreye uygun bağlantı bulunamadı.</td></tr>
                    @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
@endsection
