<?php

namespace App\Filament\Resources\VisitorEntryResource\Pages;

use App\Filament\Resources\VisitorEntryResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
use Livewire\Attributes\On;
use Storage;

class EditVisitorEntry extends EditRecord
{
    protected static string $resource = VisitorEntryResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\ViewAction::make(),
            Actions\DeleteAction::make(),
            Actions\ForceDeleteAction::make(),
            Actions\RestoreAction::make(),
        ];
    }

    #[On('photo-captured')]
    public function handlePhotoCapture(string $photo): void
    {
        $this->data['photo'] = $photo;
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        if (
            !empty($data['photo']) &&
            str_starts_with($data['photo'], 'data:image')
        ) {
            // Delete the old photo file if one exists
            $oldPhoto = $this->record->photo;
            if ($oldPhoto && Storage::disk('public')->exists($oldPhoto)) {
                Storage::disk('public')->delete($oldPhoto);
            }

            // Save the new photo
            $imageData = explode(',', $data['photo'])[1];
            $filename  = 'visitor_' . time() . '_' . uniqid() . '.jpg';
            $path      = 'visitor-photos/' . $filename;
            Storage::disk('public')->put($path, base64_decode($imageData));

            $data['photo'] = $path;
        }

        return $data;
    }
}
