<?php

class UploadVendorSpreadsheetController extends Controller
{
	public $layout = 'dashboard';
	public $activeSideNav = array('manage_vendor_spreadsheet');
	public $pageTitle = 'Upload Vendor Spreadsheets';

	public function actionIndex() {
		$vendorFile = new VendorFile;
		if (Yii::app()->request->isAjaxRequest && $_SERVER['REQUEST_METHOD'] == 'POST') {
			$transaction = Yii::app()->db->beginTransaction();
			
			try {
				$postVendorId = isset($_POST['VendorFile']['vendor_id']) ? $_POST['VendorFile']['vendor_id']: '';
				$postVendorFileId = isset($_POST['file'][0]) ? $_POST['file'][0]: '';
				
				if ($postVendorId == '' || $postVendorFileId == '') {
					throw new Exception('Spreadsheet <strong>vendor</strong> cannot be blank. <br> Spreadsheet attach <strong>file</strong> cannot be blank.');			
				}

				$vendorFile->vendor_id = $postVendorId;
				$vendorFile->fileupload_id = $postVendorFileId;

				if ($vendorFile->save()){
					$vendorFile->total_product = $vendorFile->countSpreadSheetData();

					//$vendorFileParsing = VendorFile::getParsingFile();

					/*if (!$vendorFileParsing) {
						$vendorFile->status = VendorFile::STATUS_PARSING;
					}*/
					$vendorFile->status = VendorFile::STATUS_PENDING;

					$vendorFile->save(false);

					$transaction->commit();

					die(CJSON::encode(array(
						'status' => 'ok',
						'message' => 'Vendor spreadsheet successfully uploaded.'
					)));
				} else {
					throw new Exception('Vendor spreadsheet is not yet uploaded. Please wait for the spreadsheet to be uploaded.');
				}
			} catch (Exception $e) {
				$transaction->rollback();
				die(CJSON::encode(array(
					'status' => 'error',
					'message' => $e->getMessage()
				)));
			}

			throw CHttpExcetion(403, 'Your request is invalid.');
		}

		// get vendor files details
		$vendorFileData = $vendorFile->getData();
		$vendorFileDataProvider = new CArrayDataProvider($vendorFileData, array(
			'pagination' => false
		));
		
		// get vendor files details (archive)
		$vendorFileDataArchive = $vendorFile->getDataArchive();
		$vendorFileDataArchiveProvider = new CArrayDataProvider($vendorFileDataArchive, array(
			'pagination' => false
		));
		
		//get vendors details
		$vendors = Vendor::model()->findAll();
		$vendorProvider = new CArrayDataProvider($vendors, array(
			'pagination' => false
		));
		// Dev::pvx(array_key_last($vendors));
		$this->render('index', array(
			'vendors' => $vendors,
			'vendorFile' => $vendorFile,
			'vendorFileDataProvider' => $vendorFileDataProvider,
			'vendorFileDataArchiveProvider' => $vendorFileDataArchiveProvider,
			'vendorProvider' => $vendorProvider,
		));
	}
	
	// func. type cronjob
	public function actionParser() {

		$maxSec = 60;
		$initSec = 0;
		$intervalSec = 5;

		$vendorFilePending = VendorFile::getPendingFile();
		$vendorFileParsing = VendorFile::getParsingFile();
		$activeVendorFile = $vendorFileParsing ? $vendorFileParsing : $vendorFilePending;	
		//$activeVendorFile = $vendorFilePending;	

		if ($activeVendorFile) {
			if ($activeVendorFile->status == VendorFile::STATUS_PENDING) {
				$activeVendorFile->_setStatusParsing();
			}

			try {

				// simulate second interval per minutes.
				for($ctr = $initSec; $ctr <= $maxSec; $ctr += $intervalSec) {

					$parsedSpreedSheetData = $activeVendorFile->parsedSpreedSheetData();
					//Dev::pvx($parsedSpreedSheetData);
					$dataCount = $activeVendorFile->dataCount();
					$parsedData = array_slice($parsedSpreedSheetData, $dataCount, 15);
					$normalizedSpreedSheetData = $activeVendorFile->normalizedSpreedSheetData($parsedData);

					sleep($intervalSec); // pause processing for 5 sec

				}
				
			} catch (Exception $e) {
				$report = $e->getMessage();
				$activeVendorFile->setStatusError($report);
				Dev::pvx($e->getMessage());
			}  
		}
	
		if (isset($parsedSpreedSheetData)) {
			$parsedCount = count($parsedSpreedSheetData);
		} else {
			$parsedCount = 0;
		}
		if (isset($normalizedSpreedSheetData)) {
			$normalizedCount = count($normalizedSpreedSheetData);
		} else {
			$normalizedCount = 0;
		}

		Dev::pvx('Parsing Initial ('. $parsedCount  .'), ' . 'Parsing Final (' . $normalizedCount . ')');
	}

