<?php
class IndexController extends Zend_Controller_Action
{
    private $user_data;
    /**
     * Initialization
     */
    public function init()
    {
		$this->_helper->layout->setLayout('layout');
        $this->_redirector = $this->_helper->getHelper('Redirector');
        $this->view->headScript()->appendFile('/js/jquery.validate/1.5.5/validate.min.js');

    }

    function preDispatch()
    {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_redirect('/auth/login');
        } else {
            $this->user_data = $auth->getIdentity();
            $this->view->user_id = $this->user_data->user_id;
            $this->view->user_fullname = $this->user_data->first_name." ".$this->user_data->last_name;
            $this->view->organisation_id = $this->user_data->organisation_id;
            $this->view->short_name = $this->user_data->short_name;
        }
    }

    // handles uploaded file to be sent by creating a new file in file folder and creating file and transfer records on db
    // if file is to be sent to "all vendors" then 1 file will still be created, and multiple transfer records will be
    // created in the db
    // input: uploaded form containing uploaded file and destination organisation(s)
    // output: file created on server; 1 record created in file db table, record(s) created in transfer db table;
    //         email(s) sent to destination organisation(s).
    public function indexAction()
    {
        $files = new Files();
        // get list of files to be collected by this user
        $this->view->collect_files = $files->getFilesToCollect($this->user_data->user_id,$this->user_data->organisation_id);
        $this->view->file_types = $files->getAllowedFileTypes($this->user_data->organisation_id);
        $allowed_destinations = $files->getAllowedDestinations($this->user_data->organisation_id);
        $this->view->allowed_destinations = $allowed_destinations;
        $this->view->wyndham = $this->view->organisation_id==1;
        $request = $this->getRequest();
        $params = $request->getParams();
        $files = new Files();
        if ($this->getRequest()->isPost()) {
            //die(print_r($_FILES));
            $error_count = 0;
            foreach($_FILES["upload_file"]["name"] as $index=>$filename) {
                if ($filename) {
                    $file_id = $files->addFile($params["file_type_id"],$filename);
                    $upload_path = Zend_Registry::get("file_path")."/".$file_id;
                    $source_file = $_FILES["upload_file"]["tmp_name"][$index];
                    if (rename($source_file,$upload_path)) {
                        // validate uploaded file to ensure CSV format is correct
                        $error_message = $files->validateUploadFile($upload_path,$params["file_type_id"]);
                    } else {
                        $error_message = "Error: Cannot create file ".$upload_path;
                        die($error_message);
                    }
                    if ($error_message) {
                        unlink($upload_path);
                        $files->deleteFile($file_id);
                        $this->view->message .= "<span id='error'>Error: ".$error_message."<br>File has not been sent.</span><br>";
                        $error_count++;
                    } else {
                        if ($params["send_to"]==-1) { // send to all vendors
                            foreach($allowed_destinations as $destination) {
                                if ($destination->organisation_id!=$this->user_data->organisation_id) { // don't send from database admin to database admin!
                                    $files->sendFile($this->user_data,$destination->organisation_id,$file_id);
                                }
                            }
                        } else { // send to individual vendor
                            foreach($allowed_destinations as $destination) {
                                if ($destination->organisation_id==$params["send_to"]) {
                                    $files->sendFile($this->user_data,$destination->organisation_id,$file_id);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
             if (!$error_count)  $this->view->message .= "File(s) sent successfully.<br>";
        }
        if ($this->view->collect_files) $this->view->message .= "You have file(s) waiting to be collected:<br>";
    }

    public function collectFileAction()
    {
        //error_reporting(0);
        $request = $this->getRequest();
        $file_id = $request->getParam('id', '');
        $files = new Files();
        $file = $files->getFile($file_id);
        $response = $this->_response;
        // Disable view and layout rendering
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout()->disableLayout();
        // security check to see if user is allowed to download this file (they have sent or received this file)
        if (!$files->allowedToDownload($file_id,$this->user_data->organisation_id)) {
            $response->setBody('Sorry, you do not have permission to download the requested file.');
        } else {
            $file_path = Zend_Registry::get("file_path")."/".$file_id;
            if (file_exists($file_path)) {
                set_time_limit(0);
                $bits = file_get_contents($file_path);
                if(strlen($bits) == 0) {
                    $response->setBody('Sorry, we could not find the requested download file.');
                }
                else {
                    $response->setHeader('Content-type', 'application/octet-stream', true);
                    header("Content-Disposition: attachment; filename=\"" . $file->filename . '";');
                    header('Content-Transfer-Encoding: binary');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                    header('Pragma: public');
                    $response->setBody($bits);
                    // note that if the current logged in organisation id is not the receiver, this file won't be set as collected
                    $files->setFileCollected($file_id,$this->user_data->user_id,$this->user_data->organisation_id);
                }
            } else {
                $response->setBody('Sorry, we could not find the requested download file.');
            }
        }
    }

    public function historyAction()
    {
        $files = new Files();
        // get list of files to be collected by this user
        $this->view->file_transfer_history = $files->getTransferHistory($this->user_data->organisation_id);
    }

    public function homeAction()
    {
    }

    public function helpAction()
    {
        $this->view->email_admin = Zend_Registry::get('email_admin');
    }

	/**
	 * Error page for access denial
	 */
    public function denyAction()
    {
    }

}
