<?php

class Product extends mfBaseModel {
  private $productgroup;
  private $producttech;
  private $sla;
  private $networks;
  private $attributes;
  
  public function loadAttributes() {
    if(!$this->producttech_id) {
      return false;
    }
    
    $this->attributes = [];
    
    // get tech attribs
    $ptattribs = ProducttechAttributeModel::search(['producttech_id' => $this->producttech_id]);
    // fill atrribs with existing values of product attribs
    foreach($ptattribs as $pta) {
      $attrib = ProductAttributeModel::getFirst(['product_id' => $this->id, 'producttechattribute_id' => $pta->id]);
      if(!$attrib) {
        $attrib = new ProductAttribute();
        $attrib->product_id = $this->id;
        $attrib->producttechattribute_id = $pta->id;
        $attrib->value = $pta->value;
        $attrib->note = $pta->note;
      }
      $attrib->name = $pta->name;
      $attrib->displayname = $pta->displayname;
      $attrib->description = $pta->description;
      $this->attributes[$attrib->name] = $attrib;
    }
    
    return true;
    
  }

  public function getProperty($name) {
    if($this->$name == null) {
      
      if($name == "networks") {
        $this->networks = [];
        $productNetworks = ProductNetworkModel::search(['product_id' => $this->id]);
        foreach($productNetworks as $pnet) {
          $this->networks[$pnet->network_id] = new Network($pnet->network_id);
        }
        return $this->networks;
      }
      
      if($name == "attributes") {
        $this->loadAttributes();
        return $this->attributes;
      }
      
      $classname = ucfirst($name);
      $idfield = $name."_id";
      $this->$name = new $classname($this->$idfield);
      
      if($this->$name->id) {
        return $this->$name;
      } else {
        return null;
      }
    }
    
    return $this->$name;
  }
}