<?php defined('MW_PATH') || exit('No direct script access allowed');

/**
 * Article
 * 
 * @package MailWizz EMA
 * @author Serban George Cristian <cristian.serban@mailwizz.com> 
 * @link http://www.mailwizz.com/
 * @copyright 2013-2014 MailWizz EMA (http://www.mailwizz.com)
 * @license http://www.mailwizz.com/license/
 * @since 1.0
 */

/**
 * This is the model class for table "article".
 *
 * The followings are the available columns in table 'article':
 * @property integer $article_id
 * @property string $title
 * @property string $slug
 * @property string $content
 * @property string $status
 * @property string $date_added
 * @property string $last_updated
 *
 * The followings are the available model relations:
 * @property ArticleCategory[] $categories
 * @property ArticleCategory[] $activeCategories
 */
class Teams extends Article
{
    const STATUS_PUBLISHED = 'published';

    const STATUS_UNPUBLISHED = 'unpublished';

    const PROJECTS = '17';
    const FLOOR_PLAN  = '26';
    const SITE_MAP  = '27';
    public $roles;
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{article}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        $rules = array(
            array('title, slug, content, status', 'required'),
            array('insta', 'email'),
            array('title,sub_title,linked_in,twitter,insta,telegram,facebook', 'length', 'max' => 200),
            array('linked_in,twitter,telegram,facebook', 'url', 'defaultScheme' => 'https'),
            array('slug', 'length', 'max' => 255),
            array('status', 'in', 'range' => array(self::STATUS_PUBLISHED, self::STATUS_UNPUBLISHED)),
            array('page_title,meta_title,meta_keywords,meta_description,category_id,youtube_url,roles,banner,phone,mobile,f_type,profile_banner,r_customer',  'safe'),
            // The following rule is used by search().
            array('title, status,', 'safe', 'on' => 'search'),
        );

        return CMap::mergeArray($rules, parent::rules());
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        $relations = array(
            'customer' => array(self::BELONGS_TO, 'ListingUsers', 'r_customer'),
        );

        return CMap::mergeArray($relations, parent::relations());
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        $labels = array(
            'article_id'    => Yii::t('articles', 'Article'),
            'sub_title'       => 'Designation',
            'title'         => Yii::t('articles', 'Name'),
            'slug'          => Yii::t('articles', 'Slug'),
            'content'       => Yii::t('articles', 'Content'),
            'page_title' => 'Phone Number',
            'sub_title' => 'Designation',
            'banner' => 'Photo',
            'phone' => 'WhatsApp (If only differed from phone number)',
            'profile_banner' => 'Banner Image [982X700 pixel]',
            'insta' => 'Instagram',
            'roles' => 'Languages Known',
            'r_customer' => 'Customer',
            'facebook' => 'vCard URL',
            'insta' => 'Email Address',
            'meta_title' => 'RERA Permit No',
            'youtube_url' => 'Agent BRN:'

        );

