<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\Permission;
use Illuminate\Http\Request;

/**
 * Firma (agency) başvurularının yönetimi: listeleme, onay/red ve doğrulama rozeti.
 * Onaylanan firmanın sahibi Agency Panel iznini otomatik alır.
 */
class CompaniesController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->query('status', Company::STATUS_PENDING);

        $query = Company::query()
            ->with('user:id,name,email')
            ->withCount('consultants')
            ->latest('applied_at')
            ->latest('id');

        if (in_array($status, [
            Company::STATUS_PENDING,
            Company::STATUS_APPROVED,
            Company::STATUS_REJECTED,
        ], true)) {
            $query->where('application_status', $status);
        }

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

        $companies = $query->paginate(20)->through(fn (Company $c) => $this->companyArray($c));

        return response()->json($companies);
    }

    public function show(Company $company)
    {
        $company->load('user:id,name,email')->loadCount('consultants');

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

    public function approve(Company $company)
    {
        $company->update([
            'application_status' => Company::STATUS_APPROVED,
            'is_active' => true,
            'rejection_reason' => null,
        ]);

        // Firma sahibine Agency Panel izinleri.
        $permissionIds = Permission::whereIn('key', Company::OWNER_PERMISSION_KEYS)
            ->pluck('id')
            ->all();

        $company->user->permissions()->syncWithoutDetaching($permissionIds);

        return response()->json([
            'data' => $this->companyArray($company->fresh('user')->loadCount('consultants')),
        ]);
    }

    public function reject(Request $request, Company $company)
    {
        $data = $request->validate([
            'rejection_reason' => ['required', 'string', 'max:1000'],
        ]);

        $company->update([
            'application_status' => Company::STATUS_REJECTED,
            'is_active' => false,
            'rejection_reason' => $data['rejection_reason'],
        ]);

        // Daha önce onaylanmışsa panel erişimi de geri alınır.
        $permissionIds = Permission::whereIn('key', Company::OWNER_PERMISSION_KEYS)
            ->pluck('id')
            ->all();

        $company->user->permissions()->detach($permissionIds);

        return response()->json([
            'data' => $this->companyArray($company->fresh('user')->loadCount('consultants')),
        ]);
    }

    public function verify(Request $request, Company $company)
    {
        $request->validate([
            'is_verified' => ['required', 'boolean'],
        ]);

        $company->update([
            'is_verified' => $request->boolean('is_verified'),
            'verified_at' => $request->boolean('is_verified') ? now() : null,
        ]);

        return response()->json(['status' => true]);
    }

    private function companyArray(Company $company): array
    {
        return [
            'id' => $company->id,
            'slug' => $company->slug,
            'name' => $company->name,
            'logo' => $company->logo,
            'email' => $company->email,
            'phone' => $company->phone,
            'whatsapp_phone' => $company->whatsapp_phone,
            'website_url' => $company->website_url,
            'instagram_url' => $company->instagram_url,
            'linkedin_url' => $company->linkedin_url,
            'description' => $company->description,
            'address' => $company->address,
            'city' => $company->city,
            'district' => $company->district,
            'country' => $company->country,
            'license_number' => $company->license_number,
            '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(),
            'consultants_count' => $company->consultants_count ?? 0,
            'user' => $company->user ? [
                'id' => $company->user->id,
                'name' => $company->user->name,
                'email' => $company->user->email,
            ] : null,
        ];
    }
}
