<?php

class ModelBlogPost extends Fiktiv_Model_Abstract
{
    protected $_schema   = 'fiktivkod';
    protected $_name     = 'Post';
    protected $_primary  = 'id';
    protected $_rowClass = 'Post';

    protected $_dependentTables = array('ModelUser', 'ModelPostTag');

    public function findByMonth()
    {
        $posts = $this->select()->from($this->_name, array('Month' => 'DATE_FORMAT(pubDate,"%Y %M")', 'Date' => 'DATE_FORMAT(pubDate,"%Y-%M")'))
                                ->group('Month')
                                ->query()
                                ->fetchAll();
                                
        return $posts;
    }

    public function findByAuthor($user)
    {
        if ($user instanceof  User) {

        } else if (is_integer($user)) {

        }
    }

    /**
     * Find all posts with tag.
     * 
     * @param string $tag
     * @return mixed
     */
    public function findByTag($tag)
    {
        $tags = new ModelTag();

        $row = $tags->fetchRow($this->quoteInto('name = ?', $tag));
        
        if ($row) {
            $posts = $row->findManyToManyRowset('ModelBlogPost', 'ModelPostTag');
 
            return $posts;
        }

        return null;
    }

    public function findByDate($date, $format)
    {
        $date = new Fiktiv_Date($date, $format, Zend_Registry::get('Zend_Locale'));
        
        $where = $this->quoteInto('DATE_FORMAT(pubDate,"%Y %m") LIKE ?', $date->toString('yyyy MM'));

        return $this->fetchAll($where);
    }

    public function findByPermlink($permlink)
    {
        return $this->fetchRow($this->quoteInto('permlink = ?', $permlink));
    }

    public function createPost($data, $id = null)
    {
        $myTags = explode(',', $data['tags']);
        unset($data['tags']);

        if (null == $id) {
            $data['userId'] = Zend_Auth::getInstance()->getIdentity()->id;
            $data['pubDate'] = Zend_Date::now()->getIso();
            $data['isPublished'] = 1;
            $data['permlink'] = $this->generatePermalink($data['title']);
        }

        if ($id) {
            $row = $this->find($id)->current();
            $row->setFromArray($data);
            $row->save();
        } else {
            $row = $this->find($this->insert($data))->current();
        }

        if ($myTags) {
            $tags = new ModelTag();
            $tags->tagsToPost($myTags, $row->id);
        }

    }

    protected function generatePermalink($title)
    {
        $permalink = date('Y-m').'-'.$title;

        // All to lowercase
        $permalink = strtolower($permalink);

        // Remove special characters
        $permalink = filter_var($permalink, FILTER_SANITIZE_SPECIAL_CHARS);
        
        // Replace stuff
        $replace = array(
            ' ' => '-',
            'å' => 'a',
            'ä' => 'a',
            'ö' => 'o',
            '_' => '-',
            '!' => '',
            '?' => '',
            '.' => '',
            ',' => '',
        );
        foreach($replace as $char => $value) {
            $permalink = str_replace($char,$value,$permalink);
        }

        return $permalink;
    }
}