<?php

namespace App\Models;

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

use App\Models\KeysPicture;

class Key extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'model_number',
        'asset_assignee_user_type_id',
        'description',
        'replacement_cost',
        'track_inventory',
        'start_amount',
        'total',
        'on_hand',
        'loaned',
        'lost_damaged',
        'property_id',
        'creator_id',
        'owner_id'
    ];  
    
    public function getSingleKey($key_id){
        
        if(empty($key_id)){
            return [];
        }
        
        $key = parent::
            select(
                'keys.*',
                'assets_assignees_users_types.type as asset_assignee_user_type'
                )
            ->join('assets_assignees_users_types', 'keys.asset_assignee_user_type_id', '=', 'assets_assignees_users_types.id')
            ->where('keys.id', $key_id)->first();
            
        $pictures = KeysPicture::where(['key_id'=>$key_id])->get();
        $key['pictures'] = (!empty($pictures)) ? $pictures->toArray() : [];
        
        return $key;
        
    }
    
    public function getKeysByOwnerId($owner_id){
        
        if(empty($owner_id)){
            return [];
        }
        
        $keys = parent::
            select(
                'keys.*',
                'assets_assignees_users_types.type as asset_assignee_user_type'
                )
            ->join('assets_assignees_users_types', 'keys.asset_assignee_user_type_id', '=', 'assets_assignees_users_types.id')
            ->where(['owner_id'=>$owner_id])->get();
            
            
        $keys = (!empty($keys)) ? $keys->toArray() : [];
        
        for($i=0; $i<count($keys); $i++){
            
            $key_id = $keys[$i]['id'];
            
            $pictures = KeysPicture::where(['key_id'=>$key_id])->get();
            $keys[$i]['pictures'] = (!empty($pictures)) ? $pictures->toArray() : [];
            
        }
        
        return $keys;
        
    }
    
}
