<?php
namespace App\Services;

use Illuminate\Http\UploadedFile;

class ImageService
{
    /**
     * Process uploaded image: resize, watermark, save.
     * Returns ['path'=>relative_path, 'watermark'=>string, 'full'=>full_path]
     */
    public function processAndSave(UploadedFile $file, $visit, string $type, array $meta = []): array
    {
        $contents = file_get_contents($file->getRealPath());
        $img = imagecreatefromstring($contents);
        if (!$img) throw new \Exception('Invalid image file');

        // resize to max 1280
        $width = imagesx($img); $height = imagesy($img); $max = 1280;
        if ($width > $max || $height > $max) {
            if ($width >= $height) {
                $newW = $max; $newH = intval($height * ($max / $width));
            } else {
                $newH = $max; $newW = intval($width * ($max / $height));
            }
            $resized = imagescale($img, $newW, IMG_BILINEAR_FIXED);
            imagedestroy($img);
            $img = $resized;
        }

        // watermark text
        $tech = auth()->user()->name ?? 'Teknisi';
        $ts = now()->format('Y-m-d H:i:s');
        $lat = $meta['lat'] ?? null; $lng = $meta['lng'] ?? null;
        $wm = $tech . ' | ' . $ts;
        if ($lat !== null && $lng !== null) $wm .= ' | GPS: '.$lat.','.$lng;
        if (!empty($type)) $wm .= ' | '.strtoupper($type);

        $col = imagecolorallocate($img, 255, 255, 255);
        $shadow = imagecolorallocate($img, 0, 0, 0);
        $fontSize = 3;
        $x = 10; $y = imagesy($img) - 20;
        imagestring($img, $fontSize, $x+1, $y+1, $wm, $shadow);
        imagestring($img, $fontSize, $x, $y, $wm, $col);

        // save
        $dir = storage_path('app/public/visits'); if (!is_dir($dir)) mkdir($dir, 0755, true);
        $filename = 'visit_'.$visit->id.'_'.($type ?: 'img').'_'.$ts.'.jpg';
        $filename = str_replace([' ',':'],['_','-'],$filename);
        $full = $dir . DIRECTORY_SEPARATOR . $filename;
        imagejpeg($img, $full, 60);
        imagedestroy($img);

        return ['path' => 'visits/'.$filename, 'watermark' => ['text'=>$wm,'ts'=>$ts], 'full' => $full];
    }
}