	// func. type cronjob
	public function actionUpdateDescription() {
		$files = VendorFile::model()->findAll(array(
            'condition' => 'status != :status and updated_description = 0',
            'params' => array(
				':status' => VendorFile::STATUS_DELETED
			),
            'order' => 'id ASC',
			'limit' => 2
        ));
		//$activeVendorFile = $vendorFilePending;	

		if (!empty($files)) {

			try {
				$data[] = '';
				foreach($files as $file){
					$parsedSpreedSheetData = $file->parsedSpreedSheetData();
					foreach($parsedSpreedSheetData as $dataValue){
						$vendorNormalizeds = VendorNormalized::model()->findAll(array(
							'alias' => 'vn',
							'join' => 'join {{vendor_normalized_info}} as vni on vn.id = vni.vendor_normalized_id',
							'condition' => 'vni.mpn = :mpn AND vn.vendor_fileupload_id = :vendorfile_id',
							'params' => [
								':mpn' => trim(preg_replace('/^[ \t]*[\r\n]+/m', '', $dataValue['mpn'])),
								':vendorfile_id' => $file->id,
							]
						));

						if(!empty($vendorNormalizeds)){
							foreach($vendorNormalizeds as $vendorNormalized){
								$vendorNormalizedInfo = $vendorNormalized->vendorNormalizedInfo;
								$vendorNormalizedInfo->description = trim($dataValue['description']);
								$vendorNormalizedInfo->qb_description = trim($dataValue['description']);
								if($vendorNormalizedInfo->save()){
									$data['normalized'][] = $vendorNormalized;
									$data['info'][] = $vendorNormalizedInfo;
								}
							}
						}
					}
					
					$file->updated_description = 1;
					if($file->save()){
						Dev::pv($file);
						Dev::pv($data);
					}else{
						$file->getError();
					}
				}
			} catch (Exception $e) {
				Dev::pvx($e->getMessage());
			}  
		}else{
			Dev::pvx('empty files');
		}
	}

	public function actionReview() {
		$this->render('review');
	}

	public function actionDelete($fileId) {
		$vendorFile = VendorFile::model()->findByPk($fileId);

		if (!$vendorFile) {
			Yii::app()->user->setFlash('danger', 'Vendor file is not exists.');
			$this->redirect(['uploadVendorSpreadsheet/index']);
		}

		$vendorFile->status = VendorFile::STATUS_DELETED;

		if ($vendorFile->save(false)) {
			if ($vendorFile->resetNormalizeData()) {
				Yii::app()->user->setFlash('success', 'Vendor file and data successfully deleted.');
				$this->redirect(['uploadVendorSpreadsheet/index']);	
			} else {
				Yii::app()->user->setFlash('danger', 'Vendor file data cannot deleted.');
				$this->redirect(['uploadVendorSpreadsheet/index']);
			}
		} else {
			Yii::app()->user->setFlash('danger', 'Vendor file cannot be saved.');
			$this->redirect(['uploadVendorSpreadsheet/index']);
		}
	}

