<?php

namespace App\Http\Controllers\Api\Company;

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

class CompanyApplicationController extends Controller
{

    public function show(Request $request)
    {
        $company = $request->user()->company;

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

    /**
     * "Bizimle Satış Yapın" firma başvurusu. Firma bilgilerini alır ve incelemeye
     * (pending) gönderir. Onay/aktifleştirme ve Agency Panel izni admin tarafından verilir.
     */
    public function store(Request $request)
    {
        $user = $request->user();

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

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

        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['nullable', 'email', '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'],
            'country' => ['nullable', 'string', 'max:120'],
            'address' => ['nullable', 'string', 'max:500'],
            'description' => ['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' => Company::STATUS_PENDING,
            'rejection_reason' => null,
            'applied_at' => now(),
            'is_verified' => false,
            'is_active' => false,
        ]);

        if ($existing) {
            $existing->update($payload);
            $company = $existing;
        } else {
            $payload['slug'] = $this->uniqueSlug($data['name']);
            $company = Company::create($payload);
        }

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

    private function companyArray(Company $company): array
    {
        return [
            'id' => $company->id,
            'slug' => $company->slug,
            'name' => $company->name,
            'phone' => $company->phone,
            'application_status' => $company->application_status,
            'rejection_reason' => $company->rejection_reason,
            'is_verified' => $company->is_verified,
            'is_active' => $company->is_active,
            'applied_at' => $company->applied_at?->toISOString(),
        ];
    }

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

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

        return $slug;
    }
}
