<?php

class CuentasConsolidadaController extends Controller
{
    /**
     * @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';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return [
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
            ['CrugeAccessControlFilter'],
        ];
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     *
     * @return array access control rules
     */
    public function accessRules()
    {
        return [
            [
                'allow', // allow all users to perform 'index' and 'view' actions
                'actions' => ['index', 'view'],
                'users' => ['@'],
            ],
            [
                'allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => ['create', 'update'],
                'users' => ['@'],
            ],
            [
                'allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => [
                    'admin',
                    'delete',
                    'cuenta',
                    'comprobar',
                    'autocomplete',
                    'pasartitulo',
                    'pasarmovimiento',
                    'pdf',
                    'eliminar',
                ],
                'users' => ['@'],
            ],
            [
                'deny', // deny all users
                'users' => ['*'],
            ],
        ];
    }

    /**
     * Displays a particular model.
     *
     * @param int $id the ID of the model to be displayed
     */
    public function actionComprobar()
    {
        $cuenta0 = $_REQUEST['cuenta'];
        $cuenta = explode('-', $cuenta0);
        $padre = CuentasConsolidada::model()->find('blnborrado=false and "codigo_cuenta"=:id', [
            ':id' => $cuenta[0],
        ]);
        $cuenta_padre = NivelCuentaContable::model()->findByPk($padre->id);

        if ($cuenta_padre->digitos == 1) {
            $criteria = new CDbCriteria();
            $criteria->select = 'max(nivel1) as nivel1';
            $criteria->condition = 'idpadre=0 and digitos=1';
            $nivel = NivelCuentaContable::model()->find($criteria);
            $codigo_n1 = str_pad($nivel->nivel1 + 1, 3, '0', STR_PAD_LEFT).'.';
        } else {
            $codigo_n1 = str_pad($cuenta_padre->nivel1, 3, '0', STR_PAD_LEFT).'.';
        }

        /*+++++++++++++++++++SI NIVEL PADRE ES 1 ++++++++++++++++++++++++*/
        if ($cuenta_padre->digitos == 3) {
            $criteria = new CDbCriteria();
            $criteria->select = 'nivel2';
            $criteria->condition = "nivel1={$cuenta_padre->nivel1} and digitos=5";
            $criteria->order = 'nivel2';
            $nivel = NivelCuentaContable::model()->findAll($criteria);
            $cuenta = count($nivel);
            if ($cuenta == 0) {
                $nivel = 1;
            } elseif ($cuenta >= 99) {
                $codigo_cuenta = 'Usted llegó al límite de cuentas por cargar.';
                echo $codigo_cuenta;
                exit();
            } elseif ($cuenta != $nivel[$cuenta - 1]->nivel2) {
                $i = 0;
                while ($i <= count($nivel) - 1) {
                    $j = 1;
                    while ($j <= count($nivel)) {
                        if (intval($nivel[$i]->nivel2) == $j) {
                            $j++;
                            $i++;
                        } else {
                            $nivel = $j;
                            break;
                        }
                    }
                }
            } elseif ($cuenta == $nivel[$cuenta - 1]->nivel2) {
                $nivel = $nivel[$cuenta - 1]->nivel2 + 1;
            }

            $codigo_n2 = str_pad($nivel, 2, '0', STR_PAD_LEFT).'.';
        } else {
            $codigo_n2 = str_pad($cuenta_padre->nivel2, 2, '0', STR_PAD_LEFT).'.';
        }

        /*+++++++++++++++++++ SI NIVEL PADRE ES 2 ++++++++++++++++++++++++*/
        if ($cuenta_padre->digitos == 5) {
            $criteria = new CDbCriteria();
            $criteria->select = 'nivel3';
            $criteria->condition = "nivel1={$cuenta_padre->nivel1} and nivel2={$cuenta_padre->nivel2} and digitos=7";
            $criteria->order = 'nivel3';
            $nivel = NivelCuentaContable::model()->findAll($criteria);
            $cuenta = count($nivel);
            if ($cuenta == 0) {
                $nivel = 1;
            } elseif ($cuenta >= 99) {
                $codigo_cuenta = 'Usted llegó al límite de cuentas por cargar.';
                echo $codigo_cuenta;
                exit();
            } elseif ($cuenta != $nivel[$cuenta - 1]->nivel3) {
                $i = 0;
                while ($i <= count($nivel) - 1) {
                    $j = 1;
                    while ($j <= count($nivel)) {
                        if (intval($nivel[$i]->nivel3) == $j) {
                            $j++;
                            $i++;
                        } else {
                            $nivel = $j;
                            break;
                        }
                    }
                }
            } elseif ($cuenta == $nivel[$cuenta - 1]->nivel3) {
                $nivel = $nivel[$cuenta - 1]->nivel3 + 1;
            }

            $codigo_n3 = str_pad($nivel, 2, '0', STR_PAD_LEFT).'.';
        } else {
            $codigo_n3 = str_pad($cuenta_padre->nivel3, 2, '0', STR_PAD_LEFT).'.';
        }

        /*+++++++++++++++++++ SI NIVEL PADRE ES 3 ++++++++++++++++++++++++*/
        if ($cuenta_padre->digitos == 7) {
            $criteria = new CDbCriteria();
            $criteria->select = 'nivel4';
            $criteria->condition = "idpadre={$cuenta_padre->id}";
            $criteria->order = 'nivel4';
            $nivel = NivelCuentaContable::model()->findAll($criteria);
            $cuenta = count($nivel);
            if ($cuenta == 0) {
                $nivel = 1;
            } elseif ($cuenta >= 99) {
                $codigo_cuenta = 'Usted llegó al límite de cuentas por cargar.';
                echo $codigo_cuenta;
                exit();
            } elseif ($cuenta != $nivel[$cuenta - 1]->nivel4) {
                $i = 0;
                while ($i <= count($nivel) - 1) {
                    $j = 1;
                    while ($j <= count($nivel)) {
                        if (intval($nivel[$i]->nivel4) == $j) {
                            $j++;
                            $i++;
                        } else {
                            $nivel = $j;
                            break;
                        }
                    }
                }
            } elseif ($cuenta == $nivel[$cuenta - 1]->nivel4) {
                $nivel = $nivel[$cuenta - 1]->nivel4 + 1;
            }

            $codigo_n4 = str_pad($nivel, 2, '0', STR_PAD_LEFT);
        } else {
            $codigo_n4 = str_pad($cuenta_padre->nivel4, 2, '0', STR_PAD_LEFT);
        }

        /*+++++++++++++++++++ SI NIVEL PADRE ES 4 ++++++++++++++++++++++++*/
        if ($cuenta_padre->digitos == 9) {
            $criteria = new CDbCriteria();
            $criteria->select = 'nivel5';
            $criteria->condition = "nivel1={$cuenta_padre->nivel1} and nivel2={$cuenta_padre->nivel2} and nivel3={$cuenta_padre->nivel3} and nivel4={$cuenta_padre->nivel4} and nivel5 > 0 ";
            $criteria->order = 'nivel5';
            $nivel = NivelCuentaContable::model()->findAll($criteria);
            $cuenta = count($nivel);
            if ($cuenta == 0) {
                $nivel = 1;
            } elseif ($cuenta >= 99) {
                $codigo_cuenta = 'Usted llegó al límite de cuentas por cargar.';
                echo $codigo_cuenta;
                exit();
            } elseif ($cuenta != $nivel[$cuenta - 1]->nivel5) {
                $i = 0;
                while ($i <= count($nivel) - 1) {
                    $j = 1;
                    while ($j <= count($nivel)) {
                        if (intval($nivel[$i]->nivel5) == $j) {
                            $j++;
                            $i++;
                        } else {
                            $nivel = $j;
                            break;
                        }
                    }
                }
            } elseif ($cuenta == $nivel[$cuenta - 1]->nivel5) {
                $nivel = $nivel[$cuenta - 1]->nivel5 + 1;
            }

            $codigo_n5 = '.'.str_pad($nivel, 2, '0', STR_PAD_LEFT);
        } else {
            $codigo_n5 = '.'.str_pad($cuenta_padre->nivel5, 2, '0', STR_PAD_LEFT);
        }

        /*+++++++++++++++++++ SI NIVEL PADRE ES 5 ++++++++++++++++++++++++*/
        if ($cuenta_padre->digitos == 11) {
            $nivel = NivelCuentaContable::model()->findAll([
                'select' => 'nivel6',
                'condition' => "nivel1={$cuenta_padre->nivel1} and nivel2={$cuenta_padre->nivel2} and nivel3={$cuenta_padre->nivel3} and nivel4={$cuenta_padre->nivel4} and nivel5={$cuenta_padre->nivel5} and nivel6 > 0 ",
                'order' => 'nivel6',
            ]);

            $cuenta = count($nivel);
            if ($cuenta == 0) {
                $nivel = 1;
            } elseif ($cuenta >= 99) {
                $codigo_cuenta = 'Usted llegó al límite de cuentas por cargar.';
                echo $codigo_cuenta;
                exit();
            } elseif ($cuenta != $nivel[$cuenta - 1]->nivel6) {
                $i = 0;
                $termino = false;
                while ($i <= count($nivel) - 1) {
                    $j = 1;
                    while ($j <= count($nivel)) {
                        if (intval($nivel[$i]->nivel6) == $j) {
                            $j++;
                            $i++;
                        } else {
                            $nivel = $j;
                            $termino = true;
                            break;
                        }
                    }
                    if ($termino) {
                        break;
                    }
                }
            } elseif ($cuenta == $nivel[$cuenta - 1]->nivel6) {
                $nivel = $nivel[$cuenta - 1]->nivel6 + 1;
            }

            $codigo_n6 = '.'.str_pad($nivel, 2, '0', STR_PAD_LEFT);
        } else {
            $codigo_n6 = null;
        }

        echo $codigo_n1.$codigo_n2.$codigo_n3.$codigo_n4.$codigo_n5.$codigo_n6;
    }

    public function actionAutocomplete($term)
    {
        $criteria = new CDbCriteria();
        $criteria->compare('LOWER(descripcion)', strtolower($_GET['term']), true);
        $criteria->compare('LOWER(codigo_cuenta)', strtolower($_GET['term']), true, 'OR');
        $criteria->addCondition('titulo_mov=1 and nivel>2 and blnborrado=false');
        $criteria->order = 'codigo_cuenta';
        $criteria->limit = 30;
        $data = CuentasConsolidada::model()->findAll($criteria);

        if (! empty($data)) {
            $arr = [];
            foreach ($data as $item) {
                $arr[] = [
                    'id' => $item->id,
                    'value' => $item->codigo_cuenta.'-'.$item->descripcion,
                    'label' => $item->codigo_cuenta.'-'.$item->descripcion,
                ];
            }
        } else {
            $arr = [];
            $arr[] = [
                'id' => '',
                'value' => 'No se han encontrado resultados para su búsqueda',
                'label' => 'No se han encontrado resultados para su búsqueda',
            ];
        }

        echo CJSON::encode($arr);
    }

    public function actionView($id)
    {
        $this->render('view', [
            'model' => $this->loadModel($id),
        ]);
    }

    public function actionPasartitulo($id)
    {
        $model = $this->loadModel($id);
        $sql = 'update contable.cuentas_consolidada set titulo_mov= 1 where  id ='.$model->id;
        $connection = Yii::app()->db;
        $command = $connection->createCommand($sql);

        if (($row2 = $command->queryAll())) {
            Yii::app()->user->setFlash(
                'success',
                "La cuenta <strong>{$model->codigo_cuenta}-{$model->descripcion}</strong> ahora es de tipo título."
            );
            $this->redirect(['admin']);
        }
    }

    public function actionPasarmovimiento($id)
    {
        $model = $this->loadModel($id);

        $cuentacons = CuentasConsolidada::model()->findAll('"idpadre"=:idpadre  and blnborrado=false', [
            'idpadre' => $id,
        ]);
        if (count($cuentacons) >= 1) {
            Yii::app()->user->setFlash(
                'error',
                "La cuenta <strong>{$model->codigo_cuenta}-{$model->descripcion}</strong> no puede ser de tipo movimiento, porque posee cuentas asociadas a la misma."
            );
            $this->redirect(['admin']);
        } else {
            $sql = 'update contable.cuentas_consolidada set titulo_mov= 2 where  id ='.$model->id;
            $connection = Yii::app()->db;
            $command = $connection->createCommand($sql);

            if (($row2 = $command->queryAll())) {
                Yii::app()->user->setFlash(
                    'success',
                    "La cuenta <strong>{$model->codigo_cuenta}-{$model->descripcion}</strong> ahora es de tipo movimiento."
                );
                $this->redirect(['admin']);
            }
        }
    }

    public function actionPdf()
    {
        $this->render('pdf');
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new CuentasConsolidada();
        $model->scenario = 'create';

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

        if (isset($_POST['CuentasConsolidada'])) {
            $model->attributes = $_POST['CuentasConsolidada'];

            $model->cuenta = str_replace('.', '', $model->codigo_cuenta);
            //                       echo "<pre>";print_r($_POST);exit;
            $cuenta0 = $_POST['CuentasConsolidada']['cuenta_descripcion'];
            $cuenta = explode('-', $cuenta0);
            $padre = CuentasConsolidada::model()->find('blnborrado=false and "codigo_cuenta"=:id', [
                ':id' => $cuenta[0],
            ]);
            //                        $cuenta_padre = NivelCuentaContable::model()->findByPk($padre->id);

            if ($padre) {
                $nivel = CuentasConsolidada::model()->findByPk($padre->id);
                $model->idpadre = $padre->id;
                $model->nivel = $nivel->nivel + 1;
                $model->grupo_cuenta = $nivel->grupo_cuenta;
                if ($model->titulo_mov == 0) {
                    $model->titulo_mov = 2;
                } else {
                    $model->titulo_mov = 1;
                }
                $model->naturaleza = $nivel->naturaleza;
                $model->usuario_registro = Yii::app()->user->id;

                $model->referencia = $nivel->cuenta;
                $model->digitos_padre = $nivel->digitos;
                $model->id_referencia = $nivel->idpadre;

                if ($model->nivel >= 4) {
                    $model->digitos = $model->digitos_padre + 2;
                }
            }

            if ($model->save()) {
                $this->redirect(['view', 'id' => $model->id]);
            }
        }

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

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param int $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $sudeca = CuentasConsolidada::model()->findByPk($id);

        if ($sudeca->sudeca == 'true') {
            $this->redirect(['admin']);
        } else {
            $model = $this->loadModel($id);
            $model->scenario = 'update';

            if (isset($_POST['CuentasConsolidada'])) {
                $model->attributes = $_POST['CuentasConsolidada'];

                if ($model->titulo_mov == 0) {
                    $model->titulo_mov = 2;
                } else {
                    $model->titulo_mov = 1;
                }

                if ($model->save()) {
                    $this->redirect(['view', 'id' => $model->id]);
                }
            }

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

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     *
     * @param int $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        $sudeca = CuentasConsolidada::model()->findByPk($id);
        if ($sudeca->sudeca == 'true') {
            $this->redirect(['admin']);
        } else {
            $cuentacons = CuentasConsolidada::model()->findAll('idpadre=:idpadre and blnborrado=false', [
                'idpadre' => $id,
            ]);
            $detalle = DetalleComprobante::model()->findAll('id_cuenta=:id_cuenta and blnborrado=false', [
                'id_cuenta' => $id,
            ]);
            if (count($cuentacons) >= 1 || count($detalle) >= 1) {
                //                Yii::app()->user->setFlash('error', "La Cuenta <strong>$sudeca->codigo_cuenta-$sudeca->descripcion</strong> No puede ser Eliminada, Porque Posee Cuentas Asocidas a la Misma");
                //                $this->redirect(array('admin'));
            } else {
                if (Yii::app()->request->isPostRequest) {
                    // we only allow deletion via POST request
                    $model = CuentasConsolidada::model()->findByPk($id);
                    $model->blnborrado = false;
                    $model->update(['blnborrado']);
                    // 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'] : ['admin']);
                    }
                } else {
                    throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
                }
            }
        }
    }

    public function actionEliminar($id)
    {
        $sudeca = CuentasConsolidada::model()->findByPk($id);
        if ($sudeca->sudeca == 'true') {
            $this->redirect(['admin']);
        } else {
            $cuentacons = CuentasConsolidada::model()->findAll('idpadre=:idpadre and blnborrado=false', [
                'idpadre' => $id,
            ]);
            $detalle = DetalleComprobante::model()->findAll('id_cuenta=:id_cuenta and blnborrado=false', [
                'id_cuenta' => $id,
            ]);
            $parambancos = ParamBancos::model()->findAll('clvcuenta=:id_cuenta and blnborrado=false', [
                'id_cuenta' => $id,
            ]);
            if (count($cuentacons) >= 1) {
                Yii::app()->user->setFlash(
                    'error',
                    "La cuenta <strong>{$sudeca->codigo_cuenta}-{$sudeca->descripcion}</strong> no puede ser eliminada, porque posee cuentas asocidas a la misma."
                );
                $this->redirect(['admin']);
            } elseif (count($detalle) >= 1) {
                Yii::app()->user->setFlash(
                    'error',
                    "La cuenta <strong>{$sudeca->codigo_cuenta}-{$sudeca->descripcion}</strong> no puede ser eliminada, porque está asociada a un comprobante."
                );
                $this->redirect(['admin']);
            } elseif (count($parambancos) >= 1) {
                Yii::app()->user->setFlash(
                    'error',
                    "La cuenta <strong>{$sudeca->codigo_cuenta}-{$sudeca->descripcion}</strong> no puede ser eliminada, porque está asociada a la parametrizacion contable de bancos."
                );
                $this->redirect(['admin']);
            } else {
                $model = CuentasConsolidada::model()->findByPk($id);
                $model->blnborrado = true;
                $model->update(['blnborrado']);
                Yii::app()->user->setFlash(
                    'success',
                    "La cuenta <strong>{$sudeca->codigo_cuenta}-{$sudeca->descripcion}</strong> ha sido eliminada exitosamente."
                );
                $this->redirect(['admin']);
            }
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider = new CActiveDataProvider('CuentasConsolidada');
        $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new CuentasConsolidada('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['CuentasConsolidada'])) {
            $model->attributes = $_GET['CuentasConsolidada'];
        }

        $this->render('admin', [
            'model' => $model,
        ]);
    }

    /**
     * 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 int the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = CuentasConsolidada::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }

        return $model;
    }

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