@extends('layouts.default')
@section('title', $page_title)
@section('content')
@php
    $from = $payload['from'];
    $to = $payload['to'];
    $channels = $payload['channels'];
    $readiness = $payload['readiness'];
    $latestReport = $payload['latest_report'];
@endphp
<div class="container-fluid">
    @include('admin.partials.page-header')

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

    <div class="row">
        <div class="col-xl-3 col-sm-6"><div class="card"><div class="card-body"><h3>{{ $readiness['score'] }}/100</h3><span>Hazırlık Skoru</span></div></div></div>
        <div class="col-xl-3 col-sm-6"><div class="card"><div class="card-body"><h3>{{ $readiness['connection_count'] }}</h3><span>Bağlantı</span></div></div></div>
        <div class="col-xl-3 col-sm-6"><div class="card"><div class="card-body"><h3>{{ $readiness['preview_ok'] }}</h3><span>Önizleme Başarılı</span></div></div></div>
        <div class="col-xl-3 col-sm-6"><div class="card"><div class="card-body"><h3>{{ $readiness['quality_ok'] }}</h3><span>Kalite OK</span></div></div></div>
    </div>

    <div class="row">
        <div class="col-xl-4">
            <div class="card">
                <div class="card-header"><h4 class="card-title mb-0">Müşteri</h4></div>
                <div class="card-body">
                    <h4>{{ $client->company_name }}</h4>
                    <p class="text-muted mb-3">{{ $client->website ?: $client->email ?: '-' }}</p>
                    <dl class="row mb-0">
                        <dt class="col-5">Onboarding</dt><dd class="col-7"><span class="badge {{ $client->onboardingBadgeClass() }}">{{ $client->onboardingStatusLabel() }}</span></dd>
                        <dt class="col-5">Şablon</dt><dd class="col-7">{{ $payload['template']?->name ?: '-' }}</dd>
                        <dt class="col-5">Tarih</dt><dd class="col-7">{{ $from }} / {{ $to }}</dd>
                        <dt class="col-5">Kanallar</dt><dd class="col-7">{{ implode(', ', array_map(fn($v) => strtoupper(str_replace('_', ' ', $v)), $channels)) }}</dd>
                    </dl>
                    <a href="{{ route('admin.onboarding.summary', $client) }}" class="btn btn-outline-primary btn-sm mt-3">Onboarding Özet</a>
                    <a href="{{ route('admin.clients.show', $client) }}" class="btn btn-outline-dark btn-sm mt-3">Müşteri Kartı</a>
                </div>
            </div>

            @if($latestReport)
            <div class="card">
                <div class="card-header"><h4 class="card-title mb-0">Son Rapor</h4></div>
                <div class="card-body">
                    <div><strong>#{{ $latestReport->id }}</strong> · {{ $latestReport->report_type }}</div>
                    <div class="text-muted">{{ optional($latestReport->date_from)->format('d.m.Y') }} - {{ optional($latestReport->date_to)->format('d.m.Y') }}</div>
                    <div class="mt-2"><span class="badge badge-{{ $latestReport->status === 'completed' ? 'success' : ($latestReport->status === 'failed' ? 'danger' : 'warning') }}">{{ $latestReport->status }}</span></div>
                    <a href="{{ route('admin.reports.show', $latestReport) }}" class="btn btn-sm btn-primary mt-3">Rapor Detayına Git</a>
                </div>
            </div>
            @endif
        </div>

        <div class="col-xl-8">
            <div class="card">
                <div class="card-header"><h4 class="card-title mb-0">İlk Rapor Akışı</h4></div>
                <div class="card-body">
                    <form method="POST" action="{{ route('admin.first-report.run-all', $client) }}" class="row g-3">
                        @csrf
                        <div class="col-md-3">
                            <label class="form-label">Başlangıç</label>
                            <input type="date" name="date_from" value="{{ $from }}" class="form-control" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Bitiş</label>
                            <input type="date" name="date_to" value="{{ $to }}" class="form-control" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Rapor Tipi</label>
                            <select name="report_type" class="form-control">
                                @foreach(['daily' => 'Günlük', 'weekly' => 'Haftalık', 'monthly' => 'Aylık', 'custom' => 'Özel'] as $key => $label)
                                    <option value="{{ $key }}" @selected($payload['report_type'] === $key)>{{ $label }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Satır Limit</label>
                            <input type="number" name="limit" value="10" min="1" max="50" class="form-control">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Rapor Şablonu</label>
                            <select name="report_template_id" class="form-control">
                                <option value="">Otomatik seç</option>
                                @foreach($payload['templates'] as $template)
                                    <option value="{{ $template->id }}" @selected($payload['template']?->id === $template->id)>{{ $template->name }} · {{ $template->type }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Test Mail Alıcısı</label>
                            <input type="text" name="test_recipient" value="{{ $client->email }}" class="form-control" placeholder="mail@site.com">
                        </div>

                        <div class="col-12">
                            <label class="form-label d-block">Kanallar</label>
                            @foreach(['google_ads' => 'Google Ads', 'meta_ads' => 'Meta Ads', 'search_console' => 'Search Console', 'ga4' => 'GA4'] as $key => $label)
                                <label class="me-3"><input type="checkbox" name="channels[]" value="{{ $key }}" @checked(in_array($key, $channels, true))> {{ $label }}</label>
                            @endforeach
                        </div>

                        <div class="col-12">
                            <label class="form-label d-block">Çalıştırılacak Adımlar</label>
                            <label class="me-3"><input type="checkbox" name="run_preview" value="1" checked> Canlı önizleme</label>
                            <label class="me-3"><input type="checkbox" name="run_sync" value="1" checked> Snapshot çek</label>
                            <label class="me-3"><input type="checkbox" name="run_quality" value="1" checked> Kalite kontrol</label>
                            <label class="me-3"><input type="checkbox" name="run_report" value="1" checked> Rapor üret</label>
                            <label class="me-3"><input type="checkbox" name="run_ai" value="1" checked> AI yorumu</label>
                            <label class="me-3"><input type="checkbox" name="send_test" value="1"> Test maili gönder</label>
                        </div>

                        <div class="col-12">
                            <label class="form-label d-block">Ekler</label>
                            <label class="me-3"><input type="checkbox" name="include_pdf" value="1" checked> PDF / HTML</label>
                            <label class="me-3"><input type="checkbox" name="include_excel" value="1"> Excel</label>
                            <label class="me-3"><input type="checkbox" name="include_csv" value="1"> CSV</label>
                            <label class="me-3"><input type="checkbox" name="include_html" value="1" checked> HTML fallback</label>
                        </div>

                        <div class="col-12">
                            <label class="form-label d-block">Bağlantılar</label>
                            @foreach($payload['connections'] as $connection)
                                <label class="d-block border rounded p-2 mb-2">
                                    <input type="checkbox" name="connection_ids[]" value="{{ $connection['id'] }}" checked>
                                    <strong>{{ $connection['platform_label'] }}</strong> · {{ $connection['name'] }}
                                    <span class="badge badge-{{ $connection['has_credential'] ? 'success' : 'warning' }} ms-2">{{ $connection['has_credential'] ? 'Token var' : 'Token yok' }}</span>
                                    @if($connection['last_quality_status'])
                                        <span class="badge badge-{{ $connection['last_quality_status'] === 'ok' ? 'success' : ($connection['last_quality_status'] === 'warning' ? 'warning' : 'danger') }} ms-1">Kalite: {{ $connection['last_quality_score'] }}/100</span>
                                    @endif
                                </label>
                            @endforeach
                        </div>

                        <div class="col-12 d-flex gap-2 flex-wrap">
                            <button class="btn btn-primary">Tüm İlk Rapor Akışını Çalıştır</button>
                            <button formaction="{{ route('admin.first-report.preview', $client) }}" class="btn btn-outline-info">Sadece Önizle</button>
                            <button formaction="{{ route('admin.first-report.sync', $client) }}" class="btn btn-outline-warning">Sadece Snapshot Çek</button>
                            <button formaction="{{ route('admin.first-report.quality', $client) }}" class="btn btn-outline-dark">Sadece Kalite Kontrol</button>
                            <button formaction="{{ route('admin.first-report.generate', $client) }}" class="btn btn-outline-success">Sadece Rapor Üret</button>
                        </div>
                    </form>
                </div>
            </div>

            @if($lastResult)
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="card-title mb-0">Son Çalıştırma Sonucu</h4>
                        <span class="badge badge-{{ !empty($lastResult['ok']) ? 'success' : 'warning' }}">{{ !empty($lastResult['ok']) ? 'Başarılı' : 'Kontrol Gerekli' }}</span>
                    </div>
                    <div class="card-body">
                        @if(!empty($lastResult['error']))
                            <div class="alert alert-danger">{{ $lastResult['error'] }}</div>
                        @endif

                        @if(!empty($lastResult['steps']))
                            <div class="row g-3">
                                @foreach($lastResult['steps'] as $step => $stepResult)
                                    <div class="col-md-6">
                                        <div class="border rounded p-3 h-100">
                                            <h5 class="mb-2">{{ strtoupper(str_replace('_', ' ', $step)) }}</h5>
                                            <span class="badge badge-{{ !empty($stepResult['ok']) ? 'success' : 'danger' }}">{{ !empty($stepResult['ok']) ? 'OK' : 'Kontrol' }}</span>
                                            @if(isset($stepResult['success_count']))
                                                <div class="text-muted mt-2">Başarılı: {{ $stepResult['success_count'] }} · Hatalı: {{ $stepResult['error_count'] }}</div>
                                            @endif
                                            @if(!empty($stepResult['report_id']))
                                                <div class="mt-2"><a href="{{ route('admin.reports.show', $stepResult['report_id']) }}" class="btn btn-xs btn-primary">Rapor #{{ $stepResult['report_id'] }}</a></div>
                                            @endif
                                            @if(!empty($stepResult['error']))
                                                <div class="text-danger small mt-2">{{ $stepResult['error'] }}</div>
                                            @endif
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        @elseif(!empty($lastResult['items']))
                            <div class="table-responsive">
                                <table class="table table-bordered align-middle">
                                    <thead><tr><th>Platform</th><th>Bağlantı</th><th>Durum</th><th>Mesaj</th><th>Satır</th></tr></thead>
                                    <tbody>
                                    @foreach($lastResult['items'] as $item)
                                        <tr>
                                            <td>{{ strtoupper(str_replace('_', ' ', $item['platform'] ?? '-')) }}</td>
                                            <td>{{ $item['connection_name'] ?? '-' }}</td>
                                            <td><span class="badge badge-{{ !empty($item['ok']) ? 'success' : 'danger' }}">{{ !empty($item['ok']) ? 'OK' : 'Hata' }}</span></td>
                                            <td>{{ $item['message'] ?? $item['error'] ?? '-' }}</td>
                                            <td>{{ $item['total_rows'] ?? count($item['rows'] ?? []) }}</td>
                                        </tr>
                                    @endforeach
                                    </tbody>
                                </table>
                            </div>
                        @else
                            <pre class="bg-light p-3 rounded">{{ json_encode($lastResult, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) }}</pre>
                        @endif
                    </div>
                </div>
            @endif
        </div>
    </div>
</div>
@endsection