        return CMap::mergeArray($labels, parent::attributeLabels());
    }
    public function getDetailLabel()
    {
        switch ($this->category_id) {

            case '20':
                return 'Designation';
                break;
            default:
                return 'Designation';
                break;
        }
    }
    protected function afterSave()
    {

        $ArticleRole = new ArticleRole;
        if (!$this->isNewRecord) {
            $ArticleRole->deleteAllByAttributes(array('article_id' => $this->primaryKey));
        }
        /*saving property types*/
        $post =  $this->roles;

        if (!empty($post)) {


            foreach ($post as $iv) {


                $ArticleRole->isNewRecord = true;
                $ArticleRole->master_id = $iv;
                $ArticleRole->article_id  = $this->primaryKey;;
                $ArticleRole->save();
            }
        }


        parent::afterSave();
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public $category_id;


    public function search($return = false)
    {
        $criteria = new CDbCriteria;

        $criteria->compare('t.title', $this->title, true);
        $criteria->compare('t.status', $this->status, true);
        $criteria->compare('t.f_type', 'Te');

        if (Yii::app()->isAppName('frontend')) {
            $criteria->order = '-t.priority desc, t.article_id DESC';
        }
        if (!empty($return)) {
            return $criteria;
        }
        return new CActiveDataProvider(get_class($this), array(
            'criteria'      => $criteria,
            'pagination'    => array(
                'pageSize'  => $this->paginationOptions->getPageSize(),
                'pageVar'   => 'page',
            ),
            'sort'  => array(
                'defaultOrder' => array(
                    'article_id' => CSort::SORT_DESC,
                ),
            ),
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Article the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    protected function afterConstruct()
    {

        $this->fieldDecorator->onHtmlOptionsSetup = array($this, '_setDefaultEditorForContent');
        parent::afterConstruct();
    }

    protected function afterFind()
    {
        //$this->content = Yii::app()->ioFilter->purify($this->content);
        $this->fieldDecorator->onHtmlOptionsSetup = array($this, '_setDefaultEditorForContent');
        parent::afterFind();
    }

    protected function beforeValidate()
    {
        $category = new ArticleCategory();
        $category->slug = $this->slug;
        $this->slug = $category->generateSlug();
        $this->slug = $this->generateSlug();
        $this->f_type = 'Te';
        return parent::beforeValidate();
    }

    public function generateSlug()
    {
        Yii::import('common.vendors.Urlify.*');
        $string = !empty($this->slug) ? $this->slug : $this->title;
        $slug = URLify::filter($string);
        $article_id = (int)$this->article_id;

        $criteria = new CDbCriteria();
        $criteria->addCondition('article_id != :id AND slug = :slug');
        $criteria->params = array(':id' => $article_id, ':slug' => $slug);
        $exists = $this->find($criteria);

        $i = 0;
        while (!empty($exists)) {
            ++$i;
            $slug = preg_replace('/^(.*)(\d+)$/six', '$1', $slug);
            $slug = URLify::filter($slug . ' ' . $i);
            $criteria = new CDbCriteria();
            $criteria->addCondition('article_id != :id AND slug = :slug');
            $criteria->params = array(':id' => $article_id, ':slug' => $slug);
            $exists = $this->find($criteria);
        }

        return $slug;
    }

    public function _setDefaultEditorForContent(CEvent $event)
    {
        if ($event->params['attribute'] == 'content') {
            $options = array();
            if ($event->params['htmlOptions']->contains('wysiwyg_editor_options')) {
                $options = (array)$event->params['htmlOptions']->itemAt('wysiwyg_editor_options');
            }
            $options['id'] = CHtml::activeId($this, 'content');
            $event->params['htmlOptions']->add('wysiwyg_editor_options', $options);
        }
    }

    public function getSelectedCategoriesArray()
    {
        $selectedCategories = array();
        if (!$this->isNewRecord) {
            $categories = ArticleToCategory::model()->findAllByAttributes(array('article_id' => (int)$this->article_id));
            foreach ($categories as $category) {
                $selectedCategories[] = $category->category_id;
            }
        } else {
            if (!Yii::app()->request->isPostRequest and !empty($this->category_id)) {
                $selectedCategories[] = $this->category_id;
            } else {
                $selectedCategories = (array) @$_POST['ArticleToCategory'];
            }
        }
        return $selectedCategories;
    }

    public function getAvailableCategoriesArray()
    {
        $category = new ArticleCategory();
        return $category->getRelationalCategoriesArray();
    }
    public function getfindCategoryThis()
    {
        $criteria = new CDbCriteria();
        $criteria->join = 'INNER JOIN {{article_to_category}} ac on ac.article_id = :this and ac.category_id = t.category_id ';
        $criteria->params[':this'] = $this->primaryKey;
        $criteria->distinct = 't.category_id';
        return ArticleCategory::model()->find($criteria);
    }
    public function getPermalink($absolute = false)
    {
        return Yii::app()->apps->getAppUrl('frontend', 'article/' . $this->slug, $absolute);
    }

    public function getStatusesArray()
    {
        return array(
            ''                          => Yii::t('app', 'Choose'),
            self::STATUS_PUBLISHED      => Yii::t('articles', 'Published'),
            self::STATUS_UNPUBLISHED    => Yii::t('articles', 'Unpublished'),
        );
    }

    public function getStatusText()
    {
        $statuses = $this->getStatusesArray();
        return isset($statuses[$this->status]) ? $statuses[$this->status] : $this->status;
    }

    public function attributeHelpTexts()
    {
        $texts = array();
        return CMap::mergeArray($texts, parent::attributeHelpTexts());
    }

    public function attributePlaceholders()
    {
        $placeholders = array();

        return CMap::mergeArray($placeholders, parent::attributePlaceholders());
    }

    public function getExcerpt($length = 200)
    {
        return StringHelper::truncateLength($this->content, $length);
    }

    public function getDelvelopmentList($notid = "")
    {
        $criteria = new CDbCriteria();
        $criteria->order = 't.article_id DESC';
        $criteria->with = array('categories');
        $criteria->select = 't.title,t.slug';;
        $criteria->condition = 't.status=:pub and  categories.category_id=:parent and t.article_id!=:notin';
        $criteria->params[':parent']   = self::PROJECTS;
        $criteria->params[':notin']   = $notid;
        $criteria->together = true;
        $criteria->params[':pub']      = self::STATUS_PUBLISHED;
        $criteria->limit = 10;
        return  $this->findAll($criteria);
    }
    public function getDateNew()
    {
        return date('d M,Y', strtotime($this->dateAdded));
    }
    public function articleById($id = null)
    {
        $article = new Article();
        $criteria = $article->search(1);
        $criteria->compare('t.status', Article::STATUS_PUBLISHED);
        $criteria->compare('t.article_id',  (int) $id);

        return Article::model()->find($criteria);
    }
    public function detailView($im, $w = 150, $q = 90)
    {
        $imagethuburl = Yii::app()->apps->getBaseUrl('timthumb/timthumb.php') . '?&w=' . $w . '&q=' . $q . '&src=' . Yii::app()->apps->getBaseUrl('uploads/files');
        $file_format = pathinfo($im, PATHINFO_EXTENSION);
        $file_format = strtolower($file_format);
        switch ($file_format) {
            case 'png':
                $bgn = $imagethuburl . '/' . $im;
                break;
            case 'jpeg':
                $bgn = $imagethuburl . '/' . $im;
                break;
            case 'jpg':
                $bgn = $imagethuburl . '/' . $im;
                break;
            case 'png':
                $bgn = $imagethuburl . '/' . $im;
                break;
            case 'doc':
                $bgn = $imagethuburl . '/microsoft-word.png';
                break;
            case 'docx':
                $bgn = $imagethuburl . '/microsoft-word.png';
                break;
            case 'pdf':
                $bgn = $imagethuburl . '/pdf.png';
                break;
            case 'xlx':
                $bgn = $imagethuburl . '/excel.png';
                break;
            case 'xlsx':
                $bgn = $imagethuburl . '/excel.png';
                break;
            default:
                $bgn = $imagethuburl . '/portable-document-format.png';
                break;
        }
        return $bgn;
    }
    public function getArticleMainImage()
    {
        if (!empty($this->banner)) {
            return Yii::app()->apps->getBaseUrl('uploads/files/' . $this->banner);
        } else {
            preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $this->content, $image);
            if (isset($image[1])) {
                return $image[1];
            }
        }
    }
    public function all_languages($limit = 0)
    {
        $criteria = new CDbCriteria;
        $criteria->select = 't.master_id';
        $criteria->distinct = 't.master_id';
        $criteria->condition = 'am.status="A" and am.is_trash="0" and t.article_id = :ad   ';
        $criteria->join = ' INNER JOIN {{master}} am on am.master_id = t.master_id ';
        $criteria->params[':ad'] = $this->article_id;

        $criteria->select .= ' ,am.master_name';

        $criteria->order = ' master_name asc';
        if (!empty($limit)) {
            $criteria->limit = $limit;
        }
        $data = ArticleRole::model()->findAll($criteria);
        $html = '';
        if ($data) {
            foreach ($data as $k => $v) {
                $html .= trim($v->master_name) . ', ';
            }
        }
        if (!empty($html)) {
            return rtrim($html, ', ');
        }
        return false;
    }
    public function all_teams()
    {
        $criteria = $this->search(1);
        return  $this->findAll($criteria);
    }
}
