<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\UnitsMaterialsPicture;
use App\Models\UnitsMaterialsFile;
use App\Models\UnitsMaterial;
use App\Models\Unit;

class UnitsMaterial extends Model
{
    use HasFactory;
    protected $fillable = [
        'unit_id',
        'material_type_id',
        'material_id',
        'property_location_id',
        'last_installed',
        'installed_by',
        'install_notes'
    ];    
    
    public static function getUnitMaterials($unit_id){
        
        if(empty($unit_id)){
            return [];
        }
        
        $materials = parent::
            select(
                'units_materials.*',
                'units_locations.location as unit_location'
                )
            ->join('units_locations', 'units_materials.unit_location_id', '=', 'units_locations.id')
            ->where(['units_materials.unit_id'=>$unit_id])->get();
            
            
        $materials = (!empty($materials)) ? $materials->toArray() : [];
        
        for($i=0; $i<count($materials); $i++){
            
            $unit_material_id = $materials[$i]['id'];
            
            $pictures = UnitsMaterialsPicture::where(['unit_material_id'=>$unit_material_id])->get();
            $materials[$i]['pictures'] = (!empty($pictures)) ? $pictures->toArray() : [];
            
            $files = UnitsMaterialsFile::where(['unit_material_id'=>$unit_material_id])->get();
            $materials[$i]['files'] = (!empty($files)) ? $files->toArray() : [];
            
        }
        
        return $materials;
        
        
    }
    
    
}
