<?php

namespace App\Http\Controllers;

use App\Models\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $images = Image::all()->map(fn($img) => [
            'id' => $img->id,
            'url' => $img->url,
            'title' => $img->title,
            'file_size' => $img->file_size,
            'width' => $img->width,
            'height' => $img->height,
        ]);

        return response()->json(['images' => $images]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,webp|max:2048',
            'folderType' => 'required|string|in:rooms,meals,addons,facilities,products,general',
            'item_name' => 'nullable|string|max:255',
            'item_id' => 'nullable|integer'
        ]);

        $file = $request->file('image');
        $folderType = $request->input('folderType', 'general');
        $itemName = $request->input('item_name', 'image');
        $itemId = $request->input('item_id');


        $originalName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
        // 🧠 Create SEO-friendly filename
        $baseName = Str::slug($itemName ?:  $originalName  ?: 'image');

        // Ensure unique filename
        $fileName = $baseName . '-' . substr(Str::uuid()->toString(), 0, 8) . '.' . $file->extension();

        // 📂 Build dynamic folder path
        $folder = $itemId
            ? "upload/{$folderType}/{$itemId}"
            : "upload/{$folderType}";

        $altText = $itemName ?: Str::headline($originalName)  ?: 'Uploaded image';

        // 💾 Store file correctly
        $path = $file->storeAs($folder, $fileName, 'public');

        // 🌐 Public URL
        $url = asset('storage/' . $path);

        // 📏 Get dimensions safely
        [$width, $height] = getimagesize($file->getRealPath());

        // 🗄️ Save to DB
        $image = Image::create([
            'title' => $fileName,
            'alt_text' => $altText, // SEO alt text
            'path' => $path,
            'url' => $url,
            'mime_type' => $file->getMimeType(),
            'file_size' => $file->getSize(),
            'width' => $width,
            'height' => $height,
            'type' => $folderType,
            'item_id' => $itemId,
        ]);

        return response()->json([
            'success' => true,
            'image' => $image,
        ]);
    }

    /**
     * Display the specified resource.
     */
    public function show(Image $image)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Image $image)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Image $image)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Image $image)
    {
        //
    }
}
