<?php

	lt_include( PLOG_CLASS_PATH."class/dao/model.class.php" );
	lt_include( PLOG_CLASS_PATH."plugins/crystalpoll/class/dao/poll.class.php" );

    /**
     * Polls
     */
	class Polls extends Model
	{
	    /**
	     * Initialize variables
	     */
    	function Polls()
        {
        	$this->Model();
        	$this->table = $this->getPrefix().'polls';
        	$this->pk = 'id';
        }

        /**
         * Get poll object by it's id
         *
         * @param int $id
         * @return Poll object
         */
        function getPoll( $id )
        {
            $query = "SELECT * FROM {$this->table} WHERE id = ".DB::qstr( $id );
            return $this->_getPollFromQuery( $query );
        }
        

        /**
         * Get all polls for specific blog
         *
         * @param int $blogId
         * @return array of Polls
         */
        function getBlogPolls( $blogId )
        {
            $query = "SELECT * FROM {$this->table} WHERE blog_id = ".DB::qstr( $blogId );
            return $this->_getPollsFromQuery( $query );
        }
        
        /**
         * Get votes count for each choice in specific poll
         *
         * @param  int $pollId
         * @return array of votes counts
         */
        function getChoicesVotesCount($pollId)
        {
            $query = "SELECT choice_id, COUNT(*) as count FROM ".$this->getPrefix()."poll_votes 
                      WHERE poll_id = ".DB::qstr( $pollId )." group by choice_id";
            $result = $this->Execute( $query );
            if( !$result ) {
                return false;
            }
            $choices = array();
            while( $row = $result->FetchRow() ) {
                $choices[$row['choice_id']] = $row['count'];
            }
            return $choices;
        }
        
        /**
         * Check if there is any vote for specific poll from specific IP address
         *
         * @param String $clientIp
         * @param int $pollId
         * @return true if vote exists or false if not
         */
        function validateVoteByIp( $clientIp, $pollId )
        {
            $query = "SELECT COUNT(*) as count FROM ".$this->getPrefix()."poll_votes
                      WHERE ip = '".DB::qstr( $clientIp )."' AND poll_id = ".DB::qstr( $pollId );
            $result = $this->Execute( $query );
            if( !$result ){
                return false;
            }
            $row = $result->FetchRow();
            return $row['count'];
        }
        
        /**
         * Add vote to database
         *
         * @param int $pollId
         * @param int $choiceId
         * @param String $ip
         * @param date $date
         * @return true if added successfully
         */
        function addPollVote( $pollId, $choiceId, $ip, $date )
        {
            $query = "INSERT INTO ".$this->getPrefix()."poll_votes( poll_id, choice_id, ip, date )
                      VALUES( ".DB::qstr($pollId).", ".DB::qstr($choiceId).", '".DB::qstr($ip)."', '".DB::qstr($date)."')";
            return $this->Execute( $query );
        }

        /**
         * Add poll to database
         *
         * @param Poll $poll
         * @return true if added successfully
         */
        function addPoll( &$poll )
        {
            return $this->add( $poll );
        }

        /**
         * update poll
         *
         * @param Poll $poll
         * @return true if updated successfully
         */
        function updatePoll( $poll )
        {
             if( !$this->update( $poll ) ) {
                 return false;
             }
             return $this->deletePollVotes($poll->getId());
        }
        
        /**
         * Delete poll
         *
         * @param int $pollId
         * @return true if deleted successfully
         */
        function deletePoll( $pollId )
        {
            if( !$this->delete( 'id', $pollId ) ) {
                return false;
            }
            return $this->deletePollVotes($pollId);
        }
        
        /**
         * Delete all votes for specific poll
         *
         * @param int $pollId
         * @return true fi deleted successfully
         */
        function deletePollVotes( $pollId )
        {
            $query = "DELETE FROM ".$this->getPrefix()."poll_votes WHERE poll_id = ".DB::qstr( $pollId );
            return $this->Execute($query);
        }

        /**
         * Get blog polls settings
         *
         * @param int $blogId
         * @return array of poll settings
         */

        function getPollsSettings( $blogId )
        {
            $query = "SELECT * FROM ".$this->getPrefix()."polls_settings WHERE blog_id = ".DB::qstr( $blogId );
            $result = $this->Execute($query);
            if( !$result ) {
                return false;
            }
            if( $row = $result->FetchRow() ) {
                return unserialize( $row['settings'] );
            }
            return false;
        }
        
        /**
         * Add blog polls settings
         *
         * @param int $blogId
         * @param array $settings
         * @return true if added successfully
         */
        function addPollsSettings( $blogId, $settings = array() )
        {
            $query = "INSERT INTO ".$this->getPrefix()."polls_settings 
                      VALUES( ".DB::qstr( $blogId ).", '".DB::qstr( serialize($settings) )."')";
            return $this->Execute($query);
        }
        
        /**
         * Update blog polls settings
         *
         * @param int $blogId
         * @param array $settings
         * @return true if updated successfully
         */
        function updatePollsSettings( $blogId, $settings = array() )
        {
            $query = "UPDATE ".$this->getPrefix()."polls_settings 
                      SET settings = '".DB::qstr( serialize($settings) )."'
                      WHERE blog_id = ".DB::qstr( $blogId );
            return $this->Execute($query);
        }

        function createTables()
        {
            $pollsTable = $this->getPrefix().'polls';
            $votesTable = $this->getPrefix().'poll_votes';
            $settingsTable = $this->getPrefix().'polls_settings';
            
            $querys[] = "CREATE TABLE $pollsTable( id int(10) AUTO_INCREMENT PRIMARY KEY, text text, blog_id int(10), choices text )";
            $querys[] = "CREATE INDEX blog_id ON $pollsTable( blog_id )";
            
            $querys[] = "CREATE TABLE $votesTable( id int(10) AUTO_INCREMENT PRIMARY KEY, poll_id int(10), choice_id int(10) , ip varchar(20), date date )";
            $querys[] = "CREATE INDEX poll_id On $votesTable( poll_id )";
            $querys[] = "CREATE INDEX choice_id On $votesTable( choice_id )";
            
            $querys[] = "CREATE TABLE $settingsTable( blog_id int(10) PRIMARY KEY, settings text)";
            
            foreach($querys as $query) {
                if( !$this->Execute( $query ) ) {
                    return false;
                }
            }
            return true;
        }
        function tablesExists()
        {
            $pollsTable = $this->getPrefix().'polls';
            $votesTable = $this->getPrefix().'poll_votes';
            $settingsTable = $this->getPrefix().'polls_settings';
            
            $querys[] = "show tables like '$pollsTable'";
            $querys[] = "show tables like '$votesTable'";
            $querys[] = "show tables like '$settingsTable'";
            
            $returnValue = true;
            foreach($querys as $query) {
                $result = $this->Execute( $query );
                if( $result ) {
                    $returnValue = ($returnValue && $result->RowCount());
                } else {
                    return false;
                }
            }
            return $returnValue;
        }
        /**
         * @private
         */
        
        function _getPollsFromQuery( $query )
        {
            // we send the query and then fetch the first array with the result
            $result = $this->Execute( $query );
            if( !$result ) {
                return false;
            }
            
            if ( $result->RecordCount() == 0) {
                $result->Close();
                return false;
            }

            $polls = array();
            while( $row = $result->FetchRow( $result ) ) {
                $polls[] = $this->mapRow( $row );
            }
            $result->Close();
            return $polls;
        }
        
        function _getPollFromQuery( $query )
        {
            // we send the query and then fetch the first array with the result
            $result = $this->Execute( $query );
            if( !$result ) {
                return false;
            }
            
            if ( $result->RecordCount() == 0) {
                $result->Close();
                return false;
            }

            $row = $result->FetchRow( $result );
            $poll = $this->mapRow( $row );
            $result->Close();
            
            return $poll;
        }
        
        function mapRow( $row )
        {
            $choices = unserialize( $row["choices"] );
        	$poll = new Poll( $row["text"], $row["blog_id"], $choices, $row["id"] );
            return $poll;
        }
    }
?>