<?php
defined('PUBLIC_ACCESS') or die('Restricted Access');

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

class modDBTables  {
  private $baseDir;
  private $scope = "tabledata";
  private $table = "";
  private $columns = [];
  private $content = [];

  public function __construct($tableName) {
    $this->table = $tableName;
    $this->baseDir = basename(__DIR__); 
    if ($this->table != NULL) {
	
      $dal = new DAL();
      $sql = "SELECT COLUMN_NAME AS name FROM INFORMATION_SCHEMA.COLUMNS " .
             "WHERE TABLE_SCHEMA = 'newdi652_aratest' AND TABLE_NAME = '$this->table' " ;
      $this->columns = $dal->query($sql);
      
      $sql = "SELECT * FROM  . $this->table ORDER BY id " ;
      $this->content = $dal->query($sql);
	  
    }
  }

  public function get($prop) {
    return $this->$prop;
  }
  
  // Set the parcels for the project
  public function set($tableName) {
    if (isset($tableName)) {
      $this->table = $tableName;
      $this->selectTable($tableName);
    }   
  }

  public function set2($col_data) {
    if (isset($col_data)) {
       $this->modify ($col_data);
    }
  }

  private function modify ($col_data) {

    $dbRowId = $col_data['id'];  

    if ($dbRowId == 0) {
      $sql = "INSERT INTO $this->table ( " ;
      $firstOf = true;
      foreach ($this->columns as $col) {
        $colName = $col->name;
        if ($firstOf)
          $sql .= "$colName ";
        else 
          $sql .= ", $colName ";
        $firstOf = false;
      }
      $sql .= ") VALUES ( ";      
    
      $firstOf = true;
      foreach ($this->columns as $col) {
        $colData = $col_data[$col->name];
        if ($firstOf)
          $sql .= "\"$colData\"";
        else
          $sql .= ", \"$colData\"";
        $firstOf = false;
      }
      $sql .= ")";
      $dal = new DAL();
      $result = $dal->query($sql);

    }  
    else if ($dbRowId > 0) {
      $sql = "UPDATE $this->table SET " ;
    
      $firstOf = true;
      foreach ($this->columns as $col) {
        $colName = $col->name;
        $colData = $col_data[$colName];
        if ($firstOf)
          $sql .= "$colName=\"$colData\"";
        else
          $sql .= ", $colName=\"$colData\"";
        $firstOf = false;
      }
      $sql .= " WHERE id = $dbRowId ";

      $dal = new DAL();
      $result = $dal->query($sql);
    }  
    $this->selectTable ($this->table);
  }
  
  private function selectTable ($table){
      $dal = new DAL();
      $sql = "SELECT COLUMN_NAME AS name FROM INFORMATION_SCHEMA.COLUMNS " .
                 "WHERE TABLE_SCHEMA = 'newdi652_aratest' AND TABLE_NAME = '$table'" ;
      $this->columns = $dal->query($sql);
      
      $sql = "SELECT * FROM $table ORDER BY id ";
      $this->content = $dal->query($sql);
  }    
}

?>