<?php

class ComprobanteController 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', 'ComprobantePdf'],
                'users' => ['@'],
            ],
            [
                'allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => [
                    'admin',
                    'delete',
                    'cuenta',
                    'numero',
                    'contabilizar',
                    'anular',
                    'descontabilizar',
                    'ComprobantePdf',
                ],
                'users' => ['@'],
            ],
            [
                'deny', // deny all users
                'users' => ['*'],
            ],
        ];
    }

    /**
     * Displays a particular model.
     *
     * @param int $id the ID of the model to be displayed
     */
    public function actionNumero()
    {
        /*if (isset($fec))
        {
          $fecha= $fec;
        }
        else
        {

        }*/

        //$fecha=$_REQUEST["fecha"];
        if (isset($_REQUEST['fecha'])) {
            $fecha = $_REQUEST['fecha'];
        } else {
            $fecha = date('d-m-Y');
        }
        list($dia, $mes, $anio) = explode('-', $fecha);

        //select MAX(numero) from comprobante where date_part('month', fecha_comprobante) ='06' and date_part('year', fecha_comprobante) ='2014';
        //$mes=date('m');
        //$anio=date('Y');
        $act = EjerciciosContables::model()->find('activo=1');
        $sql = "select MAX(numero) from contable.comprobante where date_part('month', fecha_comprobante) ='${mes}' and date_part('year', fecha_comprobante) ='${anio}' and clvejercicio={$act->id}";
        //var_dump($sql);
        //$sql=("select MAX(numero) from contable.comprobante where blnborrado=false");
        $connection = Yii::app()->db;
        $command = $connection->createCommand($sql);
        $row = $command->queryRow();
        $numero = $row['max'];
        if ($numero == '') {
            $numero = 1;
        } else {
            $numero = $numero + 1;
        }
        echo CJSON::encode($numero);

        return $numero;
    }

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

    public function actionContabilizar()
    {
        // var_dump($_POST["yt1"]);
        $id_comprobante = $_POST['yt1'];

        $dif = DiferenciaComprobante::model()->find('clv_comprobante='.$id_comprobante);

        $dife = (float) $dif->diferencia;
        if ($dif->diferencia == 0) {
            $model = Comprobante::model()->findByPk($id_comprobante);
            $model->status = 1;
            $model->update(['status']);

            $det_c = DetalleComprobante::model()->findAll(['condition' => 'clv_comprobante='.$id_comprobante]);
            if (isset($det_c)) {
                foreach ($det_c as $d_c) {
                    $d_c->estatus_contab = 1;
                    $d_c->update(['estatus_contab']);
                }
            }
        }
        echo CJSON::encode($dife);
    }

    public function actionDescontabilizar($id)
    {
        $model = $this->loadModel($id);
        $id_comprobante = $_GET['id'];

        //            $dif = DiferenciaComprobante::model()->find("clv_comprobante=".$id_comprobante);

        //            $dife= (float) $dif->diferencia;
        //            if($dif->diferencia==0){
        if ($model->eje->estatus != 3) {
            $model = Comprobante::model()->findByPk($id_comprobante);
            $model->status = 2;
            $model->update(['status']);

            $det_c = DetalleComprobante::model()->findAll(['condition' => 'clv_comprobante='.$id_comprobante]);
            if (isset($det_c)) {
                foreach ($det_c as $d_c) {
                    $d_c->estatus_contab = 2;
                    $d_c->update(['estatus_contab']);
                }
            }
            Yii::app()->user->setFlash('success', '<strong>Bien!</strong> comprobante reabierto con éxito.');
        } else {
            Yii::app()->user->setFlash(
                'error',
                '<strong>Disculpe,</strong> no se permite reabrir un comprobante de un año cerrado.'
            );
        }
        $this->redirect(['/contable/Comprobante/admin']);
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $ejercicio = EjerciciosContables::model()->findAll('activo=1');

        if (count($ejercicio) == 0) {
            Yii::app()->user->setFlash('error', '<strong>Disculpe</strong> Debe tener un periodo contable abierto.');
            $this->redirect(['ejerciciosContables/create']);
        } elseif ($ejercicio[0]->activo == 0) {
            Yii::app()->user->setFlash(
                'error',
                '<strong>Disculpe</strong> Debe seleccionar un periodo contable abierto para activar la carga de comprobantes.'
            );
            $this->redirect(['ejerciciosContables/seleccionaPeriodo']);
        } elseif ($ejercicio[0]->estatus == 3) {
            Yii::app()->user->setFlash(
                'error',
                '<strong>Disculpe</strong> Este periodo contable está cerrado, debe seleccionar un periodo contable abierto para activar la carga de comprobantes.'
            );
            $this->redirect(['ejerciciosContables/seleccionaPeriodo']);
        } else {
            $model = new Comprobante();
            $model->scenario = 'crea';

            if (isset($_POST['Comprobante'])) {
                $model->attributes = $_POST['Comprobante'];
                $model->id_usuario = Yii::app()->user->id;
                $model->id_automatico = 2;

                if ($model->mov_apertura) {
                    $model->id_tipo_comprobante = 2;
                }

                if ($model->save()) {
                    $_SESSION['id_m'] = $model->id;
                    $this->redirect(['/contable/DetalleComprobante/create', 'id2' => $model->id]);
                }
            }

            $this->render('create', [
                'model' => $model,
                'periodo' => EjerciciosContables::model()->find('activo=1'),
            ]);
        }
    }

    /**
     * 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)
    {
        $model = $this->loadModel($id);
        $model->scenario = 'actualiza';

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if ($model->status == 1) {
            Yii::app()->user->setFlash(
                'error',
                '<strong>Disculpe</strong> Esta comprobante ya fué contabilizado, no se puede modificar.'
            );
            $this->redirect(['comprobante/admin']);
        } elseif ($model->status == 3) {
            Yii::app()->user->setFlash(
                'error',
                '<strong>Disculpe</strong> Esta comprobante ya fué anulado, no se puede modificar.'
            );
            $this->redirect(['comprobante/admin']);
        } else {
            if (isset($_POST['Comprobante'])) {
                $model->attributes = $_POST['Comprobante'];
                $model->id_usuario = Yii::app()->user->id;
                $model->id_automatico = 2;
                if ($model->save()) {
                    $this->redirect(['/contable/DetalleComprobante/create', 'id2' => $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)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $model = Comprobante::model()->findByPk($id);
            $model->blnborrado = true;
            $model->update(['blnborrado']);
            DetalleComprobante::model()->updateAll(['blnborrado' => true], 'clv_comprobante=:id', [
                'id' => $model->id,
            ]);

            // 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.');
        }
    }

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

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        //            $ejercicio=  EjerciciosContables::model()->findAll('estatus=1');
        ////            echo "<pre>"; print_r($ejercicio); exit;
        //            if (count($ejercicio)==0){
        //              Yii::app()->user->setFlash('error', "<strong>Disculpe</strong> Debe tener un periodo contable abierto.");
        //              $this->redirect(array('ejerciciosContables/create'));
        //
        ////            }else if ($ejercicio[0]->activo==0){
        ////               Yii::app()->user->setFlash('error', "<strong>Disculpe</strong> Debe seleccionar un periodo contable abierto para activar la carga de comprobantes.");
        ////              $this->redirect(array('ejerciciosContables/seleccionaPeriodo'));
        //            }
        //            else{

        $model = new Comprobante('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Comprobante'])) {
            $model->attributes = $_GET['Comprobante'];
        }

        $this->render('admin', [
            'model' => $model,
            'periodo' => EjerciciosContables::model()->find('activo=1'),
        ]);
        //            }
    }

    /**
     * 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 = Comprobante::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'] === 'comprobante-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionAnular($id)
    {
        $model = $this->loadModel($id);
        $model->scenario = 'anular';
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Comprobante'])) {
            $model->attributes = $_POST['Comprobante'];
            $model->fecha_anulacion = date('Y-m-d H:i:s');
            $model->usuario_anulacion = Yii::app()->user->id;
            if ($model->eje->estatus != 3) {
                if ($model->save()) {
                    $model = Comprobante::model()->findByPk($id);
                    $model->blnborrado = false;
                    $model->status = 3;
                    $model->update(['blnborrado', 'status']);
                    DetalleComprobante::model()->updateAll(
                        ['blnborrado' => true, 'estatus_contab' => 3],
                        'clv_comprobante=:id',
                        ['id' => $model->id]
                    );

                    Yii::app()->user->setFlash(
                        'success',
                        "El comprobante <strong>{$model->num_comprobante}</strong> ha sido anulado exitosamente."
                    );
                    $this->redirect(['admin']);
                    //				$this->redirect(array('/contable/DetalleComprobante/create','id2'=>$model->id));
                }
            } else {
                Yii::app()->user->setFlash(
                    'error',
                    '<strong>Disculpe,</strong> no se permite anular un comprobante de un año cerrado.'
                );
                $this->redirect(['admin']);
            }
        }

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

    //                 public function actionActivar($id)
    //	{
    //
    //                        $model = Comprobante::model()->findByPk($id);
    //                        $model->blnborrado= false;
    //                        $model->status= 2;
    //                        $model->update(array('blnborrado','status'));
    //                        DetalleComprobante::model()->updateAll(array('blnborrado'=>true,'estatus_contab'=>2),'clv_comprobante=:id',array('id'=>$model->id));
    //                        Yii::app()->user->setFlash('success', "El comprobante <strong>$model->num_comprobante</strong> ha sido activado exitosamente.");
    //                        $this->redirect(array('admin'));
    //
    //
    //                }

    public function actionComprobantePdf($id_comprobante)
    {
        $this->render('fpdf_comp_contable', [
            'comprobante' => $id_comprobante,
        ]);
    }
}
