<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SubSize;
use Illuminate\Http\Request;

class SubSizeController extends Controller
{
    public function index(Request $request)
    {
        $query = SubSize::query();

        if ($request->has('size_id') && $request->query('size_id') !== 'ALL') {
            $query->where('size_id', $request->query('size_id'));
        }

        if ($request->has('search')) {
            $query->where('name', 'like', "%{$request->search}%");
        }

        if ($request->has('per_page')) {
            return $query->with('size')->orderBy('name')->paginate($request->per_page);
        }

        return $query->orderBy('name')->get();
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'size_id' => 'required|exists:sizes,id',
            'name' => 'required',
        ]);

        $subSize = SubSize::create($data);
        return response()->json($subSize, 201);
    }

    public function update(Request $request, string $id)
    {
        $subSize = SubSize::findOrFail($id);
        $subSize->update($request->all());
        return response()->json($subSize);
    }

    public function destroy(string $id)
    {
        $subSize = SubSize::findOrFail($id);
        $subSize->delete();
        return response()->json(['message' => 'Sub-Size deleted successfully']);
    }
}
