<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ShopGarment;
use App\Models\ShopGarmentField;
use Illuminate\Http\Request;

class GarmentTypeController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $shopId = $user->type_id === 1 ? $request->query('shop_id') : $user->shop_id;

        $shopGarments = ShopGarment::where('shop_id', $shopId)
            ->where('is_active', true)
            ->with(['garmentType', 'prices.ageType'])
            ->get();

        return $shopGarments->map(fn ($sg) => [
            'garment_type_id' => $sg->garment_type_id,
            'name' => $sg->garmentType->name,
            'name_ta' => $sg->garmentType->name_ta,
            'code' => $sg->garmentType->code,
            'prices' => $sg->prices->map(fn ($p) => [
                'age_type_id' => $p->age_type_id,
                'age_type_name' => $p->ageType?->name,
                'price' => $p->price,
            ]),
        ]);
    }

    public function fields(Request $request, $garmentTypeId)
    {
        $user = $request->user();
        $shopId = $user->type_id === 1 ? $request->query('shop_id') : $user->shop_id;

        $fields = ShopGarmentField::where('shop_id', $shopId)
            ->where('garment_type_id', $garmentTypeId)
            ->with('measurementField')
            ->orderBy('display_order')
            ->get();

        return $fields->map(fn ($f) => [
            'measurement_field_id' => $f->measurement_field_id,
            'code' => $f->measurementField->code,
            'label' => $f->label,
            'unit' => $f->measurementField->unit,
            'is_required' => $f->is_required,
            'display_order' => $f->display_order,
        ]);
    }
}
