<?php

namespace App\Filament\Resources\VisitorEntryResource\Pages;

use App\Filament\Resources\VisitorEntryResource;
use App\Models\DealerVisitPlan;
use App\Models\EmployeeMaster;
use App\Models\VisitorEntry;
use Carbon\Carbon;
use Filament\Actions;
use Filament\Actions\Action;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\On;
use App\Mail\VisitorMail;
use Illuminate\Support\Facades\Mail;

class CreateVisitorEntry extends CreateRecord
{
    protected static string $resource = VisitorEntryResource::class;

    public $capturedPhoto;

    public function processMobile($mobile)
    {
        $registerId = $this->data['register_id'] ?? null;

        $visitor = VisitorEntry::where('mobile_number', $mobile)->latest()->first();
        if ($visitor) {

            $employee = EmployeeMaster::where('id', $visitor->employee_master_id)->first();

            $this->form->fill([
                'register_id'        => $registerId ?? '',
                'mobile_number'      => $visitor->mobile_number,
                'name'               => $visitor->name ?? '',
                'company'            => $visitor->company ?? '',
                'type'               => $visitor->type ?? '',
                'department'         => $employee?->department ?? '',
                'employee_master_id' => $visitor->employee_master_id,
                'code'               => $employee?->code ?? '',
                'purpose_of_visit'   => '',
                'in_time'            => now(),
                'out_time'           => null,
                'valid_upto'         => null,
            ]);
        }
        else {
            $this->form->fill([
                'register_id'        => $registerId ?? '',
                'mobile_number'      => $mobile,
                'name'               => '',
                'company'            => '',
                'type'               => '',
                'department'         => '',
                'employee_master_id' => null,
                'code'               => '',
                'purpose_of_visit'   => '',
                'in_time'            => now(),
                'out_time'           => null,
                'valid_upto'         => null,
            ]);
        }
    }

    #[On('photo-captured')]
    public function handlePhotoCapture(string $photo): void
    {
        $this->data['photo'] = $photo;
        \Log::info('WEBCAM: photo-captured event received, length: ' . strlen($photo));
    }

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        if (
            !empty($data['photo']) &&
            str_starts_with($data['photo'], 'data:image')
        ) {
            try {
                $imageData = explode(',', $data['photo'])[1];

                $filename = 'visitor_' . time() . '_' . uniqid() . '.jpg';

                $path = 'visitor-photos/' . $filename;

                $decoded = base64_decode($imageData);

                $saved = Storage::disk('public')->put($path, $decoded);

                $data['photo'] = $path;

            } catch (\Exception $e) {
                \Log::error('PHOTO UPLOAD ERROR: ' . $e->getMessage());
            }
        }

        return $data;
    }


    public function setPhoto(string $photo): void
    {
        $this->capturedPhoto = $photo;

        $this->dispatch('photo-captured', photo: $photo)->to(\App\Filament\Resources\VisitorEntryResource\Pages\CreateVisitorEntry::class);
    }

        // ── Custom form action buttons ──
    protected function getFormActions(): array
    {
        return [
            $this->getCreateFormAction(),
            $this->getCreateAnotherFormAction(),

            Action::make('createAndPrint')
                ->label('Create & Print')
                ->color('success')
                ->icon('heroicon-o-printer')
                ->action(function () {
                    // Save the record using existing logic (calls mutateFormDataBeforeCreate internally)
                    $this->create();

                    // Open the badge print page in a new tab
                    $this->js("window.open('" . route('visitor.badge', $this->record->id) . "', '_blank')");
                }),

            $this->getCancelFormAction(),
        ];
    }

    protected function afterCreate(): void
    {
        $visitor = $this->record;

        $employee = EmployeeMaster::find($visitor->employee_master_id);

        if ($employee && !empty($employee->email)) {
            Mail::to($employee->email)
                ->send(new VisitorMail($visitor)); // or ->send()
        }
        else{
            \Log::warning('No email found for employee ID: ' . $visitor->employee_master_id);
        }


        if ($visitor->type == 'Dealers') {
            DealerVisitPlan::where('name', $visitor->name)
                ->where('company', $visitor->company)
                ->where('mobile_number', $visitor->mobile_number)
                ->whereDate('visit_plan_date', today())
                ->where('status', 'Planned')
                ->update([
                    'status' => 'Completed',
                ]);
        }
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('view', ['record' => $this->record]);
    }
}
