<?php

namespace App\Filament\Resources\ProductResource\Pages;

use App\Filament\Resources\ProductResource;
use App\Models\Product;
use App\Support\ExcelImporter;
use Filament\Actions;
use Filament\Forms\Components\FileUpload;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ManageRecords;

class ManageProducts extends ManageRecords
{
    protected static string $resource = ProductResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\CreateAction::make()->label('کالا/خدمت جدید'),
            Actions\Action::make('import')->label('ورودی اکسل')->icon('heroicon-o-arrow-up-tray')->color('warning')
                ->form([
                    FileUpload::make('file')->label('فایل اکسل / CSV')
                        ->disk('local')->directory('imports')
                        ->acceptedFileTypes([
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                            'application/vnd.ms-excel', 'text/csv', 'text/plain',
                        ])->required()
                        ->helperText('ستون‌ها به ترتیب: نام | واحد | قیمت پیش‌فرض (ردیف اول سرستون است)'),
                ])
                ->action(function (array $data) {
                    $count = 0;
                    foreach (ExcelImporter::rows($data['file']) as $r) {
                        if (blank($r[0] ?? null)) {
                            continue;
                        }
                        Product::create([
                            'name' => trim((string) $r[0]),
                            'unit' => $r[1] ?? null,
                            'default_price' => (float) ($r[2] ?? 0),
                            'is_active' => true,
                        ]);
                        $count++;
                    }
                    Notification::make()->success()->title("تعداد {$count} ردیف وارد شد")->send();
                }),
        ];
    }
}
