<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\carousel;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Storage;

class DashboardController extends Controller
{
    public function index()
    {
        return Inertia::render("dashboard");
    }


    public function carousel()
    {
        $carousel = Carousel::all();
        $carouselResponse = $carousel->map(function ($item) {
            return [
                "id" => $item->id,
                "alt" => $item->alt,
                "image_url" => $item->image_url ? asset(Storage::url($item->image_url)) : null,
            ];
        });

        return Inertia::render('dashboard/carousel/carousel', ['carousel' => $carouselResponse]);
    }

    public function carouselAdd()
    {
        return Inertia::render('dashboard/carousel/add');
    }

    public function carouselStore(Request $request)
    {
        $validated = $request->validate([
            "image_url" => "required|file|image",
            "alt" => "string|nullable"
        ]);

        if ($request->hasFile('image_url')) {
            $path = $request->file('image_url')->store('carousel_images', 'public');

            $carousel = Carousel::create([
                'alt' => $validated['alt'],
                'image_url' => $path
            ]);

            $carouselResponse = [
                "alt" => $carousel->alt,
                "image_url" => $carousel->image_url ? asset(Storage::url($carousel->image_url)) : null,
            ];

            return to_route('dashboard.carousel.index', $carouselResponse);
        }

        return response()->json([
            'status' => 'error',
            'message' => 'File upload failed',
        ], 400);
    }
}
