<?php

namespace App\Models;

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

use App\Models\PropertiesMeasurementsPicture;
use App\Models\PropertiesMeasurementsFile;
use App\Models\PropertiesMeasurement;

class PropertiesMeasurement extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'property_id',
        'measurement_type_id',
        'property_location_id',
        'measurement_unit_id',
        'length',
        'width',
        'height',
        'depth',
        'amount',
        'notes'
    ];    
    
    public function getPropertyMeasurements($property_id)
    {
        
        if(empty($property_id)){
            return [];
        }
        
        $measurements = PropertiesMeasurement::
            select(
                'properties_measurements.*',
                'measurements_types.type as measurement_type', 
                'measurements_units.unit as measurement_unit', 
                'properties_locations.location as property_location'
                )
            ->join('measurements_types', 'properties_measurements.measurement_type_id', '=', 'measurements_types.id')
            ->join('measurements_units', 'properties_measurements.measurement_unit_id', '=', 'measurements_units.id')
            ->join('properties_locations', 'properties_measurements.property_location_id', '=', 'properties_locations.id')
            ->where(['properties_measurements.property_id'=>$property_id])->get();
            
        $measurements = (!empty($measurements)) ? $measurements->toArray() : [];
        
        for($i=0; $i<count($measurements); $i++){
            
            $property_measurement_id = $measurements[$i]['id'];
            
            $pictures = PropertiesMeasurementsPicture::where(['property_measurement_id'=>$property_measurement_id])->get();
            $measurements[$i]['pictures'] = (!empty($pictures)) ? $pictures->toArray() : [];
            
            $files = PropertiesMeasurementsFile::where(['property_measurement_id'=>$property_measurement_id])->get();
            $measurements[$i]['files'] = (!empty($files)) ? $files->toArray() : [];
            
        }
        
        return $measurements;
        
    }
    
}
