<?php

namespace App\Http\Resources;

use App\Models\StockProduct;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Storage;

class ProductResource extends JsonResource
{

    public function toArray(Request $request): array
    {
        $cointType = $this->relationLoaded('cointType') ? $this->whenLoaded('cointType') : null;
        $category = $this->relationLoaded('category') ? $this->whenLoaded('category') : null;
        $subcategory = $this->relationLoaded('subcategory') ? $this->whenLoaded('subcategory') : null;
        $specificsubcategory = $this->relationLoaded('specificsubcategory') ? $this->whenLoaded('specificsubcategory') : null;
        $type = $this->relationLoaded('type') ? $this->whenLoaded('type') : null;
        $supplier = $this->relationLoaded('supplier') ? $this->whenLoaded('supplier') : null;
        $unitmeasure = $this->relationLoaded('unitmeasure') ? $this->whenLoaded('unitmeasure') : null;
        $unitMeasureOptional = $this->relationLoaded('unitMeasureOptional') ? $this->whenLoaded('unitMeasureOptional') : null;
        $businessarea = $this->relationLoaded('businessarea') ? $this->whenLoaded('businessarea') : null;
        $classification = $this->relationLoaded('classification') ? $this->whenLoaded('classification') : null;
        $company = $this->relationLoaded('company') ? $this->whenLoaded('company') : null;
        $stock = $this->relationLoaded('stock') ? $this->whenLoaded('stock') : null;

        if (app()->environment('production')) {
            $urlback = "https://www.pewen.factories.cl/pewen_api";
        } else {
            $urlback = "http://localhost:8000";
        }

        # Stock total del producto
        $total_stock = StockProduct::where('idproduct', $this->id)
            ->active()
            ->sum('difference');

        # Stock por bodega
        $stores = Store::active()
            ->company()
            ->get();

        $stockStore = [];

        foreach ($stores as $store) {
            $total_stock_store = StockProduct::where('idproduct', $this->id)
                ->active()
                ->where('idwarehouse', $store['id'])
                ->sum('difference');

            $stockStore[] = [
                'id'          => $store['id'],
                'name'        => $store['name'],
                'description' => $store['description'],
                'stock'       => $total_stock_store
            ];
        }

        return [
            'id' => $this->id,
            'code_erp' => $this->code_erp,
            'code_system' => $this->code_system,
            'barcode' => $this->barcode,
            'name' => $this->name,
            'description' => $this->description,
            'cost' => (int) $this->cost,
            'price' => $this->price,
            'alternativeprice' => $this->alternativeprice,
            'margin' => $this->margin,
            'offerprice' => $this->offerprice,
            'minimumstock' => $this->minimumstock,
            'maximumstock' => $this->maximumstock,
            'total_stock' => $total_stock,
            $this->mergeWhen($stock, fn() => [
                'stock' => $stock
            ]),

            'main_image' => !is_null($this->main_image) ? $urlback . Storage::url($this->main_image) : $this->main_image,
            'optional_image1' => !is_null($this->optional_image1) ? $urlback . Storage::url($this->optional_image1) : $this->optional_image1,
            'optional_image2' => !is_null($this->optional_image2) ? $urlback . Storage::url($this->optional_image2) : $this->optional_image2,
            'optional_image3' => !is_null($this->optional_image3) ? $urlback . Storage::url($this->optional_image3) : $this->optional_image3,
            'optional_image4' => !is_null($this->optional_image4) ? $urlback . Storage::url($this->optional_image4) : $this->optional_image4,

            'idcointype' => $this->idcointype,
            $this->mergeWhen($cointType, fn() => [
                'cointypecode' => $cointType->code,
                'cointype' => $cointType->name,
                'cointypesymbol' => $cointType->symbol,
            ]),
            'idcategory' => $this->idcategory,
            $this->mergeWhen($category, fn() => [
                'category' => $category->name,
            ]),
            'idsubcategory' => $this->idsubcategory,
            $this->mergeWhen($subcategory, fn() => [
                'subcategory' => $subcategory->name,
            ]),
            'idspecificsubcategory' => $this->idspecificsubcategory,
            $this->mergeWhen($specificsubcategory, fn() => [
                'specificsubcategory' => $specificsubcategory->name,
            ]),
            'idtype' => $this->idtype,
            $this->mergeWhen($type, fn() => [
                'type' => $type->name,
            ]),
            'idsupplier' => $this->idsupplier,
            $this->mergeWhen($supplier, fn() => [
                'supplier' => $supplier->name_rz,
            ]),
            'idunitmeasure' => $this->idunitmeasure,
            $this->mergeWhen($unitmeasure, fn() => [
                'unitmeasure' => $unitmeasure->name,
            ]),
            'idunitmeasureoptional' => $this->idunitmeasureoptional,
            $this->mergeWhen($unitMeasureOptional, fn() => [
                'unit_measure_optional' => $unitMeasureOptional->name,
            ]),
            'idbusinessarea' => $this->idbusinessarea,
            $this->mergeWhen($businessarea, fn() => [
                'businessarea' => $businessarea->name,
            ]),
            'idclassification' => $this->idclassification,
            $this->mergeWhen($classification, fn() => [
                'classification' => $classification->name,
            ]),

            'idattributes' => $this->idattributes,
            'idspecificattributes' => $this->idspecificattributes,
            'iduses' => $this->iduses,
            'idspecificuses' => $this->idspecificuses,
            'idwarehouses' => $this->idwarehouses,

            'idcompany' => $this->idcompany,
            $this->mergeWhen($company, fn() => [
                'company' => $company->business_name,
            ]),
            'status' => $this->status,
            'stockStore' => $stockStore
        ];
    }
}
