<?php

namespace App\Http\Controllers;

use App\Mail\PvConfigurationCopy;
use App\Mail\PvConfigurationInternal;
use App\Models\Inquiry;
use App\Models\Service;
use App\Support\ServiceConfigurator;
use App\Support\PvConfigurator;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class PvConfiguratorController extends Controller
{
    public function create(): View
    {
        return view('services.pv-configurator', [
            'steps' => PvConfigurator::steps(),
            'configuratorServices' => Service::published()->orderBy('sort_order')->get()->filter(fn (Service $service) => ServiceConfigurator::available($service)),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        if ($request->filled('website')) {
            return redirect()->route('pv-configurator.success');
        }

        $validated = $request->validate($this->rules($request), [
            'consent.accepted' => 'Bitte bestätigen Sie die Datenschutzhinweise.',
            'building_type.required' => 'Bitte wählen Sie eine Gebäudeart.',
            'roof_sides.required_unless' => 'Bitte wählen Sie die Anzahl der nutzbaren Dachseiten.',
        ]);

        if ($validated['roof_type'] !== 'Sonstige (bitte spezifizieren)') {
            $validated['other_roof_type'] = null;
        }

        if (! in_array('Sonstige (bitte spezifizieren)', $validated['energy_usage'] ?? [], true)) {
            $validated['other_energy_usage'] = null;
        }

        if (in_array($validated['roof_shape'], ['Flachdach', 'Pultdach'], true)) {
            $validated['roof_sides'] = null;
        }

        $configuration = collect($validated)->except([
            'name', 'email', 'phone', 'street', 'street_number', 'postal_code', 'city', 'consent',
        ])->all();

        $inquiry = Inquiry::query()->create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'] ?? null,
            'street' => $validated['street'] ?? null,
            'street_number' => $validated['street_number'] ?? null,
            'postal_code' => $validated['postal_code'] ?? null,
            'city' => $validated['city'] ?? null,
            'audience' => $validated['building_type'],
            'topics' => ['Photovoltaik'],
            'configuration' => $configuration,
            'message' => PvConfigurator::plainSummary($configuration),
            'status' => 'neu',
            'source' => 'photovoltaik-konfigurator',
            'ip_hash' => hash('sha256', (string) $request->ip().config('app.key')),
            'consent_at' => now(),
        ]);

        try {
            Mail::to(config('mail.contact_address', 'info@energietec.plus'))
                ->send(new PvConfigurationInternal($inquiry));
        } catch (\Throwable $exception) {
            Log::warning('PV-Konfiguration gespeichert, interne Benachrichtigung konnte nicht gesendet werden.', ['inquiry_id' => $inquiry->id, 'exception' => $exception->getMessage()]);
        }

        $copySent = false;

        try {
            Mail::to($inquiry->email, $inquiry->name)
                ->send(new PvConfigurationCopy($inquiry));
            $inquiry->forceFill(['customer_copy_sent_at' => now()])->save();
            $copySent = true;
        } catch (\Throwable $exception) {
            Log::warning('PV-Konfiguration gespeichert, Kundenkopie konnte nicht gesendet werden.', ['inquiry_id' => $inquiry->id, 'exception' => $exception->getMessage()]);
        }

        return redirect()->route('pv-configurator.success')->with([
            'pv_configurator_success' => true,
            'pv_customer_copy_sent' => $copySent,
        ]);
    }

    public function success(): View|RedirectResponse
    {
        if (! session('pv_configurator_success')) {
            return redirect()->route('pv-configurator.create');
        }

        return view('services.pv-configurator-success');
    }

    private function rules(Request $request): array
    {
        $in = fn (array $values) => Rule::in($values);

        return [
            'website' => ['nullable', 'string', 'max:200'],
            'building_status' => ['required', $in(['Neubau', 'Bestandsgebäude'])],
            'building_type' => ['required', $in(['Freistehendes Haus', 'Reihenhaus', 'Unternehmensgebäude', 'Hallen und Industriegebäude'])],
            'roof_shape' => ['required', $in(['Flachdach', 'Pultdach', 'Satteldach', 'Walmdach', 'Zeltdach'])],
            'roof_sides' => [Rule::requiredIf(fn () => ! in_array($request->input('roof_shape'), ['Flachdach', 'Pultdach'], true)), 'nullable', $in(['Eine', 'Zwei', 'Drei', 'Vier', 'Ich wünsche eine individuelle Beratung'])],
            'roof_size' => ['required', $in(['Klein ca. 20m²', 'Mittel ca. 30m²', 'Groß ca. 45m²', 'Sehr groß ca. 60m²', 'Ich wünsche eine individuelle Beratung'])],
            'roof_type' => ['required', $in(['Dachziegel / Dachpfannen', 'Schiefer', 'Bitumen', 'Trapezblech / Wellblech', 'Folie', 'Sonstige (bitte spezifizieren)'])],
            'other_roof_type' => [Rule::requiredIf(fn () => $request->input('roof_type') === 'Sonstige (bitte spezifizieren)'), 'nullable', 'string', 'max:150'],
            'roof_angle' => ['required', $in(['Ca. 15°', 'Ca. 30°', 'Ca. 45°', 'Ca. 60°'])],
            'roof_direction' => ['nullable', $in(['Südlich', 'Östlich / Westlich', 'Nördlich'])],
            'natural_roof_barrier' => ['required', $in(['Nein', 'Ja'])],
            'building_roof_barrier' => ['required', $in(['Nein', 'Ja'])],
            'structure_roof_barrier' => ['required', $in(['Nein', 'Ja'])],
            'installation_roof_barrier' => ['required', $in(['Nein', 'Ja'])],
            'security_roof_barrier' => ['required', $in(['Nein', 'Ja'])],
            'other_roof_barrier' => ['required', $in(['Nein', 'Ja'])],
            'amount_of_users' => ['nullable', $in(['1-2 Personen', '3-4 Personen', '5-7 Personen', 'Mehr als 7 Personen'])],
            'power_consume' => ['nullable', 'integer', 'min:0', 'max:10000000'],
            'energy_usage' => ['nullable', 'array', 'max:6'],
            'energy_usage.*' => ['string', $in(['Wärmepumpe', 'Klimaanlage', 'Lüftungsanlage', 'Elektrofahrzeug (Wallbox, Ladesäule, etc.)', 'Nachtspeicherheizung', 'Sonstige (bitte spezifizieren)'])],
            'other_energy_usage' => [Rule::requiredIf(fn () => in_array('Sonstige (bitte spezifizieren)', $request->input('energy_usage', []), true)), 'nullable', 'string', 'max:300'],
            'energy_storage' => ['nullable', $in(['Batteriespeicher (Speicherung elektrischer Energie)', 'Ich benötige keinen Speicher', 'Ich wünsche eine individuelle Beratung'])],
            'name' => ['required', 'string', 'max:120'],
            'phone' => ['nullable', 'string', 'max:60'],
            'email' => ['required', 'email:rfc', 'max:190'],
            'street' => ['nullable', 'string', 'max:160'],
            'street_number' => ['nullable', 'string', 'max:30'],
            'postal_code' => ['nullable', 'string', 'max:20'],
            'city' => ['nullable', 'string', 'max:120'],
            'consent' => ['accepted'],
        ];
    }
}
