<?php

class SaleController extends NodeSiteController
{
    /** @var SaleRoot */
    public $saleRoot;

    public function init()
    {
        parent::init();
        $this->saleRoot = SaleRoot::model()->with('i18n')->findByPk($this->getNode()->data_id);
        $this->headerGalleryId = $this->saleRoot->header_gallery_id;
    }

    public function actionIndex()
    {
        $sort = new CSort();
        $sort->defaultOrder = array(
            'rank' => false,
        );

        $vehicles = Vehicle::model()->with('i18n')->findAll(array(
            'condition' => 'not t.hidden and t.sale_root_id = ' . $this->saleRoot->id,
            'order' => 'rank asc, t.id desc',
        ));

        $this->pageName = $this->saleRoot->i18n->page_name;
        $this->setSEOParams($this->saleRoot->i18n->title, $this->saleRoot->i18n->keywords, $this->saleRoot->i18n->description);

        $this->setContacts(explode(',', $this->saleRoot->contacts_data));

        $this->render('index', array(
            'vehicles' => $vehicles,
        ));
    }

    public function actionView($link)
    {
        /** @var $vehicle Vehicle */
        $vehicle = Vehicle::model()->with('i18n')->findByAttributes(array(
            'sale_root_id' => $this->saleRoot->id,
            'link' => $link,
        ));
        if (empty($vehicle)) throw new CHttpException(404);
        $this->pageName = $vehicle->i18n->page_name;
        $this->setSEOParams($vehicle->i18n->title, $vehicle->i18n->keywords, $vehicle->i18n->description);

        $this->setContacts(explode(',', $vehicle->contacts_data));
        $this->setContacts(explode(',', $this->saleRoot->contacts_data));


        $vehicles = Vehicle::model()->with('i18n')->findAll(array(
            'condition' => 'not t.hidden and t.sale_root_id = ' . $this->saleRoot->id,
            'order' => 'rank asc, t.id desc',
        ));

        $this->render('view', array(
            'vehicles' => $vehicles,
            'vehicle' => $vehicle,
        ));
    }
}