	public function actionArchive($fileId) {
		$vendorFile = VendorFile::model()->findByPk($fileId);

		if (!$vendorFile) {
			Yii::app()->user->setFlash('danger', 'Vendor file is not exists.');
			$this->redirect(['uploadVendorSpreadsheet/index']);
		}

		$vendorFile->status = VendorFile::STATUS_ARCHIVED;

		if ($vendorFile->save(false)) {
			Yii::app()->user->setFlash('success', 'Vendor file and data successfully archived.');
			$this->redirect(['uploadVendorSpreadsheet/index']);	
		} else {
			Yii::app()->user->setFlash('danger', 'Vendor file cannot be saved.');
			$this->redirect(['uploadVendorSpreadsheet/index']);
		}
	}

	public function actionTestSpreadsheet() {
		$fileupload = Fileupload::model()->findByPk(291);
		
		$spreadSheetFile = $fileupload->getAbsPath();

		$workbook = SpreadsheetParser::open($spreadSheetFile);

		$productCount = 0;

		$worksheets = $workbook->getWorksheets();

		foreach ($worksheets as $worksheet) {
			$myWorksheetIndex = $workbook->getWorksheetIndex($worksheet);
			$rows = $workbook->createRowIterator($myWorksheetIndex);

			foreach ($rows as $rowIndex => $rowValue) {
				if (count($rowValue) < 4) {
					continue;
				}

				$rowValue1 = $rowValue[0];
				$rowValue2 = $rowValue[1];
				$rowValue3 = $rowValue[2];
				$rowValue4 = $rowValue[3];
				$rowValue5 = $rowValue[4];
				$rowValue6 = $rowValue[5];
				
				if (trim($rowValue1) == '' 
				&& trim($rowValue2) == ''
				&& trim($rowValue3) == ''
				&& trim($rowValue4) == ''
				&& trim($rowValue5) != '') {
					continue;
				}

				// Camera shets
				if (trim($rowValue1) == 'Popular Item' 
				&& trim($rowValue2) == 'Model No.'
				&& trim($rowValue3) == 'Megapixel'
				&& trim($rowValue4) == 'Lens') {
					continue;
				}

				// Clearance shets
				if (trim($rowValue1) == 'Model No.' 
				&& trim($rowValue2) == 'Ordering Part No.'
				&& trim($rowValue3) == 'Description'
				&& trim($rowValue4) == 'UPC') {
					continue;
				}

				/* 
				Mount, 
				Sofware, 
				Sofware, 
				Standalone, 
				Accessories, 
				Access Control, 
				Captured Card shets*/
				if (trim($rowValue1) == 'Popular Item' 
				&& trim($rowValue2) == 'Model No.'
				&& trim($rowValue3) == 'Ordering Part No.'
				&& trim($rowValue4) == 'Description') {
					continue;
				}

				// Captured Card
				if (trim($rowValue3) == 'Ordering Part No.' 
				&& trim($rowValue4) == 'Description'
				&& trim($rowValue5) == 'SKU No.'
				&& trim($rowValue6) == '') {
					continue;
				}

				// UVS VMS Server 1
				if (trim($rowValue1) == 'Model' 
				&& trim($rowValue2) == 'Sales Part No.'
				&& trim($rowValue3) == 'Item Number'
				&& trim($rowValue4) == 'No. of Cam') {
					continue;
				}

				// UVS VMS Server 2
				if (trim($rowValue1) == 'Sales part #' 
				&& trim($rowValue2) == 'Item'
				&& trim($rowValue3) == 'Component / Size'
				&& trim($rowValue4) == 'Price') {
					continue;
				}

				// Recordings 1
				if (trim($rowValue1) == 'Model' 
				&& trim($rowValue2) == 'Sales Part No.'
				&& trim($rowValue3) == 'Item Number'
				&& trim($rowValue4) == 'No. of Cam') {
					continue;
				}

				// Recordings 2
				if (trim($rowValue1) == 'Model' 
				&& trim($rowValue2) == 'CPU/MEM'
				&& trim($rowValue3) == 'Sales Part No.'
				&& trim($rowValue4) == 'Item Number') {
					continue;
				}

				// Recordings 3
				if (trim($rowValue1) == 'Model' 
				&& trim($rowValue2) == 'Sales Part No.'
				&& trim($rowValue3) == 'Item Number'
				&& trim($rowValue4) == 'Description') {
					continue;
				}

				// Recordings 4
				if (trim($rowValue1) == 'Model' 
				&& trim($rowValue2) == 'Item Number'
				&& trim($rowValue3) == ''
				&& trim($rowValue4) == 'Description') {
					continue;
				}

				// Recordings 5
				if (trim($rowValue1) == 'Model' 
				&& trim($rowValue2) == 'Sales Part No.'
				&& trim($rowValue3) == 'Item Number'
				&& trim($rowValue4) == 'Bay') {
					continue;
				}

				// Recordings 5 (weird hidden upc)
				if (trim($rowValue1) == 'Model' 
				&& trim($rowValue2) == 'Sales Part No.'
				&& trim($rowValue3) == 'Item Number'
				&& trim($rowValue4) == 'UPC') {
					continue;
				}
				

				// Optional Acc. 1
				if (trim($rowValue1) == 'Sales part #' 
				&& trim($rowValue2) == 'Item'
				&& trim($rowValue3) == 'Component / Size'
				&& trim($rowValue4) == 'Price') {
					continue;
				}

				// Optional Acc. 2
				if (trim($rowValue1) == 'Sales Part No.' 
				&& trim($rowValue2) == 'Item Number'
				&& trim($rowValue3) == 'Product Name'
				&& trim($rowValue4) == 'VIP') {
					continue;
				}

				$productCount++;
			}
		}	

		Dev::pvx($productCount);
	}

