<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class SettingsController extends Controller
{
    public function notificationSettings(Request $request): JsonResponse
    {
        $user = $request->user();

        if ($request->isMethod('put')) {
            $request->validate([
                'channels'          => 'array',
                'channels.in_app'   => 'boolean',
                'channels.push'     => 'boolean',
                'channels.email'    => 'boolean',
            ]);

            $channels = $request->input('channels', []);

            $updates = [];
            if (isset($channels['in_app'])) $updates['notify_in_app'] = $channels['in_app'];
            if (isset($channels['push']))   $updates['notify_push']   = $channels['push'];
            if (isset($channels['email']))  $updates['notify_email']  = $channels['email'];

            if ($updates) {
                $user->update($updates);
            }

            // Devices aktivieren/deaktivieren je nach Push-Wunsch
            if (isset($channels['push'])) {
                $user->devices()->update(['active' => (bool) $channels['push']]);
            }
        }

        return response()->json([
            'success' => true,
            'data'    => [
                'channels' => [
                    'in_app' => (bool) ($user->notify_in_app ?? true),
                    'push'   => (bool) ($user->notify_push ?? false),
                    'email'  => (bool) ($user->notify_email ?? false),
                ],
            ],
        ]);
    }

    public function credits(Request $request): JsonResponse
    {
        $user = $request->user();

        // Verbrauch aus AgentLogs (das ist die tatsächliche Nutzung).
        // Label-Priorität wie im Web: output.title > input > type.
        $usage = $user->agentLogs()
            ->orderByDesc('created_at')
            ->take(30)
            ->get()
            ->map(fn ($log) => [
                'type'        => $log->type,
                'description' => $log->output['title'] ?? $log->input ?? $log->type,
                'amount'      => -$log->credits,
                'duration_ms' => $log->duration_ms ?? 0,
                'created_at'  => $log->created_at,
            ]);

        // Bonus-Credits aus CreditTransactions
        $bonuses = $user->creditTransactions()
            ->orderByDesc('created_at')
            ->take(10)
            ->get()
            ->map(fn ($tx) => [
                'type'        => $tx->type,
                'description' => $tx->description,
                'amount'      => $tx->amount,
                'created_at'  => $tx->created_at,
            ]);

        // Zusammenführen und nach Datum sortieren
        $transactions = $usage->merge($bonuses)
            ->sortByDesc('created_at')
            ->values()
            ->take(30);

        return response()->json([
            'success' => true,
            'data'    => [
                'credits_used'    => $user->effective_usage,
                'credit_limit'    => $user->effective_limit,
                'bonus_credits'   => $user->bonus_credits,
                'usage_percent'   => $user->usage_percent,
                'transactions'    => $transactions,
            ],
        ]);
    }

    public function affiliate(Request $request): JsonResponse
    {
        $user = $request->user();
        $affiliate = $user->affiliate;

        if (! $affiliate) {
            return response()->json([
                'success' => true,
                'data'    => null,
            ]);
        }

        $referrals = $affiliate->referrals()
            ->with('referredUser')
            ->latest()
            ->get()
            ->map(fn ($r) => [
                'name'            => $r->referredUser?->name ?? 'Unbekannt',
                'registered_at'   => $r->registered_at,
                'qualifies_at'    => $r->qualifies_at,
                'status'          => $r->status,
                'credits_awarded' => $r->credits_awarded,
            ]);

        return response()->json([
            'success' => true,
            'data'    => [
                'code'             => $affiliate->code,
                'referral_link'    => $affiliate->referral_link,
                'referrals_count'  => $affiliate->total_referrals,
                'qualified_count'  => $affiliate->qualified_referrals,
                'credits_earned'   => $affiliate->total_credits_earned,
                'status'           => $affiliate->status,
                'referrals'        => $referrals,
            ],
        ]);
    }

    public function updateProfile(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name'     => 'sometimes|string|max:255',
            'email'    => 'sometimes|email|max:255',
            'locale'   => 'sometimes|in:de,en',
            'timezone' => 'sometimes|string|max:100',
        ]);

        $request->user()->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Profil aktualisiert.',
        ]);
    }

    public function updatePassword(Request $request): JsonResponse
    {
        $request->validate([
            'current_password'      => 'required|string',
            'password'              => ['required', 'confirmed', Password::min(6)],
        ]);

        $user = $request->user();

        if (! Hash::check($request->current_password, $user->password)) {
            return response()->json([
                'success' => false,
                'message' => 'Aktuelles Passwort ist falsch.',
            ], 422);
        }

        $user->update(['password' => Hash::make($request->password)]);

        return response()->json([
            'success' => true,
            'message' => 'Passwort geändert.',
        ]);
    }

    public function deleteAccount(Request $request): JsonResponse
    {
        $user = $request->user();

        // Alle Daten löschen
        $user->events()->delete();
        $user->tasks()->delete();
        $user->notes()->delete();
        $user->contacts()->delete();
        $user->agentLogs()->delete();
        $user->creditTransactions()->delete();
        $user->tokens()->delete();

        if ($user->affiliate) {
            $user->affiliate->referrals()->delete();
            $user->affiliate->creditLogs()->delete();
            $user->affiliate->delete();
        }

        $user->delete();

        return response()->json([
            'success' => true,
            'message' => 'Konto gelöscht.',
        ]);
    }
}
