<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

use App\Models\UnitsMeasurementsPicture;
use App\Models\UnitsMeasurementsFile;
use App\Models\UnitsMeasurement;

class UnitsMeasurement extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'unit_id',
        'measurement_type_id',
        'unit_location_id',
        'measurement_unit_id',
        'length',
        'width',
        'height',
        'depth',
        'notes'
    ];    
    
    public function getUnitMeasurements($unit_id)
    {
        
        if(empty($unit_id)){
            return [];
        }
        
        $measurements = UnitsMeasurement::
            select(
                'units_measurements.*',
                'measurements_types.type as measurement_type', 
                'measurements_units.unit as measurement_unit', 
                'units_locations.location as unit_location'
                )
            ->join('measurements_types', 'units_measurements.measurement_type_id', '=', 'measurements_types.id')
            ->join('measurements_units', 'units_measurements.measurement_unit_id', '=', 'measurements_units.id')
            ->join('units_locations', 'units_measurements.unit_location_id', '=', 'units_locations.id')
            ->where(['units_measurements.unit_id'=>$unit_id])->get();
            
        $measurements = (!empty($measurements)) ? $measurements->toArray() : [];
        
        for($i=0; $i<count($measurements); $i++){
            
            $unit_measurement_id = $measurements[$i]['id'];
            
            $pictures = UnitsMeasurementsPicture::where(['unit_measurement_id'=>$unit_measurement_id])->get();
            $measurements[$i]['pictures'] = (!empty($pictures)) ? $pictures->toArray() : [];
            
            $files = UnitsMeasurementsFile::where(['unit_measurement_id'=>$unit_measurement_id])->get();
            $measurements[$i]['files'] = (!empty($files)) ? $files->toArray() : [];
            
        }
        
        return $measurements;
        
    }
    
}
