<?php
 
require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/db.php');

class modInstances  {
  private $path;  
  private $instances;
  
  public function __construct() {
      
    $dal = new DAL();
    $sql = "SELECT CI.id, SPACE(0) AS 'select', instance, location, CC.control  " .
           "FROM controlinit CI, controlconfig CC " .
           "WHERE CI.controlconfig_id = CC.id AND CI.active = 1 " .
           "ORDER BY CC.control, CI.location ";
    $this->instances = $dal->query($sql);
    
    $default = array ("id"=>0, "instance"=>"", "location"=>"");
    $this->form_defs = $this->toObject ($default);


    $sql = "SELECT id, control AS descr FROM controlconfig";
    $this->controls = $dal->query($sql);
  }
  
  private function toObject($array) {
    $object = new stdClass();
    foreach ($array as $key => $value) {
      if (is_array($value)) {
        $value = $this->toObject($value);
      }
      $object->$key = $value;
    }
    return $object;
  }


  public function get($prop) {
    return $this->$prop;
  }
  
  public function setInit($ci_id, $instance, $location) {
    $this->modifyInit ($ci_id, $instance, $location);
  }  

  public function setEntry($ce_id, $controlinit_id, $property, $value) {
    $this->modifyEntry ($ce_id, $controlinit_id, $property, $value);
  }  
  
  

  private function modifyInit ($ci_id, $instance, $location) {
      
    $dal = new DAL();

    if ($ci_id == 0) {
      $sql = "INSERT INTO controlinit (instance, location) VALUES ('$instance', '$location')";
      $this->selInit = $dal->query($sql);
    }  

    else {
      $sql = "UPDATE controlinit SET instance='$instance', location='$location' " .
             "WHERE id=$ci_id ";
      $result = $dal->query($sql);
      $this->selInit = $ci_id;
    }
    
    $sql = "SELECT id, controlconfig_id, instance, location FROM controlinit ORDER BY controlconfig_id";
    $this->instances = $dal->query($sql);
  }    

  private function modifyEntry ($ce_id, $controlinit_id, $property, $value) {
      
    $dal = new DAL();

    if ($ce_id == 0) {
      $sql = "INSERT INTO controlentry (controlinit_id, property, value) VALUES ('$controlinit_id','$property', '$value')";
      $this->selEntry = $dal->query($sql);
      $this->selInit = $controlinit_id;
    }  

    else {
      $sql = "UPDATE controlentry SET controlinit_id=$controlinit_id, property='$property', value='$value' " .
             "WHERE id=$ce_id ";
      $result = $dal->query($sql);
      $this->selEntry = $ce_id;
      $this->selInit = $controlinit_id;
    }
  }    
}

?>