<?php
/**
 * IMPORTANT NOTE
 * The code of this system is closed and a private proprietary of Flex Solutions.
 * A written authorization/license from Flex Solutions is required before using or modifying this code.
 * Email: sales@flexsolution.biz, Phone: +962795342585, Website: http://www.flexsolutions.biz
 */
 
/**
 *  Document
 *
 * Yii controller to control docuemnt actions
 *
 * @version 1.0
 *
 * @author Amaney
 * @package application.controllers
 */
class DocumentController extends Controller {

    /**
     * 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', 'update', 'Download', 'UploadPhoto', 'updateDocTyps'),
		'roles' => array(User::SYSTEM_ADMIN_ROLE, User::LOGISTICS_ADMIN_ROLE),
	    ),
	    array('deny', // deny all users
		'users' => array('*'),
	    ),
	);
    }

    public function actionIndex() {
	$this->render('index');
    }

    public function actionUpdate($data) {
	$result = explode('##', $data);
	$array = json_decode($result[0]);
	$model_id = $result[1];
	$dataArray = array();
	foreach ($array as $value) {
	    if ($value != null) {
		$columns = array();
		$columns['id'] = $value->id;
		$columns['name'] = $value->name;
		$columns['date'] = ($value->date == '') ? date('Y-m-d') : $value->date;
		$columns['path'] = $value->path;
		$columns['file_type'] = $value->file_type;
		$columns['file_size'] = $value->file_size;
		$dataArray[] = $columns;
	    }
	}

	$dataProvider = new CArrayDataProvider($dataArray, array('id' => 'documents'));

	Yii::app()->controller->renderPartial('/document/_grid', array('dataProvider' => $dataProvider, 'model_id' => $model_id, 'from_view' => null));
    }

    public function actionUpdateDocTyps() {
	if (isset($_POST['docType']) && isset($_POST['tid_id'])) {
	    $selected = Tid::getSelectedDocumentType($_POST['tid_id']);
	    $docTypes = explode(',', $_POST['docType']);
	    if ($docTypes != '' && $docTypes != null) {
		foreach ($docTypes as $docType) {
		    if ($docType != '')
			$selected[] = $docType;
		}
	    }
	    echo CHtml::checkBoxList('checklist', $selected, DocumentType::getNamesForDropDown(), array('style' => 'margin: 10px 5px 10px 20px !important;'));
	}
    }

    /**
     * Get the uploaded photo from user and move it to temp folder after changing its name to the entered parameter
     *
     * @param string $image_name image name
     *
     * @return array array of filename and extension
     */
    public function actionUploadPhoto() {
	Yii::import("ext.EAjaxUpload.qqFileUploader");

	$folder = Yii::app()->basePath . '\\temp\\'; // folder for uploaded files
	$allowedExtensions = Yii::app()->params["document_allowed_extension"];
	$sizeLimit = Setting::getDocumentSizeLimit() * 1024 * 1024;
	// maximum file size in bytes	
	$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
	$result = $uploader->handleUpload($folder);
	//here we keep the file name
	$file_name = "";
	//path to temp folder where we keep the image after uploading
	$url = Yii::app()->request->baseUrl . "/protected/temp/";
	//path of uploaded image
	$path_without_extension = $folder . $result['filename'];
	//get the extension
	$file_extension = pathinfo($result['filename'], PATHINFO_EXTENSION);
	$fileSize = filesize($folder . $result['filename']);

	$output = array("file_name" => $result['filename'], "file_path" => $path_without_extension, 'type' => $file_extension, 'size' => $fileSize, 'Success' => 'true');
	echo json_encode($output);
    }

    /**
     * Download the attachment
     * @param string $id of attachment we want to download it
     */
    public function actionDownload($id, $path) {
	if ($path == "") {
	    $document = Document::model()->findByPk($id);
	    if ($document != null) {
		$path = $document->getDocumentPath();
	    }
	}
	if ($path != "" && $path != null) {
	    // Must be fresh start
	    if (headers_sent ())
		die('Headers Sent');

	    // Required for some browsers
	    if (ini_get('zlib.output_compression'))
		ini_set('zlib.output_compression', 'Off');

	    // File Exists?
	    if (file_exists($path)) {

		// Parse Info / Get Extension
		$fsize = filesize($path);
		$path_parts = pathinfo($path);
		$ext = strtolower($path_parts["extension"]);

		// Determine Content Type
		switch ($ext) {
		    case "pdf": $ctype = "application/pdf";
			break;
		    case "zip": $ctype = "application/zip";
			break;
		    case "doc": $ctype = "application/msword";
			break;
		    case "xls": $ctype = "application/vnd.ms-excel";
			break;
		    case "ppt": $ctype = "application/vnd.ms-powerpoint";
			break;
		    case "gif": $ctype = "image/gif";
			break;
		    case "png": $ctype = "image/png";
			break;
		    case "jpeg":
		    case "jpg": $ctype = "image/jpg";
			break;
		    default: $ctype = "application/force-download";
		}

		header("Pragma: public"); // required
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: private", false); // required for certain browsers
		header("Content-Type: $ctype");
		header("Content-Disposition: attachment; filename=\"" . basename($path) . "\";");
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: " . $fsize);
		ob_clean();
		flush();
		readfile($path);
	    }
	}
	//}
    }

}