<?php

namespace App\Filament\Resources\StickerPrintingResource\Pages;

use App\Filament\Resources\StickerPrintingResource;
use Filament\Resources\Pages\CreateRecord;
use PDF;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Filament\Facades\Filament;
use App\Models\StickerPrinting;
use Filament\Notifications\Notification;
use Str;


class CreateStickerPrinting extends CreateRecord
{
    protected static string $resource = StickerPrintingResource::class;

    protected static string $view = 'filament.resources.sticker-printing-resource.pages.create-sticker-printing';

    public $plantId;

    public $ref_number;

    public $ref;

    public $serial_number;

    public function getFormActions(): array
    {
        return [
            $this->getCancelFormAction(),
        ];
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('create');
    }

    public function loadRecords()
    {
        $this->records = StickerPrinting::where('reference_number', $this->refNumber)
            ->where('plant_id', $this->plantId)
            ->latest()
            ->get();

    }

    public function processRef($value)
    {

        //$this->ref_number = $value;
        $ref = $this->form->getState()['reference_number'] ?? null;

        $user = Filament::auth()->user();

        $operatorName = $user->name;

        $plantId = $this->form->getState()['plant_id'];

        $this->plantId = $plantId;

        $this->dispatch('refreshEmptySticker', $plantId, $ref);

        $this->dispatch('focus-serial-number');

    }

    public function processSno($value)
    {

        $this->serial_number = $value;

        $plant = $this->form->getState()['plant_id'] ?? null;

        $ref = $this->form->getState()['reference_number'] ?? null;

        $sNumber = $this->form->getState()['serial_number'] ?? null;

        $pattern1 = '/^(?<item_code>[^|]+)\|(?<serial_number>[^|]+)\|?$/i';

        $pattern2 = '/^(?<item_code>[^|]+)\|(?<serial_number>[^|]+)\|(?<batch_number>.+)$/i';

        $pattern3 = '/^(?<serial_number>[^|]+)$/i';


        if (preg_match($pattern1, $sNumber, $matches) || preg_match($pattern2, $sNumber, $matches) || preg_match($pattern3, $sNumber, $matches)) {

            $serial = $matches['serial_number'];

            if (Str::length($serial) < 9) {
                Notification::make()
                    ->title('Invalid Serial Number')
                    ->body("Serial number should conatin minimum 9 digits '$serial'.")
                    ->warning()
                    ->send();
                    $this->form->fill([
                        'plant_id'      => $plant,
                        'reference_number' => $ref,
                        'serial_number' => '',
                    ]);
                return;
            }
            else if(!ctype_alnum($serial)) {
                Notification::make()
                    ->title('Invalid Serial Number')
                    ->body("Serial number should be alphanumeric '$serial'.")
                    ->warning()
                    ->send();
                    $this->form->fill([
                        'plant_id'      => $plant,
                        'reference_number' => $ref,
                        'serial_number' => '',
                ]);
                return;
            }
            $extractedSerialNumber = $matches['serial_number'];
            $sNumber = $extractedSerialNumber;
        }
        else
        {
            Notification::make()
            ->title('Invalid Format')
            ->body("Serial number must be in the format 'itemcode|serialnumber' or 'itemcode|serialnumber|batchnumber'. or just 'serialnumber'.")
            ->warning()
            ->send();

            // Reset only serial number field
            $this->form->fill([
                'plant_id'      => $plant,
                'reference_number' => $ref,
                'serial_number' => '',
            ]);
            return;
        }

        if ($plant == null || trim($plant) == '' || $ref == null || trim($ref) == '' || $sNumber == null || trim($sNumber) == '')
        {
            Notification::make()
                ->title('Unknown: Incomplete Data!')
                ->body("Please ensure Plant, Reference Number, and Serial Number are provided.")
                ->danger()
                ->seconds(3)
                ->send();
            return;
        }

        $exists = StickerPrinting::where('plant_id', $plant)
            ->where('serial_number', $sNumber)
            ->first();

        if ($exists) {
            Notification::make()
                ->title('Duplicate Serial Number!')
                ->body("Serial Number {$sNumber} already exists for this plant.")
                ->danger()
                ->seconds(3)
                ->send();

            // Reset only serial number field
            $this->form->fill([
                'plant_id'      => $plant,
                'reference_number' => $ref,
                'serial_number' => '',
            ]);

            return;
        }

        StickerPrinting::create([
            'plant_id'      => $plant,
            'reference_number' => $ref,
            'serial_number' => $sNumber,
            'created_by'    => Filament::auth()->user()->name,
        ]);

        $this->dispatch('addStickerToList', $plant, $ref, $sNumber);

        $this->form->fill([
            'plant_id'      => $plant,
            'reference_number' => $ref,
            'serial_number' => '',
        ]);

    }

    public function printSticker() {

        $plantId = $this->form->getState()['plant_id'];

        $plantId = trim($plantId) ?? null;

        $refNumber = trim($this->form->getState()['reference_number'])?? null;

        $refNumber = trim($refNumber) ?? null;

        $serialNumber = trim($this->form->getState()['serial_number'])?? null;

        $serialNumber = trim($serialNumber) ?? null;

        // dd($plantId, $refNumber, $serialNumber);

        $serialNumbers = StickerPrinting::where('plant_id', $plantId)
        ->where('reference_number', $refNumber)
        ->pluck('serial_number')
        ->toArray();

        if (empty($serialNumbers))
        {
            Notification::make()
                ->title('No Serial Numbers found!')
                ->body('Please check the selected Plant & Reference Number.')
                ->danger()
                ->send();
            return;
        }

        // Encode as JSON string in QR Code
        // $qrData = json_encode([
        //     'serial_numbers' => $serialNumbers,
        // ]);
        //$qrData = implode(',', $serialNumbers);
        $qrData = implode("\n", $serialNumbers);

        $qrCode = base64_encode(
            QrCode::format('png')
                ->size(1200)           // smaller, still high res
                ->margin(6)           // white border
                ->errorCorrection('Q')// medium-high correction
                ->generate($qrData)
        );

        // Send data to Pdf view
        $pdf = PDF::loadView('pdf.qrcode', [
            'qrCode'   => $qrCode,
            'referenceNumber' => $refNumber,
        ]);

        return response()->streamDownload(function () use ($pdf) {
            echo $pdf->output();
        }, "qr-sticker.pdf");
    }
}
