<?php

namespace App\Livewire;

use App\Models\Plan;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.app')]
class AdminPricingPage extends Component
{
    /** @var array<int, array{plan_id:int,price_cents:int}> */
    public array $rows = [];

    public function mount(): void
    {
        $this->rows = Plan::query()
            ->orderBy('price_cents')
            ->get()
            ->map(fn (Plan $plan): array => [
                'plan_id' => (int) $plan->id,
                'price_cents' => (int) $plan->price_cents,
            ])->values()->all();
    }

    public function savePricing(): void
    {
        $validated = $this->validate([
            'rows.*.plan_id' => ['required', 'integer'],
            'rows.*.price_cents' => ['required', 'integer', 'min:0'],
        ]);

        foreach ($validated['rows'] as $row) {
            Plan::query()->where('id', $row['plan_id'])->update([
                'price_cents' => $row['price_cents'],
            ]);
        }

        session()->flash('toast', (string) __('budgets.admin_console.pricing_saved'));
    }

    public function render()
    {
        return view('livewire.admin-pricing-page', [
            'plans' => Plan::query()->orderBy('price_cents')->get()->keyBy('id'),
        ])->title((string) __('budgets.admin_console.pricing_title'));
    }
}
