<?php

namespace App\Filament\Tenant\Pages;

use App\Models\Tenant\Part;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Livewire\Attributes\On;

/**
 * Mobile scanner: opens camera in the browser, decodes QR/barcode, looks up
 * Part by:
 *   - `PART:<article|id>` payload (our own QR labels)
 *   - exact barcode match on parts.barcode
 *   - exact article match on parts.article
 * On match → redirect to Part edit page.
 */
class Scanner extends Page
{
    protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-qr-code';

    protected static ?string $navigationLabel = 'Scaner';

    protected static string|\UnitEnum|null $navigationGroup = 'Depozit';

    protected static ?int $navigationSort = 39;

    protected static ?string $title = 'Scaner cod QR / Bare';

    protected string $view = 'filament.tenant.pages.scanner';

    public string $manual = '';

    #[On('scanner-decoded')]
    public function decoded(string $text): void
    {
        $this->resolveAndRedirect(trim($text));
    }

    public function submitManual(): void
    {
        if (trim($this->manual) === '') return;
        $this->resolveAndRedirect(trim($this->manual));
    }

    protected function resolveAndRedirect(string $code): void
    {
        $clean = $code;
        if (str_starts_with($clean, 'PART:')) {
            $clean = substr($clean, 5);
        }

        $part = Part::where(function ($q) use ($clean, $code) {
                $q->where('article', $clean)
                  ->orWhere('barcode', $clean)
                  ->orWhere('barcode', $code);
                if (ctype_digit($clean)) $q->orWhere('id', (int) $clean);
            })
            ->first();

        if (! $part) {
            Notification::make()
                ->title('Cod necunoscut')
                ->body('Nu am găsit nicio piesă pentru: ' . $code)
                ->warning()
                ->send();
            return;
        }

        Notification::make()
            ->title('Piesă găsită: ' . $part->name)
            ->success()
            ->send();

        $this->redirect(
            route('filament.tenant.resources.parts.edit', ['record' => $part->id])
        );
    }
}
