<?php

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

include_once( PLOG_CLASS_PATH."plugins/currentlyaddictedto/class/dao/cat_music.class.php" );

/**
* schema of the table, so that we can tell ADOdb to create it
* automatically for us
*/
/*
define( ATOM_PASSWORDS_DB_SCHEMA,
        "user_id I(10) NOTNULL,
            password C(32) NOTNULL DEFAULT ''" );
*/

             
class CAT_ItemsFetcher extends Model {

    var $id;
    var $blogId;
    
    var $blogSettings;

    var $resultCounter;
    var $itemsResult;
    var $currentPage;

    function CAT_ItemsFetcher($blogId, $blogSettings) {
        $this->blogSettings = $blogSettings;
    
        /* Modelize it! */
        $this->Model();

        /* Check Setup */
        $this->createTable();
    
        /* Initialization */
        $this->blogId = $blogId;
    }

    
    ###########################################################
    # Database setup section. To be migrated to ADODB, but for the moment I can't get
    # it working :(
    function createTable() {
        $dbPrefix = $this->getPrefix();

        $sql = "SELECT * FROM {$dbPrefix}cat_items";
        if( !$this->_db->Execute($sql) ) {
            //echo("Seems there is no such a table! $sql");
            // Make new setup
            $sql = "
CREATE TABLE {$dbPrefix}cat_items (
    id INT(11) PRIMARY KEY auto_increment,
    blogid INT(11) NOT NULL,
    startdate DATETIME,
    enddate DATETIME DEFAULT NULL,
    permalink TEXT,
    reslink TEXT,
    rate INT NOT NULL DEFAULT 3,
    data TEXT,
    class TEXT
);
";
            if( !$this->_db->Execute($sql) ) {
                die("The database setup failed!<br> <pre>". $sql . '</pre>');
            }
        }
    }
    

    function getItems($classType, $notExpired = true, $ids = false) {
    
        $sql =  "SELECT * FROM " . $this->getPrefix() . "cat_items ";
        $sql .= "WHERE blogid =  {$this->blogId} AND class = '$classType' ";
        if($notExpired)
            $sql .= "AND endDate IS NULL ";
        else
            $sql .= "AND endDate IS NOT NULL ";

        if($ids)
            $sql .= "AND id IN($ids) ";
            
        $sql .= "ORDER BY enddate, startdate DESC";

        //echo($sql . '<br>');

        $this->itemsResult = $this->Execute($sql);
        if(!$this->itemsResult)
            die("Grr $sql");

        while($itemData = $this->itemsResult->FetchRow()) {
            eval("\$item = new $classType();");
            $item->init($itemData, $this->blogId, $this->blogSettings);
            $item->setData($itemData['data']);
            $res[] = $item;
        }
        
        return $res;
    }

    function getLastPage() {
        $sql =  "SELECT COUNT(*) as cnt FROM " . $this->getPrefix() . "cat_items ";
        $res = $this->Execute($sql);
        if(!$res)
            return 0;
        $cnt = $res->FetchRow();
        if($cnt['cnt'] > 0)
            $cnt = floor($cnt['cnt'] / 15);
        return $cnt;
    }


    function thinkAndDo() {
        return $this->getItemsArray();
    }
}

class CAT_Item extends Model {
    var $id;
    var $blogId;
    var $startDate;
    var $endDate;
    var $permalink;
    var $reslink;
    var $rate;

    var $blogSettings;
    var $blogId;

    function init($itemData, $blogId, $blogSettings) {
        $this->id = $itemData['id'];
        $this->startDate = $itemData['startdate'];
        $this->endDate = $itemData['enddate'];
        $this->permalink = $itemData['permalink'];
        $this->reslink = $itemData['reslink'];
        $this->rate = $itemData['rate'];
    
        $this->blogSettings = $blogSettings;
    
        /* Modelize it! */
        $this->Model();
    
        /* Initialization */
        $this->blogId = $blogId;
    }

    function expire() {
        $this->endDate = date('Y-m-d H:m');
        $this->save();
    }
    function unexpire() {
        $this->endDate = false;
        $this->save();
    }

    function setRate($r) {
        if(!$this->isRateable())
            return false;
            
        $sql =  "UPDATE " . $this->getPrefix() . "cat_items SET rate = $r WHERE id = {$this->id}";
        $result = $this->Execute($sql);
         if(!$result) {
            die("Sorry, coud not alter your item. $sql");
        }
    }

    function save() {
        if($this->id == 0)
            $this->_saveNew();
        else
            $this->_update();
    }

    function _saveNew() {
        $data = $this->getData();
        $class = $this->getClass();

        $this->startDate = date('Y-m-d H:m');

        if(!$this->rate)
            $this->rate = 3;
    
        $sql =  "INSERT INTO " . $this->getPrefix() . "cat_items (".
                "blogId,
                 permalink,
                 reslink,
                 rate,
                 data,
                 class,
                 startdate
                 ) VALUES (
                 {$this->blogId},
                 '{$this->permalink}',
                 '{$this->reslink}',
                 {$this->rate},
                 '$data',
                 '$class',
                 '{$this->startDate}'
                 )";
        //echo($sql);
        $result = $this->Execute($sql);
        if(!$result) {
            echo("Sorry, coud not add your item. $sql");
            return false;
        }
    }
    
    function _update() {
        $data = $this->getData();
        $class = $this->getClass();

         if(!$this->endDate || $this->endDate == '')
            $endDate = 'NULL';
        else
            $endDate = "'{$this->endDate}'";

        if(!$this->rate)
            $this->rate = 3;
    
        $sql =  "UPDATE " . $this->getPrefix() . "cat_items SET ".
                "permalink = '{$this->permalink}',
                 reslink = '{$this->reslink}',
                 rate = {$this->rate},
                 data = '$data',
                 enddate = $endDate
                 WHERE id = {$this->id}";
        $result = $this->Execute($sql);
        //echo($sql);
        if(!$result) {
            echo("Sorry, coud not alter your item. $sql");
            return false;
        }
    }


    function remove() {}

    //function getData() {}
    function getClass() {}
    function isRateable() {}

    function getRatingHtml() {
        for($i = 1; $i <= 5; $i++) {
            if($i != $this->rate)
                $res .= '<a href="?op=Currentlyaddictedto&sub_op=rate&class_type=' . $this->getClass() . '&rate=' .$i.'&id='.$this->id.'">' .$i.'</a> ';
            else
                $res .= "<b>{$this->rate}</b> ";
        }
        return $res;
    }
}

?>
