<?php

class DocumentstorageController extends Controller
{

    public function init()
    {
        parent::init();
        $this->initAjaxCsrfToken();
    }

    // this function will work to post csrf token.
    protected function initAjaxCsrfToken()
    {

        Yii::app()->clientScript->registerScript('AjaxCsrfToken', ' $.ajaxSetup({
                         data: {"' . Yii::app()->request->csrfToken . '": "' . Yii::app()->request->csrfToken . '"},
                         cache:false
                    });', CClientScript::POS_HEAD);
    }

    public function accessRules()
    {
        return array(
            array(
                'allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('login', 'error', 'logout'),
                'users' => array('*'),
            ),
            array(
                'allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('Index', 'ReportIndex', 'Create', 'GetList', 'GetListReport', 'Save', 'Delete', 'UploadDocument'),
                'expression' => '$user->isMember()',
            ),
            array(
                'deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex()
    {
        //if (isset(Yii::app()->user->havePermissionOn['master_category_type_name_view']) || Yii::app()->user->authorised_user == 1) {
        $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if (count($_GET) > 0) {
            $this->render('index');
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
        /* } else {
          throw new CHttpException(401, 'Unauthorized Access');
          } */
    }

    public function actionReportIndex()
    {
        //if (isset(Yii::app()->user->havePermissionOn['master_category_type_name_view']) || Yii::app()->user->authorised_user == 1) {
        $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if (count($_GET) > 0) {
            $this->render('report_index');
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
        /* } else {
          throw new CHttpException(401, 'Unauthorized Access');
          } */
    }

    // Uncomment the following methods and override them if needed
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if (count($_GET) > 0) {
            $model = new DocumentStorage();
            $id = (int) Yii::app()->request->getParam('id');
            if ($id > 0) {
                $model = $model->findByPk($id);
            }
            Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false, 'jquery-2.1.4.js' => false);
            $this->render('create', array('model' => $model), false, false);
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }

    public function actionGetList()
    {
        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0) {
            $model = new DocumentStorage();
            $draw = $_POST['draw'];
            $offset = $_POST['start'];
            $limit = $_POST['length'];
            $category_id = isset($_POST['category_id']) ? $_POST['category_id'] : null;
            $document_year = isset($_POST['document_year']) ? $_POST['document_year'] : null;
            $document_month = isset($_POST['document_month']) ? $_POST['document_month'] : null;
            $document_fin_year = isset($_POST['document_fin_year']) ? $_POST['document_fin_year'] : null;
            $remarks = isset($_POST['remarks']) ? $_POST['remarks'] : null;

            $columns = array(
                // datatable column index  => database column name
                0 => 't.id',
                1 => 'category.document_category_name',
                2 => 't.document_year',
                3 => 't.document_month',
                4 => 't.id',
            );
            $filterColumn = $columns[$_POST['order'][0]['column']];
            $filterOrder = $_POST['order'][0]['dir'];

            $orderBy = $filterColumn . " " . $filterOrder;
            $condition = '1=1 ';

            if ($category_id > 0) {
                $childernArray = MasDocumentCategory::getChildernList($category_id);
                $childernArray[] = $category_id;
                $condition .= " AND t.category_id IN (" . implode(",", $childernArray) . ")";
            }

            if ($document_year > 0) {
                $condition .= " AND t.document_year = {$document_year}";
            }

            if ($document_month > 0) {
                $condition .= " AND t.document_month = {$document_month}";
            }
            if (!empty($document_fin_year)) {
                $next_year = $document_fin_year + 1;
                $condition .= " AND ((document_month IN (4,5,6,7,8,9,10,11,12) AND document_year = $document_fin_year)  OR (document_month IN (1,2,3) AND document_year = $next_year)  ) ";
            }

            if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
                $searchString = $_POST['search']['value'];
                // $condition .= " AND category.document_category_name LIKE '%" . addslashes($searchString) . "%'";
                $condition .= " AND (category.document_category_name LIKE '%" . addslashes($searchString) . "%' 
                 OR remarks LIKE '%" . addslashes($searchString) . "%')";

            }
            $count = $model->with('category')->count(array('condition' => $condition));
            $model = $model->with('category')->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => $orderBy));
            $recordsTotal = $count;
            $recordsFiltered = $count;
            $data['draw'] = $draw;
            $data['recordsTotal'] = $recordsTotal;
            $data['recordsFiltered'] = $recordsFiltered;
            $rowData = array();
            $m = 1;
            foreach ($model as $row) {
                $div = '';
                //if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["master_category_type_name_edit"])) {
                $div .= '<div class="btn-wrap text-center"><button class="btn btn-primary btn-xs" onclick="loadPopupModal(\'documentstorage/create&id=' . $row['id'] . '\',\'Edit Document\',\'lg\')"><i class="fa fa-pencil"></i></button>
                        <a class="btn btn-success btn-xs"
                href="' . Yii::app()->baseUrl . '/upload/document-storage/' . CHtml::encode($row['upload_document_name']) . '"
               download
                  target="_blank"
                     title="Download Document">
                     <i class="fa fa-download"></i>
                      </a>
                    ';

                //}
                $rowData[] = array(
                    $m,
                    $row['category']['document_category_name'],
                    $row['document_year'],
                    $row->getDocumentMonthName(),
                    $row['remarks'],
                    '<div class="btn-wrap text-center">' . $div . '</div>'
                );
                $m++;
            }
            $data['data'] = $rowData;
            $data['con'] = $condition;
            echo json_encode($data);
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }

    public function actionSave()
    {
        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0) {
            $model = new DocumentStorage();
            if (isset($_POST['DocumentStorage'])) {
                $model->created_by = Yii::app()->user->id;
                $model->created_datetime = date("Y-m-d H:i:s");
                if ((int) @$_POST['DocumentStorage']['id'] > 0) {
                    $id = (int) @$_POST['DocumentStorage']['id'];
                    $model = $model->findByPk($id);
                    $model->updated_by = Yii::app()->user->id;
                    $model->updated_date_time = date("Y-m-d H:i:s");
                }
                $model->attributes = $_POST['DocumentStorage'];
                $model->remarks = $_POST['DocumentStorage']['remarks'];
                if ($model->save()) {
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['DocumentStorage'];
                    $jsonData['id'] = $model->id;
                    echo CJSON::encode($jsonData);
                } else {
                    $error = CActiveForm::validate($model, '', false);
                    if ($error != '[]')
                        echo $error;
                }
            }
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }

    public function actionUploadDocument($folder = 'upload/document-storage/')
    {
        Yii::import("ext.EAjaxUpload.qqFileUploader");

        $allowedExtensions = array(
            'pdf',
            'doc',
            'docx',
            'xls',
            'xlsx',
            'ppt',
            'pptx',
            'txt',
            'csv'
        );
        $sizeLimit = 20 * 1024 * 1024; // 20 MB

        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $uploadFolder = Yii::getPathOfAlias('webroot') . DIRECTORY_SEPARATOR . $folder;

        if (!is_dir($uploadFolder)) {
            mkdir($uploadFolder, 0777, true);
        }

        $result = $uploader->handleUpload($uploadFolder);

        // The uploaded file name is returned in $result['filename']
        // So just return it back to the frontend
        if (isset($result['success']) && $result['success'] == true) {
            // nothing to change, filename is already set by handleUpload
        }

        echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        Yii::app()->end(); // Ensure no extra output
    }
    public function actionGetListReport()
    {
        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if (count($_POST) > 0) {
            $model = new DocumentStorage();
            $draw = $_POST['draw'];
            $offset = $_POST['start'];
            $limit = $_POST['length'];
            $category_id = isset($_POST['category_id']) ? $_POST['category_id'] : null;
            $document_year = isset($_POST['document_year']) ? $_POST['document_year'] : null;
            $document_month = isset($_POST['document_month']) ? $_POST['document_month'] : null;
            $document_fin_year = isset($_POST['document_fin_year']) ? $_POST['document_fin_year'] : null;
            $remarks = isset($_POST['remarks']) ? $_POST['remarks'] : null;

            $columns = array(
                // datatable column index  => database column name
                0 => 't.id',
                1 => 'category.document_category_name',
                2 => 't.document_year',
                3 => 't.document_month',
                4 => 't.id',
            );
            $filterColumn = $columns[$_POST['order'][0]['column']];
            $filterOrder = $_POST['order'][0]['dir'];

            $orderBy = $filterColumn . " " . $filterOrder;
            $condition = '1=1 ';

            if ($category_id > 0) {
                $childernArray = MasDocumentCategory::getChildernList($category_id);
                $childernArray[] = $category_id;
                $condition .= " AND t.category_id IN (" . implode(",", $childernArray) . ")";
            }

            if ($document_year > 0) {
                $condition .= " AND t.document_year = {$document_year}";
            }

            if ($document_month > 0) {
                $condition .= " AND t.document_month = {$document_month}";
            }
            if (!empty($document_fin_year)) {
                $next_year = $document_fin_year + 1;
                $condition .= " AND ((document_month IN (4,5,6,7,8,9,10,11,12) AND document_year = $document_fin_year)  OR (document_month IN (1,2,3) AND document_year = $next_year)  ) ";
            }

            if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
                $searchString = $_POST['search']['value'];
                // $condition .= " AND category.document_category_name LIKE '%" . addslashes($searchString) . "%'";
                $condition .= " AND (category.document_category_name LIKE '%" . addslashes($searchString) . "%' 
                 OR remarks LIKE '%" . addslashes($searchString) . "%')";

            }
            $count = $model->with('category')->count(array('condition' => $condition));
            $model = $model->with('category')->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => $orderBy));
            $recordsTotal = $count;
            $recordsFiltered = $count;
            $data['draw'] = $draw;
            $data['recordsTotal'] = $recordsTotal;
            $data['recordsFiltered'] = $recordsFiltered;
            $rowData = array();
            $m = 1;
            foreach ($model as $row) {
                $div = '';
                //if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["master_category_type_name_edit"])) {
                $div .= '<a class="btn btn-success btn-xs"
                href="' . Yii::app()->baseUrl . '/upload/document-storage/' . CHtml::encode($row['upload_document_name']) . '"
               download
                  target="_blank"
                     title="Download Document">
                     <i class="fa fa-download"></i>
                      </a>
                    ';

                //}
                $rowData[] = array(
                    $m,
                    $row['category']['document_category_name'],
                    $row['document_year'],
                    $row->getDocumentMonthName(),
                    $row['remarks'],
                    '<div class="btn-wrap text-center">' . $div . '</div>'
                );
                $m++;
            }
            $data['data'] = $rowData;
            $data['con'] = $condition;
            echo json_encode($data);
        } else {
            throw new CHttpException(404, 'Page not found.');
        }
    }

}
