<?php

class SuppliersController extends Controller
{
    public function filters()
    {
        return array('accessControl');
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'actions'=>array('index','getList','create','disable','getStates'),
                'users'=>array('@'),
            ),
            array('deny',
                'users'=>array('*'),
            ),
        );
    }

    public function actionIndex()
    {
        $this->render('index');
    }

    public function actionGetList()
    {
        $model = new Suppliers();

        $draw   = $_POST['draw'];
        $offset = $_POST['start'];
        $limit  = $_POST['length'];

        $count = $model->count();

        $rows = $model->findAll(array(
            'limit'=>$limit,
            'offset'=>$offset,
            'order'=>'supplier_name ASC'
        ));

        $data['draw'] = $draw;
        $data['recordsTotal'] = $count;
        $data['recordsFiltered'] = $count;

        $result = array();
        $m = $offset;

        foreach($rows as $row){

            $filePreview = '';

            if(!empty($row->img_upload))
            {
                $fileUrl = Yii::app()->baseUrl . '/uploads/suppliers/' . $row->img_upload;

                $filePreview = '<img src="'.$fileUrl.'" 
                style="width:60px;height:60px;object-fit:cover;border:1px solid #ddd;padding:2px;border-radius:6px;">';
            }

            $result[] = array(
                ++$m,
                $row->supplier_name,
                $row->phone_no,
                $row->email,
                $filePreview,
                array(
                    'id'=>$row->id,
                    'status'=>$row->isActive
                )
            );
        }

        $data['data'] = $result;

        echo json_encode($data);
        Yii::app()->end();
    }

    public function actionCreate()
    {
        $model = new Suppliers();
        $id = (int) Yii::app()->request->getParam('id');

        if($id > 0){
            $model = Suppliers::model()->findByPk($id);
        }

        if(isset($_POST['Suppliers']))
        {
            if((int) @$_POST['Suppliers']['id'] > 0){
                $model = Suppliers::model()->findByPk($_POST['Suppliers']['id']);
            }

            $model->attributes = $_POST['Suppliers'];

            if(isset($_FILES['img_upload']) && $_FILES['img_upload']['name'] != '')
            {
                $fileName = time() . '_' . $_FILES['img_upload']['name'];
                $uploadPath = Yii::getPathOfAlias('webroot') . '/uploads/suppliers/' . $fileName;

                if(move_uploaded_file($_FILES['img_upload']['tmp_name'], $uploadPath)){
                    $model->img_upload = $fileName;
                }
            }

            if($model->isNewRecord){
                $model->created_by = Yii::app()->user->id;
                $model->created_datetime = date('Y-m-d H:i:s');
                $model->isActive = 'Y';
            }

            $model->updated_by = Yii::app()->user->id;
            $model->updated_datetime = date('Y-m-d H:i:s');

            if($model->validate())
            {
                $model->save();

                echo CJSON::encode(array(
                    'status'=>'success'
                ));
                Yii::app()->end();
            }
            else
            {
                echo CJSON::encode(array(
                    'status'=>'fail',
                    'errors'=>$model->getErrors()
                ));
                Yii::app()->end();
            }
        }

        Yii::app()->clientScript->scriptMap = array(
            '*jquery.js' => false,
            '*jquery.min.js' => false,
            '*jquery-ui.js' => false,
            '*jquery-ui.min.js' => false
        );

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

    public function actionGetStates()
    {
        $country_id = Yii::app()->request->getParam('country_id');

        $states = States::model()->findAll(array(
            'condition'=>'country_id=:cid AND isActive="Y"',
            'params'=>array(':cid'=>$country_id),
            'order'=>'state_name ASC'
        ));

        echo CHtml::tag('option', array('value'=>''), 'Select State', true);

        foreach($states as $state){
            echo CHtml::tag(
                'option',
                array('value'=>$state->id),
                CHtml::encode($state->state_name),
                true
            );
        }

        Yii::app()->end();
    }

    public function actionDisable()
    {
        $id = Yii::app()->request->getParam('id');

        $model = Suppliers::model()->findByPk($id);

        if($model){
            $model->isActive = ($model->isActive == 'Y') ? 'N' : 'Y';
            $model->updated_by = Yii::app()->user->id;
            $model->updated_datetime = date('Y-m-d H:i:s');
            $model->save();
        }

        echo json_encode(array('status'=>'success'));
        Yii::app()->end();
    }
}