<?php

namespace App\Services;

use App\Events\UnitUpdated;
use App\Models\Unit;
use App\Models\User;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class UnitService
{
    public function list(int $perPage = 15): LengthAwarePaginator
    {
        return Unit::with('createdBy:id,name')
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data, User $createdBy): Unit
    {
        $unit = Unit::create([
            'unit_name'  => $data['unit_name'],
            'unit_code'  => $data['unit_code'],
            'location'   => $data['location'] ?? null,
            'status'     => $data['status'] ?? 'active',
            'notes'      => $data['notes'] ?? null,
            'created_by' => $createdBy->id,
        ]);

        $this->generateQrCode($unit);

        return $unit->fresh();
    }

    public function update(Unit $unit, array $data): Unit
    {
        $unit->update(array_filter([
            'unit_name' => $data['unit_name'] ?? null,
            'unit_code' => $data['unit_code'] ?? null,
            'location'  => $data['location'] ?? null,
            'status'    => $data['status'] ?? null,
            'notes'     => $data['notes'] ?? null,
        ], fn ($v) => $v !== null));

        event(new UnitUpdated($unit->fresh()));

        return $unit->fresh();
    }

    public function delete(Unit $unit): void
    {
        if ($unit->qr_code) {
            Storage::disk('public')->delete($unit->qr_code);
        }
        $unit->delete();
    }

    public function findByQrData(string $data): ?Unit
    {
        return Unit::where('qr_data', $data)->first();
    }

    private function generateQrCode(Unit $unit): void
    {
        $qrData = json_encode([
            'unit_id'   => $unit->id,
            'unit_code' => $unit->unit_code,
            'app'       => 'farm-manager',
        ]);

        // PNG requires Imagick on Windows/XAMPP; SVG works with default PHP only.
        $filename = 'qrcodes/unit_' . $unit->id . '.svg';

        $qrImage = QrCode::format('svg')
            ->size(300)
            ->margin(2)
            ->generate($qrData);

        Storage::disk('public')->put($filename, $qrImage);

        $unit->update([
            'qr_code' => $filename,
            'qr_data' => $qrData,
        ]);
    }
}
