<?php
  

class clsCustomMetaData extends clsItem
{
//    var $m_CustomDataId;
//    var $m_ResourceId;
//    var $m_CustomFieldId;
//    var $m_Value;

    var $FieldName;

    function clsCustomMetaData($CustomDataId=-1,$table="CustomMetaData")
    {
        $this->clsItem();
        $this->tablename=GetTablePrefix()."CustomMetaData";
        $this->type=12;
        $this->BasePermission="";
        $this->id_field = "CustomDataId";
        $this->NoResourceId=1; //set this to avoid using a resource ID

        if(isset($CustomDataId))
            $this->LoadFromDatabase($CustomDataId);
    }

    function Validate()
    {
 	global $Errors;

        $dataValid = true;
        if(!strlen($this->Get("ResourceId")))
        {
            $Errors->AddError("error.fieldIsRequired",'ResourceId',"","",get_class($this),"Validate");
            $dataValid = false;
        }
        return $dataValid;
    }

    function SetFieldName($name)
    {
      $this->FieldName = $name;
    }
    
    function GetFieldName()
    {
      return $this->FieldName;
    }

    function Save()
    {
        if(is_numeric($this->Get("CustomDataId")))
        {
            $this->Update();
        }
        else
            $this->Create();
    }

    /*
    function LoadFromDatabase($Id)
    {
        global $objSession, $Errors;

        if(!isset($Id))
        {
            $Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
            return false;
        }
        $sql = sprintf("SELECT * FROM ".$this->SourceTable." WHERE CustomDataId = '%s'",$Id);
        $result = $this->adodbConnection->Execute($sql);
        if ($result === false)
        {
            $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
            return false;
        }
        $data = $result->fields;
        $this->SetFromArray($data);
        $this->Clean();
        return true;
    }
    */
} /*clsCustomMetaData*/

class clsCustomDataList extends clsItemCollection
{

  function clsCustomDataList($table="")
  {
    $this->clsItemCollection();
    $this->classname = "clsCustomMetaData";
    if(!strlen($table))
        $table = GetTablePrefix()."CustomMetaData";
    $this->SetTable('live', $table);
  }

  function LoadResource($ResourceId)
  {
      $sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=".$ResourceId;
      $this->Query_Item($sql);
      return $this->Items;
  }
  
  function DeleteResource($ResourceId)
  {
      $sql = "DELETE FROM ".$this->SourceTable." WHERE ResourceID=".$ResourceId;
      $this->adodbConnection->Execute($ResourceId);
  }
  
  function &SetFieldValue($FieldId,$ResourceId,$Value)
  {
    // so strange construction used, because in normal
    // way it doesn't work at all (gets item copy not
    // pointer)
    $index = $this->GetDataItem($FieldId, true);
    
    if($index !== false)
    	$d =& $this->Items[$index];
    else
    	$d = null;
    
    if(is_object($d))
    {
      $d->Set("Value",$Value);
      if(!strlen($Value))
      {
      	for($x=0;$x<count($this->Items);$x++)
      	{
      		if($this->Items[$x]->Get("CustomFieldId")==$FieldId &&
      		   $this->Items[$x]->Get("ResourceId")==$ResourceId)
      		{
      		  $this->Items[$x]->Set("CustomFieldId",0);
      		  break;
      		}
      	}	
      	$d->Delete();
      }
    }
    else
    {
      if(strlen($Value)>0)
      {
        $d = new clsCustomMetaData();
        $d->Set("CustomFieldId",$FieldId);
        $d->Set("ResourceId",$ResourceId);
        $d->Set("Value",$Value);
        array_push($this->Items,$d);
      }
    }
    return $d;
  }

  function &GetDataItem($id, $return_index = false)
  {
    // $id - custom field id to find
    // $return_index - return index to items, not her.
    $found = false;
    $index = false;
    for($i = 0; $i < $this->NumItems(); $i++)
    {
        $d =& $this->GetItemRefByIndex($i);
        if($d->Get("CustomFieldId")==$id)
        {  
            $found=TRUE;
            break;
        }                  
    }
    return $found ? ($return_index ? $i : $d) : false;
  }

  function SaveData()
  {
      foreach($this->Items as $f)
      {
        $FieldId = $f->Get("CustomFieldId");
        $value = $f->Get("Value");
        $ResId = $f->Get("ResourceId");
        $DataId = $f->Get("CustomDataId");
        if(is_numeric($DataId))
        {
            $sql = "UPDATE ".$this->SourceTable." SET Value='".$value."' WHERE CustomFieldId='$FieldId' AND ResourceId='$ResId'";
            $this->adodbConnection->Execute($sql);
        }
        else
        {
        	if($FieldId>0)
        	{
              $sql = "INSERT INTO ".$this->SourceTable." (ResourceId,CustomFieldId,Value) VALUES ('".$ResId."','$FieldId','$value')";
              $this->adodbConnection->Execute($sql);
        	}
        }
      }
      
      $rs = $this->adodbConnection->Execute("SELECT * FROM ".$this->SourceTable." WHERE CustomDataId=0 ");
      while($rs && !$rs->EOF)
      {
          $m = $this->adodbConnection->Execute("SELECT MIN(CustomDataId) as MinValue FROM ".$this->SourceTable);
          $NewId = $m->fields["MinValue"]-1;

          $sql = "UPDATE ".$this->SourceTable." SET CustomDataId=$NewId WHERE ResourceId=".$rs->fields["ResourceId"]." AND ";
          $sql .= "CustomFieldId=".$rs->fields["CustomFieldId"];
          $this->adodbConnection->Execute($sql);
          $rs->MoveNext();
      }
  }

  function CopyToEditTable($idfield, $idlist)
  {
      global $objSession;

      $edit_table = $objSession->GetEditTable($this->SourceTable);
      @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
      if(is_array($idlist))
      {
        $list = implode(",",$idlist);
      }
      else
           $list  = $idlist;
      $query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield IN ($list)";
      $insert = "CREATE TABLE ".$edit_table." ".$query;
      if((int)$GLOBALS["debuglevel"])
          echo $insert;
      $this->adodbConnection->Execute($insert);      
      $this->SourceTable = $edit_table;
      $this->SaveData();

  }

  function CopyFromEditTable($ResourceId)
  {
      global $objSession;

      $edit_table = $objSession->GetEditTable($this->SourceTable);
      $idlist = array();
      
      //$this->adodbConnection->Execute($sql);
      
      $sql = "SELECT * FROM $edit_table";
      $this->Clear();
      $rs = $this->adodbConnection->Execute($sql);
      while($rs && !$rs->EOF)
      {
          $data = $rs->fields;
          
          $c = $this->AddItemFromArray($data);
          if(strlen($data["Value"])>0)
          { 
            $c->Dirty();         
            if($data["CustomDataId"]>0)
            {
              
              $c->Update();
            }
            else
            {
              $c->UnsetIdField();
              $c->Create();
            }
            $idlist[] = $c->Get("CustomDataId");                                          
         }
          else
          {
              $sql = "DELETE FROM ".$this->SourceTable." WHERE ResourceId=".$data["ResourceId"]." AND CustomFieldId=".$data["CustomFieldId"];
              //echo $sql."<br>\n";
              $this->adodbConnection->Execute($sql);
          }
         $rs->MoveNext();
      }     
      @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
  }  

} /* clsCustomDataList */
?>