<?php

namespace App\Services;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use App\Models\Setting;

class FileUploadService
{
    /**
     * Upload visitor ID image
     */
    public function uploadVisitorIdImage(UploadedFile $file, string $type): string
    {
        // Validate
        $this->validateImage($file);

        // Generate unique filename
        $filename = uniqid() . '_' . $type . '.' . $file->getClientOriginalExtension();

        // Create path with year/month structure
        $path = 'visitors/ids/' . date('Y') . '/' . date('m');

        // Store file
        $fullPath = $file->storeAs($path, $filename, 'public');

        return $fullPath;
    }

    /**
     * Validate uploaded image
     */
    private function validateImage(UploadedFile $file): void
    {
        $maxSizeMB = Setting::get('max_file_size_mb', 5);
        $allowedTypes = Setting::get('allowed_file_types', ['image/jpeg', 'image/jpg', 'image/png']);

        // Check file size
        if ($file->getSize() > $maxSizeMB * 1024 * 1024) {
            throw new \Exception("File size must not exceed {$maxSizeMB}MB");
        }

        // Check MIME type
        if (!in_array($file->getMimeType(), $allowedTypes)) {
            throw new \Exception("File type not allowed. Allowed types: " . implode(', ', $allowedTypes));
        }

        // Check file extension
        $allowedExtensions = ['jpg', 'jpeg', 'png'];
        if (!in_array(strtolower($file->getClientOriginalExtension()), $allowedExtensions)) {
            throw new \Exception("Invalid file extension");
        }

        // Validate actual image content
        $imageInfo = @getimagesize($file->getRealPath());
        if (!$imageInfo) {
            throw new \Exception("Invalid image file");
        }
    }

    /**
     * Delete image file
     */
    public function deleteImage(string $path): void
    {
        if (Storage::disk('public')->exists($path)) {
            Storage::disk('public')->delete($path);
        }
    }

    /**
     * Get public URL for image
     */
    public function getImageUrl(string $path): string
    {
        return Storage::disk('public')->url($path);
    }
}
