<?php

namespace App\Http\Controllers\Api\Consultant;

use App\Http\Controllers\Controller;
use App\Models\ConsultantProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class ConsultantApplicationController extends Controller
{
    
    public function show(Request $request)
    {
        $profile = $request->user()->consultantProfile;

        return response()->json([
            'data' => $profile ? $this->profileArray($profile) : null,
        ]);
    }

    /**
     * "Emlakçı Ol" başvurusu. Profesyonel bilgileri alır ve incelemeye (pending)
     * gönderir. Onay/aktifleştirme ve izinler admin tarafından verilir.
     */
    public function store(Request $request)
    {
        $user = $request->user();

        // Zaten bir profili varsa: onaylıysa ya da beklemedeyse tekrar başvuramaz.
        // Yalnızca reddedilmiş başvuru tekrar gönderilebilir (aşağıda güncellenir).
        $existing = $user->consultantProfile;

        if ($existing && $existing->application_status !== ConsultantProfile::STATUS_REJECTED) {
            throw ValidationException::withMessages([
                'application' => ['Zaten bir emlakçı başvurunuz bulunuyor.'],
            ]);
        }

        $data = $request->validate([
            'company_name' => ['required', 'string', 'max:255'],
            'phone' => ['required', 'string', 'max:50'],
            'whatsapp_phone' => ['nullable', 'string', 'max:50'],
            'license_number' => ['nullable', 'string', 'max:100'],
            'city' => ['nullable', 'string', 'max:120'],
            'district' => ['nullable', 'string', 'max:120'],
            'address' => ['nullable', 'string', 'max:500'],
            'bio' => ['nullable', 'string', 'max:2000'],
            'website_url' => ['nullable', 'url', 'max:255'],
            'instagram_url' => ['nullable', 'url', 'max:255'],
            'linkedin_url' => ['nullable', 'url', 'max:255'],
        ]);

        $payload = array_merge($data, [
            'user_id' => $user->id,
            'application_status' => ConsultantProfile::STATUS_PENDING,
            'rejection_reason' => null,
            'applied_at' => now(),
            'is_verified' => false,
            'is_active' => false,
        ]);

        if ($existing) {
            
            $existing->update($payload);
            $profile = $existing;
        } else {
            $payload['slug'] = $this->uniqueSlug($data['company_name']);
            $profile = ConsultantProfile::create($payload);
        }

        return response()->json([
            'data' => $this->profileArray($profile),
        ], 201);
    }

    private function profileArray(ConsultantProfile $profile): array
    {
        return [
            'id' => $profile->id,
            'slug' => $profile->slug,
            'company_name' => $profile->company_name,
            'phone' => $profile->phone,
            'application_status' => $profile->application_status,
            'rejection_reason' => $profile->rejection_reason,
            'is_verified' => $profile->is_verified,
            'is_active' => $profile->is_active,
            'applied_at' => $profile->applied_at?->toISOString(),
        ];
    }

    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;
    }
}
