<?php

include_once( PLOG_CLASS_PATH."class/dao/model.class.php" );
include_once( PLOG_CLASS_PATH."class/template/cachecontrol.class.php" );

class ShoutboxInstaller extends Model {

  function ShoutboxInstaller($blogId, $blogSettings) {
    $this->blogSettings = $blogSettings;
    
    /* Modelize it! */
    $this->Model();
    
    /* Initialization */
    $this->blogId = $blogId;
  }
  
  function checkShoutbox() {  
    $dbPrefix = $this->getPrefix();
    
    $version = "1.0";
  
    $sql =  "SELECT * FROM " . $this->getPrefix() . "shoutbox_shouts ";
    $this->shoutsResult = $this->Execute($sql);
    if(!$this->shoutsResult) {
        $version = "no";
    }
    else {
      $sql = "SELECT auth FROM " . $this->getPrefix() . "shoutbox_shouts ";
      $this->shoutsResult = $this->Execute($sql);
      if(!$this->shoutsResult)
          $version = "0.x";
    }
    
    if($version == "no")
      return $this->createTable();
    else if($version == "0.x")
      return $this->upgrade_0x_100();

    return true;
  }

  function createTable() {
    $dbPrefix = $this->getPrefix();

    $sql = "SELECT * FROM {$dbPrefix}shoutbox_shouts";
    if(!$this->_db->Execute($sql)) {
      // Make new setup
      $sql = "
CREATE TABLE {$dbPrefix}shoutbox_shouts (
    shout_id INT(11) NOT NULL auto_increment,
    blog_id INT(11) NOT NULL,
    nickname TEXT NOT NULL,
    shout_text TEXT NOT NULL,
    shout_date DATETIME NOT NULL,
    auth CHAR(12),
    UNIQUE KEY cashout_id (shout_id)
)
";
      if( !$this->_db->Execute($sql) ) {
        $message = "An error occurred while trying to create the table {$dbPrefix}shoutbox_shouts. Please, create it manually. Start you favorite database manager (like phpmyadmin) and run the following code:<br><pre>$sql</pre>";
        return $message;
      }
    }
    
    return true;
  }
      
  // Upgrade from 0.x version to 1.0.0
  function upgrade_0x_100() {
    $dbPrefix = $this->getPrefix();

    $sql = "SELECT auth FROM {$dbPrefix}shoutbox_shouts";
    if( !$this->_db->Execute($sql) ) {
      // Make new setup
      $sql = "ALTER TABLE {$dbPrefix}shoutbox_shouts ADD COLUMN auth CHAR(12)";
      if( !$this->_db->Execute($sql) ) {
        $message = "An error occurred while trying to update the table {$dbPrefix}shoutbox_shouts. Please, update it manually. Start you favorite database manager (like phpmyadmin) and run the following code:<br><pre>$sql</pre>";
        return $message;
      }
    }
    
    return true;
  }
}
?>