<?php

namespace App\Http\Controllers\Api\Company;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\PropertyRequest;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

/**
 * Agency Panel "Müşteri Talepleri": firmaya özel + genel (company_id null) talepler.
 * Durum (new/contacted/closed) talep üzerinde tutulur; genel taleplerde durum
 * tüm firmalar için ortaktır (v1 — firma bazlı durum ileride pivotla ayrılabilir).
 */
class CompanyPropertyRequestController extends Controller
{
    public function index(Request $request)
    {
        $company = $this->company($request);

        $status = $request->query('status', 'new');

        $query = PropertyRequest::query()
            ->visibleToCompany($company->id)
            ->with('category:id,name,slug')
            ->latest('id');

        if (in_array($status, PropertyRequest::STATUSES, 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('location', 'like', "%{$search}%")
                    ->orWhere('category_name', 'like', "%{$search}%");
            });
        }

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

        $counts = PropertyRequest::query()
            ->visibleToCompany($company->id)
            ->selectRaw('status, COUNT(*) as total')
            ->groupBy('status')
            ->pluck('total', 'status');

        return response()->json([
            'data' => collect($paginator->items())->map(fn (PropertyRequest $r) => $this->requestArray($r, $company)),
            'meta' => [
                'current_page' => $paginator->currentPage(),
                'last_page' => $paginator->lastPage(),
                'per_page' => $paginator->perPage(),
                'total' => $paginator->total(),
            ],
            'counts' => [
                'new' => (int) ($counts['new'] ?? 0),
                'contacted' => (int) ($counts['contacted'] ?? 0),
                'closed' => (int) ($counts['closed'] ?? 0),
            ],
        ]);
    }

    public function updateStatus(Request $request, PropertyRequest $propertyRequest)
    {
        $company = $this->company($request);

        // Başka firmaya özel talep bu firmaya görünmez (404 — varlığı sızmasın).
        abort_unless(
            $propertyRequest->company_id === null || $propertyRequest->company_id === $company->id,
            404,
            'Talep bulunamadı.'
        );

        $data = $request->validate([
            'status' => ['required', Rule::in(PropertyRequest::STATUSES)],
        ]);

        $propertyRequest->update([
            'status' => $data['status'],
            'contacted_at' => $data['status'] === PropertyRequest::STATUS_CONTACTED
                ? ($propertyRequest->contacted_at ?? now())
                : $propertyRequest->contacted_at,
        ]);

        return response()->json([
            'data' => $this->requestArray($propertyRequest->fresh('category'), $company),
        ]);
    }

    private function requestArray(PropertyRequest $r, Company $company): array
    {
        return [
            'id' => $r->id,
            'status' => $r->status,
            // Bu firmaya özel mi, genel mi (UI rozeti).
            'targeted' => $r->company_id === $company->id,
            'category' => $r->category ? [
                'id' => $r->category->id,
                'name' => $r->category->name,
                'slug' => $r->category->slug,
            ] : null,
            'category_name' => $r->category_name,
            'location' => $r->location,
            'price_min' => $r->price_min,
            'price_max' => $r->price_max,
            'currency' => $r->currency,
            'description' => $r->description,
            'name' => $r->name,
            'email' => $r->email,
            'phone' => $r->phone,
            'locale' => $r->locale,
            'source' => $r->source,
            'user_id' => $r->user_id,
            'contacted_at' => $r->contacted_at?->toISOString(),
            'created_at' => $r->created_at?->toISOString(),
        ];
    }

    private function company(Request $request): Company
    {
        $company = $request->user()->company;

        abort_unless(
            $company && $company->application_status === Company::STATUS_APPROVED,
            403,
            'Onaylı bir firmanız bulunmuyor.'
        );

        return $company;
    }
}
