<?php

namespace App\Http\Controllers\Admin\Size;

use App\Http\Controllers\Controller;
use App\Models\productAttribute;
use App\Models\Size;
use App\Service\Sizes\SizeService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class SizeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return Inertia::render('Sizes/Size');
    }

    public function view()
    {
        return response()->json(['brands' => Size::orderByDesc('id')->get()]);
    }

    /**
     * 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([
            'name' => 'required|unique:sizes,name',
        ]);
        // Retrieve the data from the request without validation
        $data = $request->all();

        // Pass the data to the SizeService for processing
        SizeService::store($data);

        // Return a response
        return response()->json([
            'success' => 'Size created successfully',
            'sizes' => Size::orderByDesc('id')->get(),
        ]);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        // Retrieve the data from the request without validation
        $data = $request->all();

        // Pass the data and ID to the SizeService for updating
        SizeService::update($data, $id);

        // Return a response
        return response()->json([
            'success' => 'Size updated successfully',
            'brands' => Size::orderByDesc('id')->get(),
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $size_id = productAttribute::where('size_id', $id)->first();
        if ($size_id) {
            return response()->json(['error' => 'Size is already in use'], 422);
        }
        Size::where('id', $id)->delete();

        return response()->json(['success' => 'Size Delete Successfully', 'brands' => Size::orderByDesc('id')->get()]);
    }

    public function search()
    {

        $medicineList = Size::where('name', 'like', '%'.request()->data.'%')->limit(10)->get();

        return response()->json($medicineList);
    }
}
