<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BrandKit;
use App\Models\Client;
use App\Models\ReportTemplate;
use App\Services\Onboarding\ClientOnboardingService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ClientOnboardingController extends Controller
{
    public function __construct(private readonly ClientOnboardingService $onboarding)
    {
    }

    public function index(Request $request): View
    {
        $status = $request->string('status')->toString();

        $clients = Client::query()
            ->withCount(['platformConnections', 'reportSchedules', 'brandKits'])
            ->when($status, fn ($query) => $query->where('onboarding_status', $status))
            ->orderByRaw("FIELD(onboarding_status, 'in_progress', 'needs_review', 'not_started', 'completed')")
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return view('admin.onboarding.index', [
            'page_title' => 'Müşteri Onboarding',
            'page_description' => 'Müşteriyi, API bağlantılarını, marka kitini ve otomatik rapor planını tek akışta hazırlayın.',
            'clients' => $clients,
            'stats' => [
                'not_started' => Client::where('onboarding_status', 'not_started')->count(),
                'in_progress' => Client::where('onboarding_status', 'in_progress')->count(),
                'completed' => Client::where('onboarding_status', 'completed')->count(),
                'needs_review' => Client::where('onboarding_status', 'needs_review')->count(),
            ],
        ]);
    }

    public function start(Request $request): View
    {
        $client = $request->filled('client_id') ? Client::find($request->integer('client_id')) : null;

        return view('admin.onboarding.step-client', [
            'page_title' => $client ? 'Onboarding Devam Et' : 'Yeni Müşteri Onboarding',
            'page_description' => 'İlk adımda müşteri ve rapor alıcı bilgilerini netleştirelim.',
            'client' => $client,
            'clients' => Client::orderBy('company_name')->get(),
            'progress' => $this->onboarding->progress($client),
        ]);
    }

    public function saveClient(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'client_id' => ['nullable', 'integer', 'exists:clients,id'],
            'company_name' => ['required', 'string', 'max:255'],
            'contact_person' => ['nullable', 'string', 'max:255'],
            'email' => ['nullable', 'email', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'website' => ['nullable', 'string', 'max:255'],
            'sector' => ['nullable', 'string', 'max:120'],
            'status' => ['nullable', 'string', 'max:30'],
            'currency_code' => ['nullable', 'string', 'size:3'],
            'timezone' => ['nullable', 'string', 'max:80'],
            'report_language' => ['nullable', 'string', 'max:5'],
            'primary_color' => ['nullable', 'string', 'max:20'],
            'report_recipients' => ['nullable', 'string'],
            'notes' => ['nullable', 'string'],
            'internal_notes' => ['nullable', 'string'],
        ]);

        $client = $request->filled('client_id') ? Client::findOrFail($request->integer('client_id')) : null;
        $client = $this->onboarding->saveClient($validated, $client);

        return redirect()
            ->route('admin.onboarding.integrations', $client)
            ->with('success', 'Müşteri bilgileri kaydedildi. Şimdi bağlantıları hazırlayalım.');
    }

    public function integrations(Client $client): View
    {
        return view('admin.onboarding.step-integrations', [
            'page_title' => 'API Bağlantıları',
            'page_description' => 'Müşteri için kullanılacak Google Ads, Meta, Search Console ve GA4 bağlantılarını seçin.',
            'client' => $client->load('platformConnections'),
            'platforms' => $this->onboarding->platforms(),
            'progress' => $this->onboarding->progress($client),
        ]);
    }

    public function saveIntegrations(Request $request, Client $client): RedirectResponse
    {
        $validated = $request->validate([
            'platforms' => ['nullable', 'array'],
            'platforms.*.enabled' => ['nullable'],
            'platforms.*.connection_name' => ['nullable', 'string', 'max:255'],
            'platforms.*.account_id' => ['nullable', 'string', 'max:255'],
            'platforms.*.account_name' => ['nullable', 'string', 'max:255'],
            'platforms.*.note' => ['nullable', 'string', 'max:500'],
        ]);

        $this->onboarding->saveConnections($client, $validated);

        return redirect()
            ->route('admin.onboarding.brand', $client)
            ->with('success', 'Bağlantı iskeletleri oluşturuldu. Hesap keşfi/OAuth adımlarını sonradan tamamlayabiliriz.');
    }

    public function brand(Client $client): View
    {
        return view('admin.onboarding.step-brand', [
            'page_title' => 'Marka Kiti',
            'page_description' => 'PDF/HTML raporun logo, renk ve kapak kimliğini hazırlayın.',
            'client' => $client,
            'brandKits' => BrandKit::whereNull('client_id')->orWhere('client_id', $client->id)->orderBy('client_id')->orderBy('name')->get(),
            'progress' => $this->onboarding->progress($client),
        ]);
    }

    public function saveBrand(Request $request, Client $client): RedirectResponse
    {
        $validated = $request->validate([
            'brand_kit_id' => ['nullable', 'integer', 'exists:brand_kits,id'],
            'name' => ['nullable', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
            'agency_name' => ['nullable', 'string', 'max:255'],
            'agency_logo_url' => ['nullable', 'string', 'max:500'],
            'client_logo_url' => ['nullable', 'string', 'max:500'],
            'primary_color' => ['nullable', 'string', 'max:20'],
            'accent_color' => ['nullable', 'string', 'max:20'],
            'secondary_color' => ['nullable', 'string', 'max:20'],
            'text_color' => ['nullable', 'string', 'max:20'],
            'muted_color' => ['nullable', 'string', 'max:20'],
            'cover_style' => ['nullable', 'string', 'max:50'],
            'footer_note' => ['nullable', 'string'],
            'contact_email' => ['nullable', 'email', 'max:255'],
            'contact_phone' => ['nullable', 'string', 'max:80'],
            'website_url' => ['nullable', 'string', 'max:255'],
        ]);

        $this->onboarding->saveBrandKit($client, $validated);

        return redirect()
            ->route('admin.onboarding.report', $client)
            ->with('success', 'Marka kiti hazır. Şimdi otomatik rapor planını oluşturalım.');
    }

    public function report(Client $client): View
    {
        return view('admin.onboarding.step-report', [
            'page_title' => 'Rapor Planı',
            'page_description' => 'Müşteriye gönderilecek otomatik rapor periyodunu ve eklerini ayarlayın.',
            'client' => $client,
            'templates' => ReportTemplate::whereNull('client_id')->orWhere('client_id', $client->id)->active()->orderBy('sort_order')->orderBy('name')->get(),
            'platforms' => $this->onboarding->platforms(),
            'progress' => $this->onboarding->progress($client),
        ]);
    }

    public function saveReport(Request $request, Client $client): RedirectResponse
    {
        $validated = $request->validate([
            'report_template_id' => ['nullable', 'integer', 'exists:report_templates,id'],
            'report_type' => ['required', 'in:daily,weekly,monthly'],
            'frequency' => ['required', 'in:daily,weekly,monthly'],
            'channels' => ['nullable', 'array'],
            'channels.*' => ['string'],
            'daily_time' => ['nullable', 'date_format:H:i'],
            'weekly_day' => ['nullable', 'integer', 'between:1,7'],
            'monthly_day' => ['nullable', 'integer', 'between:1,28'],
            'recipients' => ['nullable', 'string'],
            'cc' => ['nullable', 'string'],
            'bcc' => ['nullable', 'string'],
            'include_pdf' => ['nullable'],
            'include_excel' => ['nullable'],
            'is_active' => ['nullable'],
        ]);

        $this->onboarding->saveReportPlan($client, $validated);

        return redirect()
            ->route('admin.onboarding.summary', $client)
            ->with('success', 'Rapor planı oluşturuldu. Son kontrolü yapıp onboarding’i tamamlayabiliriz.');
    }

    public function summary(Client $client): View
    {
        return view('admin.onboarding.summary', [
            'page_title' => 'Onboarding Son Kontrol',
            'page_description' => 'Müşteri paneli, bağlantılar, marka kiti ve rapor planını kontrol edin.',
            'client' => $client->load(['platformConnections', 'brandKits', 'reportSchedules.template']),
            'summary' => $this->onboarding->summary($client),
            'progress' => $this->onboarding->progress($client),
        ]);
    }

    public function complete(Client $client): RedirectResponse
    {
        $this->onboarding->complete($client);

        return redirect()
            ->route('admin.clients.show', $client)
            ->with('success', 'Müşteri onboarding tamamlandı. Artık veri önizleme, kalite kontrol ve rapor üretimine geçebiliriz.');
    }
}
