<?php

namespace App\Http\Controllers\client;

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

class ProductController extends Controller
{
    public function index()
    {
        $product = Product::all();
        $productResponse = $product->map(function ($item) {
            return [
                "id" => $item->id,
                "title" => $item->title,
                "type" => $item->type,
                "image_url" => $item->image_url ? asset(Storage::url($item->image_url)) : null,
            ];
        });

        return Inertia::render("dashboard/products/index", ['product' => $productResponse]);
    }

    public function productAdd()
    {
        return Inertia::render("dashboard/products/add");
    }
    public function productAddPost(Request $request)
    {
        $validated = $request->validate([
            "title" => "required|string",
            "type" => "required|string",
            "image_url" => "file"
        ]);

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

            $product = Product::create([
                'title' => $validated['title'],
                "type" => $validated['type'],
                'image_url' => $path
            ]);

            $productResponse = [
                "title" => $product->title,
                "type" => $product->type,
                "image_url" => $product->image_url ? asset(Storage::url($product->image_url)) : null,
            ];

            return to_route('dashboard.product.index', $productResponse);
        }

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