<?php

namespace App\Http\Livewire\SuperAdmin;

use App\Models\Module;
use App\Models\Company;
use App\Models\Plan;
use App\Services\Subscription\ModuleAccessService;
use Illuminate\Support\Str;
use Livewire\Attributes\Validate;
use Livewire\Component;

class PlanForm extends Component
{
    public ?Plan $plan = null;

    #[Validate('required|string|max:255')]
    public string $name = '';

    #[Validate('nullable|string')]
    public string $description = '';

    #[Validate('required|numeric|min:0')]
    public float $price_monthly = 0;

    #[Validate('required|numeric|min:0')]
    public float $price_yearly = 0;

    #[Validate('nullable|integer|min:1')]
    public ?int $max_employees = null;

    #[Validate('nullable|integer|min:1')]
    public ?int $max_services = null;

    #[Validate('nullable|integer|min:1')]
    public ?int $max_bookings_month = null;

    #[Validate('nullable|integer|min:1')]
    public ?int $max_branches = 1;

    public bool $is_active = true;
    public bool $is_featured = false;
    public bool $is_public = true;

    /** @var array<int> */
    public array $selected_modules = [];

    public function mount(?int $planId = null): void
    {
        if ($planId) {
            $this->plan = Plan::with('modules')->findOrFail($planId);
            $data = $this->plan->only([
                'name', 'description', 'price_monthly', 'price_yearly',
                'max_employees', 'max_services', 'max_bookings_month', 'max_branches',
                'is_active', 'is_featured', 'is_public',
            ]);

            $data['description'] = $data['description'] ?? '';

            $this->fill($data);
            $this->selected_modules = $this->plan->modules->pluck('id')->all();
        }
    }

    public function save()
    {
        $this->validate();

        $data = [
            'name'               => $this->name,
            'description'        => $this->description,
            'price_monthly'      => $this->price_monthly,
            'price_yearly'       => $this->price_yearly,
            'max_employees'      => $this->max_employees,
            'max_services'       => $this->max_services,
            'max_bookings_month' => $this->max_bookings_month,
            'max_branches'       => $this->max_branches,
            'is_active'          => $this->is_active,
            'is_featured'        => $this->is_featured,
            'is_public'          => $this->is_public,
        ];

        if ($this->plan) {
            $this->plan->update($data);
        } else {
            $data['slug'] = Str::slug($this->name).'-'.Str::random(4);
            $this->plan = Plan::create($data);
        }

        $sync = collect($this->selected_modules)
            ->mapWithKeys(fn ($id) => [$id => ['is_enabled' => true]])
            ->all();
        $this->plan->modules()->sync($sync);

        Company::where('plan_id', $this->plan->id)
            ->get(['id'])
            ->each(fn (Company $company) => app(ModuleAccessService::class)->flush($company));

        session()->flash('success', 'Plan guardado correctamente.');
        return redirect()->route('superadmin.plans.index');
    }

    public function render()
    {
        $modules = Module::orderBy('group')->orderBy('sort_order')->get()->groupBy('group');
        $groups  = config('modules.groups');

        return view('livewire.superadmin.plan-form', compact('modules', 'groups'));
    }
}
