<?php

class DetalleComprobanteController 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 array(
			'accessControl', // perform access control for CRUD operations
                        'postOnly + delete',
                         array('CrugeAccessControlFilter')
		);
	}
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','cuenta','cuentamov','autocomplete','anular'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
        
        public function actionCuenta($term) {
    $criteria = new CDbCriteria;                                    
    $criteria->condition = "LOWER(codigo) like LOWER(:term)";
      $criteria->params = array(':term'=> ''.$_GET['term'].'%');   
      //$criteria->limit = 1000;
      $criteria->order = 'codigo asc';
      $data = Unidad::model()->findAll($criteria);      
      $arr = array();
      foreach ($data as $item) {
		   $cuenta=$item->codigo. " ". $item->descripcion ;
          $arr[] = array(
              'id' => $item->idunidad, 
              'value' => $cuenta,
              'label' => $cuenta,
          );
      }
      echo CJSON::encode($arr);
      }
      
      public function actionCuentamov($term) {
      $criteria = new CDbCriteria;                                    
      $criteria->condition = "titulo_mov=2 AND  LOWER(codigo_cuenta) like LOWER(:term)";
      $criteria->params = array(':term'=> ''.$_GET['term'].'%');   
      //$criteria->limit = 30; 
      $criteria->order = 'codigo_cuenta asc';

      $data = CuentasConsolidada::model()->findAll($criteria);      
      $arr = array();
      foreach ($data as $item) {
		   $cuenta=$item->codigo_cuenta."-".$item->descripcion;
          $arr[] = array(
              'id' => $item->id, 
              'value' => $cuenta,
              'label' => $cuenta,
          );
      }
      echo CJSON::encode($arr);
      }

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=2 and blnborrado=false');
 $criteria->order = 'codigo_cuenta';
 $criteria->limit = 30; 
 $data = CuentasConsolidada::model()->findAll($criteria);

 if (!empty($data))
 {
  $arr = array();
  foreach ($data as $item) {
   $arr[] = array(
    'id' => $item->id,
    'value' => $item->codigo_cuenta.'-'.$item->descripcion,
    'label' => $item->codigo_cuenta.'-'.$item->descripcion,
   );
  }
 }
 else
 {
  $arr = array();
  $arr[] = array(
   '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);
}       
      
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{      
                $id2=$_GET['id2'];
                $comprobante=Comprobante::model()->find('id=:id',array(':id'=>$id2));
                 if ($comprobante->status==1){
                 Yii::app()->user->setFlash('error', "<strong>Disculpe</strong> Esta comprobante ya fué contabilizado, no se puede modificar.");
                 $this->redirect(array('comprobante/admin')); 
                 }else if ($comprobante->status==3){
                 Yii::app()->user->setFlash('error', "<strong>Disculpe</strong> Esta comprobante ya fué anulado, no se puede modificar.");
                 $this->redirect(array('comprobante/admin')); 
                
                 }else {
		$model=new DetalleComprobante;
		$model->scenario='create';

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['DetalleComprobante']))
		{
			$transaction=Yii::app()->db->beginTransaction();

			try {
			
				$model->attributes=$_POST['DetalleComprobante'];

				$model->monto_debe=ProcesoPago::formatter($model->monto_debe);
				$model->monto_haber=ProcesoPago::formatter($model->monto_haber);
	//                       echo "<pre>";print_r($model);exit;
	            $cuenta0=$_POST["DetalleComprobante"]["cuenta_descripcion"];
	            $cuenta= explode("-", $cuenta0);
	            $padre = CuentasConsolidada::model()->find('"codigo_cuenta"=:id and blnborrado=false',array(':id'=>$cuenta[0]));
	                        
	            if($padre){
	            	$model->id_cuenta=$padre->id;
	                            
		            if($model->monto_debe==''){
		                $model->monto_debe=0;
		            }
		            if($model->monto_haber==''){
		                $model->monto_haber=0;
		            }
		            if($model->clv_auxiliar==''){
		                $model->clv_auxiliar=null;
		            }
	            }
	            $model->clv_comprobante=$_GET['id2'];

				if($model->save()){

					$transaction->commit();
					$this->redirect(array('create','id2'=>$model->clv_comprobante));
				}else{

					throw new Exception("Error al guardar datos", 1);
					
				}


			} catch (Exception $e) {
				
				Yii::app()->user->setFlash('error', $e->getMessage());
				$this->redirect(array('create','id2'=>$model->clv_comprobante));
			}
		}

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

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

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
                $id2=$_GET['id2'];
                $comprobante=Comprobante::model()->find('id=:id',array(':id'=>$id2));
                 if ($comprobante->status==1){
                 Yii::app()->user->setFlash('error', "<strong>Disculpe</strong> Esta comprobante ya fué contabilizado, no se puede modificar.");
                 $this->redirect(array('comprobante/admin')); 
                
                 }else if ($comprobante->status==3){
                 Yii::app()->user->setFlash('error', "<strong>Disculpe</strong> Esta comprobante ya fué anulado, no se puede modificar.");
                 $this->redirect(array('comprobante/admin')); 
                
                 }else {
		if(isset($_POST['DetalleComprobante']))
		{
			$model->attributes=$_POST['DetalleComprobante'];
			$model->monto_debe=ProcesoPago::formatter($model->monto_debe);
			$model->monto_haber=ProcesoPago::formatter($model->monto_haber);
			
                        $cuenta0=$_POST["DetalleComprobante"]["cuenta_descripcion"];
                        $cuenta= explode("-", $cuenta0);
                        $padre = CuentasConsolidada::model()->find('"codigo_cuenta"=:id',array(':id'=>$cuenta[0]));
                        
                        if($padre){
                         $model->id_cuenta=$padre->id;
                        }
                        if($model->monto_debe==''){
                            $model->monto_debe=0;
                        }
                        if($model->monto_haber==''){
                            $model->monto_haber=0;
                        }
                           if($model->clv_auxiliar==''){
                            $model->clv_auxiliar=null;
                        }
			if($model->save()){
				Yii::app()->user->setFlash('success', "Actualizado con exito!");
				$this->redirect(array('create','id2'=>$model->clv_comprobante));
			}
		}

		$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)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = DetalleComprobante::model()->findByPk($id);
                        $model->blnborrado= true;
                        $model->update(array('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'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

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

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

		$this->render('admin',array(
			'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 integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=DetalleComprobante::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']==='detalle-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['DetalleComprobante']))
		{
			$model->attributes=$_POST['DetalleComprobante'];
                        $model->fecha_anulacion=date("Y-m-d H:i:s");
                        $model->usuario_anulacion=Yii::app()->user->id;
                        if($model->comprob->eje->estatus!=3){
			if($model->save()){
//                        $model = DetalleComprobante::model()->findByPk($id);
                        $model->blnborrado= true;
                        $model->estatus_contab= 3;
                        $model->update(array('blnborrado','status'));
//                        DetalleComprobante::model()->updateAll(array('blnborrado'=>true,'estatus_contab'=>3),'clv_comprobante=:id',array('id'=>$model->id));
                       
                        Yii::app()->user->setFlash('error', "El detalle comprobante <strong>$model->referencia</strong> ha sido anulado exitosamente.");
                        $this->redirect(array('create','id2'=>$model->clv_comprobante));
                                        }         
                        } else {
                    Yii::app()->user->setFlash('error', "<strong>Disculpe,</strong> no se permite anular un comprobante de un año cerrado.");
                    $this->redirect(array('comprobante/admin')); 
                           }
                
                }

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

}
