<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\ConsultantApplication;
use App\Models\ConsultantProfile;
use App\Models\Permission;
use App\Notifications\ConsultantApplicationReviewedNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

/**
 * Bireysel "Danışman Ol" başvurularının (consultant_applications) admin incelemesi.
 * Onay → başvurana ConsultantProfile açılır (varsa güncellenir), AGENT izinleri verilir.
 * Red → gerekçe saklanır, başvuran yeniden başvurabilir.
 * (Firma tarafından açılan hesapların onayı ayrı: ConsultantProfilesController.)
 */
class ConsultantApplicationsController extends Controller
{
    private const RELATIONS = [
        'user:id,name,email',
        'company:id,name,slug,logo,city,country',
        'reviewer:id,name',
    ];

    public function index(Request $request)
    {
        $status = $request->query('status', ConsultantApplication::APPLICATION_PENDING_STATUS);

        $query = ConsultantApplication::query()
            ->with(self::RELATIONS)
            ->latest('id');

        if (in_array($status, [
            ConsultantApplication::APPLICATION_PENDING_STATUS,
            ConsultantApplication::APPLICATION_APPROVED_STATUS,
            ConsultantApplication::APPLICATION_REJECTED_STATUS,
        ], true)) {
            $query->where('status', $status);
        }

        if ($request->filled('search')) {
            $search = $request->query('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%")
                    ->orWhere('city', 'like', "%{$search}%");
            });
        }

        $paginator = $query->paginate(20)->withQueryString();

        // Sekme rozetleri için durum sayaçları (tek sorgu).
        $counts = ConsultantApplication::query()
            ->selectRaw('status, COUNT(*) as total')
            ->groupBy('status')
            ->pluck('total', 'status');

        return response()->json([
            'data' => $paginator->items(),
            'meta' => [
                'current_page' => $paginator->currentPage(),
                'last_page' => $paginator->lastPage(),
                'per_page' => $paginator->perPage(),
                'total' => $paginator->total(),
            ],
            'counts' => [
                'pending' => (int) ($counts['pending'] ?? 0),
                'approved' => (int) ($counts['approved'] ?? 0),
                'rejected' => (int) ($counts['rejected'] ?? 0),
            ],
        ]);
    }

    public function show(ConsultantApplication $application)
    {
        return response()->json([
            'data' => $application->load(self::RELATIONS),
        ]);
    }

    public function approve(Request $request, ConsultantApplication $application)
    {
        $this->ensurePending($application);

        $applicant = $application->user;

        if (! $applicant) {
            throw ValidationException::withMessages([
                'application' => ['Başvuru sahibinin hesabı bulunamadı (silinmiş olabilir).'],
            ]);
        }

        DB::transaction(function () use ($request, $application, $applicant) {
            $application->loadMissing('company');

            $payload = [
                'user_id' => $applicant->id,
                'company_id' => $application->company_id,
                // Public profilde görünen ofis adı: bağlı firma varsa onun adı.
                'company_name' => $application->company?->name,
                'phone' => $application->phone,
                'city' => $application->city,
                'district' => $application->district,
                'bio' => $application->bio,
                'website_url' => $application->website,
                'instagram_url' => $this->normalizeInstagram($application->instagram),
                'linkedin_url' => $application->linkedin,
                'application_status' => ConsultantProfile::STATUS_APPROVED,
                'rejection_reason' => null,
                'applied_at' => $application->created_at,
                'is_active' => true,
            ];

            $profile = $applicant->consultantProfile;

            if ($profile) {
                // Eski (reddedilmiş/pasif) profil varsa üzerine yazılır, slug korunur.
                $profile->update($payload);
            } else {
                $payload['slug'] = $this->uniqueSlug($application->name);
                $payload['is_verified'] = false;
                ConsultantProfile::create($payload);
            }

            $permissionIds = Permission::whereIn('key', ConsultantProfile::AGENT_PERMISSION_KEYS)
                ->pluck('id')
                ->all();

            $applicant->permissions()->syncWithoutDetaching($permissionIds);

            $application->update([
                'status' => ConsultantApplication::APPLICATION_APPROVED_STATUS,
                'rejection_reason' => null,
                'reviewed_at' => now(),
                'reviewed_by' => $request->user()->id,
            ]);
        });

        $applicant->notify(new ConsultantApplicationReviewedNotification($application->fresh()));

        return response()->json([
            'data' => $application->fresh(self::RELATIONS),
        ]);
    }

    public function reject(Request $request, ConsultantApplication $application)
    {
        $this->ensurePending($application);

        $data = $request->validate([
            'rejection_reason' => ['required', 'string', 'max:1000'],
        ]);

        $application->update([
            'status' => ConsultantApplication::APPLICATION_REJECTED_STATUS,
            'rejection_reason' => $data['rejection_reason'],
            'reviewed_at' => now(),
            'reviewed_by' => $request->user()->id,
        ]);

        $application->user?->notify(new ConsultantApplicationReviewedNotification($application->fresh()));

        return response()->json([
            'data' => $application->fresh(self::RELATIONS),
        ]);
    }

    /** Yalnızca incelemedeki başvuru karara bağlanır; ikinci karar 422. */
    private function ensurePending(ConsultantApplication $application): void
    {
        if ($application->status !== ConsultantApplication::APPLICATION_PENDING_STATUS) {
            throw ValidationException::withMessages([
                'application' => ['Bu başvuru zaten karara bağlanmış.'],
            ]);
        }
    }

    /** "@kullanici" ya da düz kullanıcı adı → tam Instagram URL'si. */
    private function normalizeInstagram(?string $value): ?string
    {
        if ($value === null || trim($value) === '') {
            return null;
        }

        $value = trim($value);

        if (Str::startsWith($value, ['http://', 'https://'])) {
            return $value;
        }

        return 'https://instagram.com/'.ltrim($value, '@/');
    }

    private function uniqueSlug(string $name): string
    {
        $base = Str::slug($name) ?: 'consultant';
        $slug = $base;
        $suffix = 1;

        while (ConsultantProfile::where('slug', $slug)->exists()) {
            $slug = "{$base}-{$suffix}";
            $suffix++;
        }

        return $slug;
    }
}
