<?php

namespace App\Filament\Pages;

use App\Models\Customer;
use App\Models\PipelineStage;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Illuminate\Support\Collection;

class SalesPipeline extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-view-columns';
    protected static ?string $navigationGroup = 'مدیریت مشتریان (CRM)';
    protected static ?string $navigationLabel = 'قیف فروش';
    protected static ?string $title = 'قیف فروش (Pipeline)';
    protected static ?int $navigationSort = 2;

    protected static string $view = 'filament.pages.sales-pipeline';

    public static function canAccess(): bool
    {
        return auth()->user()?->can('access_sales_pipeline') ?? false;
    }

    public static function shouldRegisterNavigation(): bool
    {
        return static::canAccess();
    }

    public function getStagesProperty(): Collection
    {
        return PipelineStage::orderBy('sort')->get();
    }

    public function getCardsProperty(): Collection
    {
        $user = auth()->user();

        // مشتریانِ بدون مرحله در نخستین مرحله نمایش داده می‌شوند تا گم نشوند.
        $firstStageId = $this->stages->first()?->id;

        return Customer::query()
            ->when(! $user->canSeeAll('customers'), fn ($q) => $q->where('assigned_user_id', $user->id))
            ->with('assignedUser')
            ->get()
            ->groupBy(fn (Customer $c) => $c->pipeline_stage_id ?: $firstStageId);
    }

    public function moveCard(int $customerId, int $stageId): void
    {
        $user = auth()->user();
        $customer = Customer::find($customerId);

        if (! $customer) {
            return;
        }

        // کنترل دسترسی: کارمند فقط مشتری خودش
        if (! $user->canSeeAll('customers') && $customer->assigned_user_id !== $user->id) {
            return;
        }

        $customer->pipeline_stage_id = $stageId;
        $customer->save();

        Notification::make()->success()->title('مرحله به‌روزرسانی شد')->send();
    }
}
