<?php

class PlateListController extends Controller {

    public function filters() {
        return array(
            array(
                'application.filters.SyslogFilter'
            )
        );
    }

    /**
     *
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     *      using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * 
     * @return array access control rules
     */

    /**
     * Displays a particular model.
     * 
     * @param integer $id
     *          the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'plateList' => $this->loadModel($id, true)
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        access_denied_check('create_plate_list');

        $model = new PlateList ();

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST ['PlateList'])) {
            $model->attributes = $_POST ['PlateList'];
            $file = CUploadedFile::getInstance($model, 'image');
            if ($file != null)
                $model->image = "plate_list_$model->code" . (empty($file->extensionName) ? "" : ("." . $file->extensionName));
            if ($model->save()) {
                if ($file != null)
                    $file->saveAs($path . $model->getImagePath());
                $this->redirect(array(
                    'view',
                    'id' => $model->id
                ));
            }
        }

        $this->render('create', array(
            'model' => $model
        ));
    }

    public function actionRemoveImage($id) {
        access_denied_check('edit_plate_list');

        $model = $this->loadModel($id, true, true);

        $img = $model->getImagePath();
        if (!empty($img)) {
            if (file_exists($img))
                unlink($img);

            $model->image = null;
            $model->save();
        }
        $this->redirect(app()->createUrl('plateList/update', array(
                    'id' => $id
        )));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * 
     * @param integer $id
     *          the ID of the model to be updated
     */
    public function actionUpdate($id, $from = null) {
        access_denied_check('edit_plate_list');

        $model = $this->loadModel($id, true, true);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST ['PlateList'])) {
            $model->attributes = $_POST ['PlateList'];
            $file = CUploadedFile::getInstance($model, 'image');
            if ($file != null)
                $model->image = "plate_list_$model->code" . (empty($file->extensionName) ? "" : ("." . $file->extensionName));
            if ($model->save()) {
                if ($file != null)
                    $file->saveAs($path . $model->getImagePath());
                if (!empty($from))
                    $this->redirect($from);
                else
                    $this->redirect(array(
                        'view',
                        'id' => $model->id
                    ));
            }
        }

        $this->render('update', array(
            'model' => $model
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * 
     * @param integer $id
     *          the ID of the model to be deleted
     */
    public function actionDelete($id) {
        access_denied_check('delete_plate_list');
        // if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $model = $this->loadModel($id, true, true);

            PlateAuthorization::deleteByListCode($model->code);
            Vehicle::deleteByListCode($model->code);
            VehicleOwner::deleteByListCode($model->code);
            ValidityPeriod::deleteByListCode($model->code);

            $model->deleteAccessRules();

            $model->delete();

//      $this->redirect ( Yii::app()->createUrl('plateAuthorization'));

            echo '<script type="text/javascript">window.location.href="' . Yii::app()->createUrl('plateAuthorization') . '"; </script>';
        }
        // else
        // throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    public function actionClearList($id) {
        access_denied_check('clear_plate_list');
        // if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $model = $this->loadModel($id, true, true);

            PlateAuthorization::deleteByListCode($model->code);
            Vehicle::deleteByListCode($model->code);
            VehicleOwner::deleteByListCode($model->code);
            ValidityPeriod::deleteByListCode($model->code);

//            $this->redirect(array(
//                'plateAuthorization/index'
//            ));
            echo '<script type="text/javascript">window.location.href="' . Yii::app()->createUrl('plateAuthorization') . '"; </script>';
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET ['ajax']))
                $this->redirect(isset($_POST ['returnUrl']) ? $_POST ['returnUrl'] : array(
                            'admin'
                        ) );
        }
        // else
        // throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
//        $this->redirect(array(
//            'plateAuthorization/index'
//        ));
        echo '<script type="text/javascript">window.location.href="' . Yii::app()->createUrl('plateAuthorization') . '"; </script>';
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * 
     * @param
     *          integer the ID of the model to be loaded
     * @return PlateList
     */
    public function loadModel($id, $checkVisible = false, $checkEditable = false) {
        $model = PlateList::load($id, false);
        if ($checkVisible && !$model->visible)
            access_denied_check('view_hidden_plate_list', false, null, "User " . user()->model->username . " tried to load plate list " . $model->getListTitleComplete());
        if ($checkEditable && !$model->editable)
            access_denied_check(null, true);
        $model->createAccessRules();
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * 
     * @param
     *          CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST ['ajax']) && $_POST ['ajax'] === 'plate-list-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