	public function actionRepublish($id, $toggleGoogle){
		$vendorFile = VendorFile::model()->find(array(
			'condition' => 'id = :id and status = :status',
			'params' => array(
				':id' => $id,
				':status' => VendorFile::STATUS_PUSHED,
			)
		));

		if($vendorFile){
			$transaction = Yii::app()->db->beginTransaction();
			$pushedVendorNormalisedData = VendorNormalized::model()->findAll(array(
				'condition' => 'status = :status AND vendor_fileupload_id = :vendor_fileupload_id',
				'params' => array(
					':status' => VendorNormalized::STATUS_PUSHED,
					':vendor_fileupload_id' => $vendorFile->id)
			));

			$error = 0;

			if(count($pushedVendorNormalisedData > 0)){
				foreach ($pushedVendorNormalisedData as $pushedVendorNormalised) {
					$pushedVendorNormalised->status = VendorNormalized::STATUS_FOR_REVIEW;
					
					if (!$pushedVendorNormalised->save(false)) {
						$error++;
					}
				}

				if($error == 0){
					$vendorFile->status = VendorFile::STATUS_PUSHING;
					$vendorFile->google_feed_publish = $toggleGoogle;
					if ($vendorFile->save(false)) {
						$actionLog = new ActionLog;
						$actionLog->action = "Republish";
						$actionLog->description = "Republish vendor file ID: ".$vendorFile->id.", with Google Feed ".($toggleGoogle == "true" ? 'on' : 'off');
						if($actionLog->save(false)){
							$transaction->commit();
							Yii::app()->user->setFlash('success', 'Vendor file and data successfully republished.');
							$this->redirect(['reviewVendorSpreadsheet/index/'.$vendorFile->id]);
						}	else {
							$transaction->rollback();
							Yii::app()->user->setFlash('danger', 'Error on republishing vendor data.');
							$this->redirect(['uploadVendorSpreadsheet/index']);
						}
					} else {
						$transaction->rollback();
						Yii::app()->user->setFlash('danger', 'Error on republishing vendor data.');
						$this->redirect(['uploadVendorSpreadsheet/index']);
					}
				} else {
					$transaction->rollback();
					Yii::app()->user->setFlash('danger', 'Error on republishing vendor data.');
					$this->redirect(['uploadVendorSpreadsheet/index']);
				}
			} else {
				Yii::app()->user->setFlash('danger', 'Error on republishing vendor data.');
				$this->redirect(['uploadVendorSpreadsheet/index']);
			}
		}
	}
}

