<?php
App::uses('AppController', 'Controller');
class AuditsController extends AppController {
	public function audit_trail() {
		$this->loadModel('User');
		$users = $this->User->usersList();
		$conditions = array();
		if(!empty($this->request->query['r'])){
		$conditions['Audit.user_id'] = $this->request->query['r'];
		}
		
		if (empty($this->request->query['from'])){
			$this->request->query['from'] = date('Y-m-01');
		}

		if(!empty($this->request->query['m'])){
			$conditions['Audit.Model'] = $this->request->query['m'];
		}

        if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
            $conditions[] = array('Audit.delete_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to'].' 23:59:59'));

        } elseif (!empty($this->request->query['from'])){
            $conditions['Audit.delete_date >= '] = $this->request->query['from'];
        } elseif (!empty($this->request->query['to'])){
            $conditions['Audit.delete_date <= '] = $this->request->query['to'].' 23:59:59';
        }
				
		$this->paginate['order'] = array('Audit.delete_date' => 'desc');
		$audit_trails =$this->paginate('Audit',$conditions);

		$models = model_types();

		$this->set(compact('audit_trails','users','models'));
	}

	public function view_audit_trail($id){
		$this->loadModel('Role');
		$this->Audit->id = $id;
		$auditData = $this->Audit->read(); 
		
		if($this->Auth->user('id') == DRUPWAYID){
			//pr($auditData);
			if(!empty($auditData) && $auditData['Audit']['Model'] == 'Customer'){
				$deleted_content =  unserialize($auditData['Audit']['deleted_content']);
				$this->loadModel('Region');
				$data = $this->Region->findById($deleted_content['Customer']['region_id']);
				if(!empty($data)){
					$deleted_content['Region'] = $data['Region'];
				}
				
				$this->loadModel('Depot');
				$data = $this->Depot->findById($deleted_content['Customer']['depot_id']);
				if(!empty($data)){
					$deleted_content['Depot'] = $data['Depot'];
				}
				
				$this->loadModel('Route');
				$data = $this->Route->findById($deleted_content['Customer']['route_id']);
				if(!empty($data)){
					$deleted_content['Route'] = $data['Route'];
				}
				
				$this->loadModel('User');
				$data = $this->User->findById($deleted_content['Customer']['user_id']);
				if(!empty($data)){
					$deleted_content['User'] = $data['User'];
				}
				
				$auditData['Audit']['deleted_content'] = serialize($deleted_content);
			}
		}
		
		
		
		$roles = $this->Role->find('list', array('fields'=>array('Role.id','Role.name'))); //pr($roles);
		//pr($auditData);
		//pr(unserialize($auditData['Audit']['deleted_content']));
		$this->set(compact('auditData','roles'));
	}

	public function revert_old($id){
		$this->Audit->id = $id;
		$data =  $this->request->data = $this->Audit->read(NULL, $id); //pr($data);
		$this->loadModel($data['Audit']['Model']);
		
		//pr($this->request->data);die();
		$Model = ($data['Audit']['Model']);
		$this->request->data = unserialize($data['Audit']['deleted_content']); //pr($this->request->data);die();
		
		$this->$Model->getDataSource()->begin();
		try{
			if($this->$data['Audit']['Model']->save($this->request->data)){
				
				$this->request->data['Audit']['id']=$id;
				$this->request->data['Audit']['revert'] = 1;
				$this->request->data['Audit']['revert_by'] = $this->Auth->user('id');
				
				if(!$this->Audit->save($this->request->data)){
					 throw new Exception("Failed to update audit record.");
				}

				if($data['Audit']['Model'] == 'ConsumerOrder'){
					$order = $this->request->data;
					$this->loadModel('ConsumerSale');
					$this->ConsumerSale->saveAll($this->request->data['ConsumerSale']);
					
					$this->loadModel('ConsumerFreeItem');
					$this->ConsumerFreeItem->saveAll($this->request->data['ConsumerFreeItem']);
					
					$stockStatus = array();
											
					foreach($order['ConsumerSale'] as $sale){
						$stockStatus[$sale['brand_id']]['entity_id'] = $sale['depot_id'];
						$stockStatus[$sale['brand_id']]['entity'] = 'Depot';
						
						@$stockStatus[$sale['brand_id']][strtolower($sale['unit'])] += $sale['quantity'];
					}
					if(!empty($order['ConsumerFreeItem'])){
						foreach($order['ConsumerFreeItem'] as $freeItem){
							@$stockStatus[$freeItem['brand_id']][strtolower($freeItem['unit'])] += $freeItem['quantity'];
						}
					}
					//pr($stockStatus);
					if($stockStatus){
						$this->loadModel('Sale');
						$this->Sale->updateStockStatus($stockStatus);
					}
				}
				
				
				if(!empty($data['Audit']['sales_data'])){
					$unserializedData = unserialize($data['Audit']['sales_data']);
					
					if(isset($unserializedData['Sale'])){
						$this->loadModel('Sale');

						//remove existing sales entry 
						if(!empty($this->request->data[$Model]['id'])){
							$orderId = $this->request->data[$Model]['id'];
							$this->Sale->deleteAll(['order_id' => $orderId], false);
						}

						foreach($unserializedData['Sale'] as $sale){//pr($sale);
							$this->request->data = $sale;
						
							if(!$this->Sale->save($this->request->data)){
								throw new Exception("Failed to restore a sale record.");
							}
						}//die();
					}
					if(!empty($unserializedData['RsSale'])){
						$this->loadModel('RedistributorSaleitem');

						//remove existing rsales entry 
						if(!empty($this->request->data[$Model]['id'])){
							$orderId = $this->request->data[$Model]['id'];
							$this->RedistributorSaleitem->deleteAll(['redistributor_sale_id' => $orderId], false);
						}

						foreach($unserializedData['RsSale'] as $rsale){//pr($sale);
							$this->request->data = $rsale;
							if(!$this->RedistributorSaleitem->save($this->request->data)){
								throw new Exception("Failed to restore a R-Sales record.");
							}
						}//die();	
					}
				}
				$this->$Model->getDataSource()->commit();
				$this->Session->setFlash('This data is reverted');
				$this->redirect(array('controller' => 'audits' , 'action' => 'audit_trail'));
			}
		}catch (Exception $e) {
			// Rollback the transaction if anything fails
			$this->$Model->getDataSource()->rollback();
			$this->Session->setFlash(__('Error: ' . $e->getMessage()));
		}
	}


	public function revert($id){
		$this->Audit->id = $id;
		$data = $this->Audit->read(NULL, $id);  //pr($data); die();
		$this->loadModel($data['Audit']['Model']);
		
		//pr($this->request->data);die();
		$Model = ($data['Audit']['Model']);
		$deleted_content = $this->request->data = unserialize($data['Audit']['deleted_content']);  //pr($deleted_content); die();
		$orderId = !empty($deleted_content[$Model]['id']) ? $deleted_content[$Model]['id'] : null;

		$this->$Model->getDataSource()->begin();
		try{
			if($this->$Model->save($this->request->data)){
				
				$auditData = ['Audit' => [
                'id'        => $id,
                'revert'    => 1,
                'revert_by' => $this->Auth->user('id')
            	]];
				
				if(!$this->Audit->save($auditData)){
					 throw new Exception("Failed to update audit record.");
				}
				
				if(!empty($data['Audit']['sales_data'])){
					$unserializedData = unserialize($data['Audit']['sales_data']);
					//pr($unserializedData); die();
					if(!empty($unserializedData['Sale'])){
						$this->loadModel('Sale');

						//remove existing sales entry 
						if($orderId){
							$this->Sale->deleteAll(['order_id' => $orderId], false);
						}

						foreach($unserializedData['Sale'] as $sale){//pr($sale);
							//$this->request->data = $sale;
							if(!$this->Sale->save($sale)){
								throw new Exception("Failed to restore a sale record.");
							}
						} //die();

						if(!empty($deleted_content['FreeItem'])){
							$this->loadModel('FreeItem');
							//remove existing free entry 
							if($orderId){
								$this->FreeItem->deleteAll(['order_id' => $orderId], false);
							}

							foreach($deleted_content['FreeItem'] as $freeitem){
								if(!$this->FreeItem->save($freeitem)){
									throw new Exception("Failed to restore a sale record.");
								}
							}//die();
						}
					}
					if(!empty($unserializedData['RsSale'])){
						$this->loadModel('RedistributorSaleitem');

						//remove existing rsales entry 
						if($orderId){
							$this->RedistributorSaleitem->deleteAll(['redistributor_sale_id' => $orderId], false);
						}
						foreach($unserializedData['RsSale'] as $rsale){//pr($sale);
							if(!$this->RedistributorSaleitem->save($rsale)){
								throw new Exception("Failed to restore a R-Sales record.");
							}
						}//die();	

						if(!empty($deleted_content['RdFreeItem'])){
							$this->loadModel('RdFreeItem');
							//remove existing rfree entry 
							if($orderId){
								$this->RdFreeItem->deleteAll(['redistributor_sale_id' => $orderId], false);
							}

							foreach($deleted_content['RdFreeItem'] as $freeitem){
								if(!$this->RdFreeItem->save($freeitem)){
									throw new Exception("Failed to restore a sale record.");
								}
							}//die();
						}
					}
				}

				

				if($data['Audit']['Model'] == 'ConsumerOrder'){
					$order = $deleted_content;
					
					if(!empty($deleted_content['ConsumerSale'])){
						$this->loadModel('ConsumerSale');
						$this->ConsumerSale->saveAll($deleted_content['ConsumerSale']);
					}
					if(!empty($deleted_content['ConsumerFreeItem'])){
						$this->loadModel('ConsumerFreeItem');
						$this->ConsumerFreeItem->saveAll($deleted_content['ConsumerFreeItem']);
					}

					$stockStatus = array();
											
					foreach($order['ConsumerSale'] as $sale){
						$stockStatus[$sale['brand_id']]['entity_id'] = $sale['depot_id'];
						$stockStatus[$sale['brand_id']]['entity'] = 'Depot';
						
						@$stockStatus[$sale['brand_id']][strtolower($sale['unit'])] += $sale['quantity'];
					}
					if(!empty($order['ConsumerFreeItem'])){
						foreach($order['ConsumerFreeItem'] as $freeItem){
							@$stockStatus[$freeItem['brand_id']][strtolower($freeItem['unit'])] += $freeItem['quantity'];
						}
					}
					//pr($stockStatus);
					if($stockStatus){
						$this->loadModel('Sale');
						$this->Sale->updateStockStatus($stockStatus);
					}
				}

				$this->$Model->getDataSource()->commit();
				$this->Session->setFlash('This data is reverted');
				$this->redirect(array('controller' => 'audits' , 'action' => 'audit_trail'));
			}
		}catch (Exception $e) {
			// Rollback the transaction if anything fails
			$this->$Model->getDataSource()->rollback();
			$this->Session->setFlash(__('Error: ' . $e->getMessage()));
		}
	}
}