<?php
require_once 'Zend/Controller/Action.php';
require_once 'Zend/Auth.php';
require_once 'Zend/Auth/Adapter/DbTable.php';
require_once 'Zend/Acl.php';
require 'aws.phar';

use Aws\S3\S3Client;

class CartellaController extends Zend_Controller_Action {
    
    private function isAllowed($identity) {
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        $roles = preg_split('[,]', $identity->Role, NULL, PREG_SPLIT_NO_EMPTY );
        $allowed = false;
        $allowedString = '';
        foreach ($roles as $role) {
            $allowed |= $acl->isAllowed($role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName());
        }
        return $allowed;
    }
    
    private function hasRole($identity,$role) {
        $roles = preg_split('[,]', $identity->Role, NULL, PREG_SPLIT_NO_EMPTY );
        return in_array($role,$roles);
    }
    
    private function createUniqueLogID() {
    	
        // uuidv4
        $namespace = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

            // 32 bits for "time_low"
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),

            // 16 bits for "time_mid"
            mt_rand(0, 0xffff),

            // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 4
            mt_rand(0, 0x0fff) | 0x4000,

            // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            mt_rand(0, 0x3fff) | 0x8000,

            // 48 bits for "node"
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
		);
        
        $name = 'DeFazioManagement';

		// Get hexadecimal components of namespace
		$nhex = str_replace(array('-','{','}'), '', $namespace);

		// Binary Value
		$nstr = '';

		// Convert Namespace UUID to bits
		for($i = 0; $i < strlen($nhex); $i+=2) {
			$nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
		}

		// Calculate hash value
		$hash = sha1($nstr . $name);

        $uuid = sprintf('%08s-%04s-%04x-%04x-%12s',

            // 32 bits for "time_low"
            substr($hash, 0, 8),

            // 16 bits for "time_mid"
            substr($hash, 8, 4),

            // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 5
            (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000,

            // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,

            // 48 bits for "node"
            substr($hash, 20, 12)
                       
		); 
        
        return $uuid;
        
	}
    
    private function log($db,$logID,$userID,$action) {
        date_default_timezone_set('Europe/Rome');
        $logData = array('UniqueID' => $logID,
                    'UserID' => $userID,
                    'Date' => date('Y-m-d H:i:s'),
                    'Action' => $action);
        $db->insert('Log', $logData); 
    }
    
    function dateCompare($el1, $el2) { 
        $format = 'Y-m-d H:i:s';
        $timezone = new DateTimeZone('Europe/Rome');
        //if (!is_object($el1) || !is_object($el2))
        //    return true;
        $d1 = DateTime::createFromFormat($format,$el1->DateSort, $timezone);
        $d2 = DateTime::createFromFormat($format,$el2->DateSort, $timezone);
        if (!is_object($d1) || !is_object($d2))
            return false;
        return $d1->format('U') < $d2->format('U');
    }
    
    // GENERALI
    
    public function getdocumentsAction() {
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
            
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $pid = $inputData['patientID'];
        $doctorID = $inputData['doctorID'];
        $requestID = $inputData['requestID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        // array finale che viene mandato in output
        $output = array();
        
        // documenti
        try {
            
            // journal
            $selectJournals = $db->select()
                                ->from(array('j'=>'Journal'),array('j.*'))
                                ->join(array('u'=>'User'),'j.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->where('j.PatientID = ?', $pid);
            $journals = $db->fetchAll($selectJournals);
            
            foreach ($journals as $value) {
                // aggiungo il piano procedure
                $selectProcedurePlan = $db->select()
                                ->from(array('prp'=>'MedProcedurePlan'),array('prp.*'))
                                ->where('prp.ID = ?', $value->MedProcedurePlanID);
                $procedurePlanData = $db->fetchAll($selectProcedurePlan);
                $value->PlanTitle = '';
                $value->PlanContent1 = '';
                $value->PlanContent2 = '';
                $value->PlanContent3 = '';
                if (count($procedurePlanData)>0) {
                    $value->PlanTitle = (isset($procedurePlanData[0]->Title))?$procedurePlanData[0]->Title:'';
                    $value->PlanContent1 = (isset($procedurePlanData[0]->Content1))?$procedurePlanData[0]->Content1:'';
                    $value->PlanContent2 = (isset($procedurePlanData[0]->Content2))?$procedurePlanData[0]->Content2:'';
                    $value->PlanContent3 = (isset($procedurePlanData[0]->Content3))?$procedurePlanData[0]->Content3:'';
                }
                
                // aggiungo la lista di procedure
                $selectProcedures = $db->select()
                                ->from(array('pre'=>'MedProcedureElement'),array('pre.*'))
                                ->join(array('mp'=>'MedProcedure'),'mp.ID = pre.MedProcedureID',array('MedProcedureTitle' => 'mp.Name'))
                                ->where('pre.MedProcedurePlanID = ?', $value->MedProcedurePlanID);
                $procedures = $db->fetchAll($selectProcedures);
                $value->Procedures = $procedures;
                
                $value->Type = "journal";
                array_push($output,$value);
            }

            // anamnesi
            $selectCaseHistory = $db->select()
                                ->from(array('h'=>'CaseHistory'),array('h.*'))
                                ->join(array('u'=>'User'),'h.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->where('h.PatientID = ?', $pid);
            $caseHistory = $db->fetchAll($selectCaseHistory);
            if (count($caseHistory) != 0) {
                // ritorno una (o più) anamnesi
                foreach ($caseHistory as $value) {
                    // aggiungo l'elenco di righe delle domande
                    $selectCaseHistoryRows = $db->select()
                                    ->from(array('chr'=>'CaseHistoryRow'),array('chr.*'))
                                    ->join(array('chq'=>'CaseHistoryQuestion'),'chr.QuestionID = chq.ID',array('SortOrder' => 'chq.SortOrder', 'Question' => 'chq.Question', 'Dependency' => 'chq.Dependency', 'AnswerWarning' => 'chq.AnswerWarning', 'NeedYesNo' => 'chq.NeedYesNo'))
                                    ->where('chr.CaseHistoryID = ?', $value->ID)
                                    ->order(array('chq.SortOrder ASC'));
                    $caseHistoryRows = $db->fetchAll($selectCaseHistoryRows);
                    $value->Questions = $caseHistoryRows;
                    $value->Type = 'caseHistory';
                    $value->Title = 'Anamnesi';
                    
                    // in questa sezione metto anche le misure corporee
                    $selectBody = $db->select()
                                        ->from(array('b'=>'Body'),array('b.*'))
                                        ->join(array('u'=>'User'),'b.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                        ->where('b.PatientID = ?', $pid);
                    $bodyResults = $db->fetchAll($selectBody);
                    if (count($bodyResults) > 0) {
                        $body = $bodyResults[0];
                        $selectBodyMeasures = $db->select()
                                        ->from(array('bm'=>'BodyMeasure'),array('bm.*'))
                                        ->where('bm.BodyID = ?', $body->ID);
                        $bodyMeasures = $db->fetchAll($selectBodyMeasures);
                        $body->Measures = $bodyMeasures;

                        $value->Body = $body;
                    }

                    array_push($output,$value); 
                }
            }
            else {
                // creo una nuova anamnesi automaticamente e la ritorno
                date_default_timezone_set('Europe/Rome');
                $data = array( 'PatientID' => $pid,
                    'DoctorID' => $doctorID,
                    'DateSort' => date('Y-m-d H:i:s'),
                    'Enabled' => '1');

                $data['LogID'] = $this->createUniqueLogID();
                $db->insert('CaseHistory', $data);
                $lastInsertID = $db->lastInsertId();
                $this->log($db,$data['LogID'],$identity->ID,'create');
                $questionsSelect = $db->select()
                                ->from(array('chq'=>'CaseHistoryQuestion'),array('chq.*'))
                                ->where('chq.DoctorID = ?', $doctorID);
                $questions = $db->fetchAll($questionsSelect);
                foreach ($questions as $value) {
                    $data = array( 'CaseHistoryID' => $lastInsertID,
                        'QuestionID' => $value->ID,
                        'Answer' => '',
                        'Note' => '');
                    $db->insert('CaseHistoryRow', $data);
                }
                
                // e la ritorno
                $selectCaseHistory = $db->select()
                                ->from(array('h'=>'CaseHistory'),array('h.*'))
                                ->join(array('u'=>'User'),'h.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->where('h.PatientID = ?', $pid);
                $caseHistory = $db->fetchAll($selectCaseHistory);
                foreach ($caseHistory as $value) {
                    $selectCaseHistoryRows = $db->select()
                                    ->from(array('chr'=>'CaseHistoryRow'),array('chr.*'))
                                    ->join(array('chq'=>'CaseHistoryQuestion'),'chr.QuestionID = chq.ID',array('SortOrder' => 'chq.SortOrder', 'Question' => 'chq.Question', 'Dependency' => 'chq.Dependency', 'AnswerWarning' => 'chq.AnswerWarning', 'NeedYesNo' => 'chq.NeedYesNo'))
                                    ->where('chr.CaseHistoryID = ?', $lastInsertID)
                                    ->order(array('chq.SortOrder ASC'));
                    $caseHistoryRows = $db->fetchAll($selectCaseHistoryRows);
                    $value->Questions = $caseHistoryRows;
                    $value->Type = 'caseHistory';
                    $value->Title = 'Anamnesi';
                    $selectBody = $db->select()
                                        ->from(array('b'=>'Body'),array('b.*'))
                                        ->join(array('u'=>'User'),'b.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                        ->where('b.PatientID = ?', $pid);
                    $bodyResults = $db->fetchAll($selectBody);
                    if (count($bodyResults) > 0) {
                        $body = $bodyResults[0];
                        $selectBodyMeasures = $db->select()
                                        ->from(array('bm'=>'BodyMeasure'),array('bm.*'))
                                        ->where('bm.BodyID = ?', $body->ID);
                        $bodyMeasures = $db->fetchAll($selectBodyMeasures);
                        $body->Measures = $bodyMeasures;

                        $value->Body = $body;
                    }

                    array_push($output,$value); 
                }

            }
            
            // album
            // c'è un solo album per ogni paziente
            // i vari interventi sono identificati da tag diverse, da filtrare alla bisogna
            $selectAlbums = $db->select()
                                ->from(array('ia'=>'ImageArchive'),array('ia.*'))
                                //->join(array('u'=>'User'),'ia.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->where('ia.PatientID = ?', $pid);
            $albums = $db->fetchAll($selectAlbums);
            if (count($albums) != 0) {
                $album = $albums[0];
                $album->Type = "album";
                $album->Title = "Foto";
                
                // estraggo le immagini dell'album
                $selectImages = $db->select()
                                    ->from(array('i'=>'Image'),array('i.*'))
                                    ->join(array('ia'=>'ImageArchive'),'i.ImageArchiveID = ia.ID',array())
                                    ->where('i.ImageArchiveID = ?', $album->ID);
                $images = $db->fetchAll($selectImages);
                foreach ($images as $image) {
                    // estraggo tutte le tag dell'immagine
                    $selectTags = $db->select()
                                    ->from(array('te'=>'TagElement'),array('te.*'))
                                    ->where('te.TagPlanID = ?', $image->TagPlanID);
                    $tags = $db->fetchAll($selectTags);   
                    $image->Tags = $tags;
                }
                $album->Images = $images;
                
                array_push($output,$album);
            }
            else {
                // se non c'è, lo creo
                $data = array('DoctorID' => $doctorID,
                    'PatientID' => $pid,
                    'Enabled' => '1');
                $logID = $this->createUniqueLogID();
                $data['LogID'] = $logID;
                $db->insert('ImageArchive', $data);
                $imageArchiveID = $db->lastInsertId();
                $this->log($db,$data['LogID'],$identity->ID,'create');
                
                $album = (object)array();
                $album->Type = "album";
                $album->Title = "Foto";
                $album->LogID = $logID;
                $album->ID = $imageArchiveID;
                $album->PatientID = $pid;
                $album->DoctorID = $doctorID;
                
                // trovo la data di creazione
                $selectCreateLog = $db->select()
                                ->from(array('l'=>'Log'),array('l.*'))
                                //->join(array('u'=>'User'),'l.UserID = u.ID',array('Fullname' => 'u.Fullname'))
                                ->where('l.UniqueID = ?', $logID)
                                ->where('l.Action = ?','create'); 
                $createLog = $db->fetchAll($selectCreateLog);
                if (count($createLog)>0) {
                    $dateCreated = $createLog[0]->Date;
                    $data = array( 'DateSort' => $dateCreated);
                    $db->update('ImageArchive', $data,'ImageArchive.ID = '.$imageArchiveID);
                    $album->DateSort = $dateCreated;
                }
                
                // estraggo le immagini dell'album
                $album->Images = array();
                $album->Enabled = '1';
                array_push($output,$album);
            }
            
            // fatture
            $selectInvoices = $db->select()
                                ->from(array('i'=>'Invoice'),array('i.*'))
                                ->join(array('u'=>'User'),'i.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                //->join(array('a'=>'Appointment'),'i.AppointmentID = a.ID',array('ProcedureID' => 'a.ProcedureID'))
                                //->join(array('mp'=>'MedProcedure'),'mp.ID = ProcedureID',array('ProcedureName' => 'mp.Name'))
                                ->where('i.PatientID = ?', $pid);
            $invoices = $db->fetchAll($selectInvoices);

            foreach ($invoices as $value) {

                // aggiungo l'elenco di righe per la fattura corrente
                $selectInvoiceRows = $db->select()
                                ->from(array('ir'=>'InvoiceRow'),array('ir.ID','ir.Description','ir.Amount'))
                                ->where('ir.InvoiceID = ?', $value->ID);
                $invoiceRows = $db->fetchAll($selectInvoiceRows);
                $value->Rows = $invoiceRows;
                
                $value->Type = 'invoice';
                $value->Title = 'Ricevuta';
                //$value->Enabled = $value->Enabled;
                array_push($output,$value);  
            }
            
            // diary
            $selectDiary = $db->select()
                                ->from(array('d'=>'Diary'),array('d.*'))
                                ->join(array('u'=>'User'),'d.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->where('d.PatientID = ?', $pid);
            $diaries = $db->fetchAll($selectDiary);
            foreach ($diaries as $value) {
                $value->Title = $value->DiaryTitle;
                $value->Type = "diary";
                array_push($output,$value);
            }
            
            // appuntamenti
            $selectAppointments = $db->select()
                                ->from(array('a'=>'Appointment'),array('a.*'))
                                ->join(array('u'=>'User'),'a.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->join(array('p'=>'Patient'),'a.PatientID = p.ID',array('PatientFirstName' => 'p.FirstName','PatientLastName' => 'p.LastName'))
                                ->joinLeft(array('at'=>'ActivityType'),'a.ActivityTypeID = at.ID',array('ActivityName' => 'at.Name', 'ActivityColor' => 'at.CalendarColor'))
                                ->joinLeft(array('cr'=>'CancelReason'),'cr.ID = a.CancelReasonID',array('CancelReason' => 'cr.Name'))
                                ->joinLeft(array('r'=>'Room'),'a.RoomID = r.ID',array('RoomName' => 'r.Name','LocationID' => 'r.LocationID'))
                                ->joinLeft(array('l'=>'Location'),'r.LocationID = l.ID',array('LocationName' => 'l.Name'))
                                //->joinLeft(array('act'=>'ActivityType'),'a.ActivityTypeID = act.ID',array('AppointmentName' => 'act.Name'))
                                ->where('a.PatientID = ?', $pid);
            $appointments = $db->fetchAll($selectAppointments);
            foreach ($appointments as $value) {
                $value->Type = "appointment";
                
                // aggiungo il piano procedure
                $selectProcedurePlan = $db->select()
                                ->from(array('prp'=>'MedProcedurePlan'),array('prp.*'))
                                ->where('prp.ID = ?', $value->MedProcedurePlanID);
                $procedurePlanData = $db->fetchAll($selectProcedurePlan);
                $value->PlanTitle = '';
                $value->PlanContent1 = '';
                $value->PlanContent2 = '';
                $value->PlanContent3 = '';
                if (count($procedurePlanData)>0) {
                    $value->PlanTitle = (isset($procedurePlanData[0]->Title))?$procedurePlanData[0]->Title:'';
                    $value->PlanContent1 = (isset($procedurePlanData[0]->Content1))?$procedurePlanData[0]->Content1:'';
                    $value->PlanContent2 = (isset($procedurePlanData[0]->Content2))?$procedurePlanData[0]->Content2:'';
                    $value->PlanContent3 = (isset($procedurePlanData[0]->Content3))?$procedurePlanData[0]->Content3:'';
                }
                
                // aggiungo la lista di procedure
                $selectProcedures = $db->select()
                                ->from(array('pre'=>'MedProcedureElement'),array('pre.*'))
                                ->join(array('mp'=>'MedProcedure'),'mp.ID = pre.MedProcedureID',array('MedProcedureTitle' => 'mp.Name'))
                                ->where('pre.MedProcedurePlanID = ?', $value->MedProcedurePlanID);
                $procedures = $db->fetchAll($selectProcedures);
                $value->Procedures = $procedures;
                $value->Title = $value->ActivityName;
                //$value->Enabled = $value->Enabled;
                
                array_push($output,$value);
            }
            
            usort($output, array('CartellaController','dateCompare'));
            
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'data' => $output,
                'requestID' => $requestID
            );
        echo json_encode($jsonResponse);
        exit;
    }

    public function getdocuments2Action() {
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
            
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $pid = $inputData['patientID'];
        $doctorID = $inputData['doctorID'];
        $requestID = $inputData['requestID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        // array finale che viene mandato in output
        $output = array();
        
        // documenti
        try {
            
            // journal
            $selectJournals = $db->select()
                                ->from(array('j'=>'Journal'),array('j.*'))
                                ->join(array('u'=>'User'),'j.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->where('j.PatientID = ?', $pid);
            $journals = $db->fetchAll($selectJournals);
            
            foreach ($journals as $value) {
                // aggiungo il piano procedure
                $selectProcedurePlan = $db->select()
                                ->from(array('prp'=>'MedProcedurePlan'),array('prp.*'))
                                ->where('prp.ID = ?', $value->MedProcedurePlanID);
                $procedurePlanData = $db->fetchAll($selectProcedurePlan);
                $value->PlanTitle = '';
                $value->PlanContent1 = '';
                $value->PlanContent2 = '';
                $value->PlanContent3 = '';
                if (count($procedurePlanData)>0) {
                    $value->PlanTitle = (isset($procedurePlanData[0]->Title))?$procedurePlanData[0]->Title:'';
                    $value->PlanContent1 = (isset($procedurePlanData[0]->Content1))?$procedurePlanData[0]->Content1:'';
                    $value->PlanContent2 = (isset($procedurePlanData[0]->Content2))?$procedurePlanData[0]->Content2:'';
                    $value->PlanContent3 = (isset($procedurePlanData[0]->Content3))?$procedurePlanData[0]->Content3:'';
                }
                
                // aggiungo la lista di procedure
                $selectProcedures = $db->select()
                                ->from(array('pre'=>'MedProcedureElement'),array('pre.*'))
                                ->join(array('mp'=>'MedProcedure'),'mp.ID = pre.MedProcedureID',array('MedProcedureTitle' => 'mp.Name'))
                                ->where('pre.MedProcedurePlanID = ?', $value->MedProcedurePlanID);
                $procedures = $db->fetchAll($selectProcedures);
                $value->Procedures = $procedures;
                
                $value->Type = "journal";
                array_push($output,$value);
            }

            // anamnesi
            $selectCaseHistoryQuestions = $db->select()
                                ->from(array('chq'=>'CaseHistoryQuestion'),array('chq.*'))
                                ->where('chq.Enabled = ?', 1)
                                ->where('chq.DoctorID = ?', $doctorID);
            $allquestions = $db->fetchAll($selectCaseHistoryQuestions);
            $selectCaseHistory = $db->select()
                                ->from(array('h'=>'CaseHistory'),array('h.*'))
                                ->join(array('u'=>'User'),'h.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->where('h.PatientID = ?', $pid);
            $caseHistory = $db->fetchAll($selectCaseHistory);
            if (count($caseHistory) != 0) {
                // ritorno una (o più) anamnesi
                $currentCaseHistory = $caseHistory[0];
                $currentCaseHistory->Type = 'caseHistory';
                $currentCaseHistory->Title = 'Anamnesi';

                // aggiungo l'elenco di righe delle domande
                // verifico anche che ci siano tutte: se non ci sono, le aggiungo
                $selectCaseHistoryRows = $db->select()
                                ->from(array('chr'=>'CaseHistoryRow'),array('chr.*'))
                                ->join(array('chq'=>'CaseHistoryQuestion'),'chr.QuestionID = chq.ID',array('SortOrder' => 'chq.SortOrder', 'Question' => 'chq.Question', 'Dependency' => 'chq.Dependency', 'AnswerWarning' => 'chq.AnswerWarning', 'NeedYesNo' => 'chq.NeedYesNo'))
                                ->where('chr.CaseHistoryID = ?', $currentCaseHistory->ID)
                                ->where('chq.Enabled = ?', 1)
                                ->where('chq.DoctorID = ?', $doctorID)
                                ->order(array('chq.SortOrder ASC'));
                $caseHistoryRows = $db->fetchAll($selectCaseHistoryRows);
                foreach ($allquestions as $value) {
                    $found = false;
                    foreach ($caseHistoryRows as $value2) {
                        if ($value2->QuestionID == $value->ID) {
                            $found = true;
                            break;
                        }
                    }
                    if (!$found) {
                        // la creo e la ritorno
                        $data = array( 'CaseHistoryID' => $currentCaseHistory->ID,
                            'QuestionID' => $value->ID,
                            'Answer' => '',
                            'Note' => '');
                        $db->insert('CaseHistoryRow', $data);
                        array_push($caseHistoryRows,$data); 
                    }
                }
                
                $currentCaseHistory->Questions = $caseHistoryRows;
                
                // in questa sezione metto anche le misure corporee
                $selectBody = $db->select()
                                    ->from(array('b'=>'Body'),array('b.*'))
                                    ->join(array('u'=>'User'),'b.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                    ->where('b.PatientID = ?', $pid);
                $bodyResults = $db->fetchAll($selectBody);
                if (count($bodyResults) > 0) {
                    $body = $bodyResults[0];
                    $selectBodyMeasures = $db->select()
                                    ->from(array('bm'=>'BodyMeasure'),array('bm.*'))
                                    ->where('bm.BodyID = ?', $body->ID);
                    $bodyMeasures = $db->fetchAll($selectBodyMeasures);
                    $body->Measures = $bodyMeasures;

                    $currentCaseHistory->Body = $body;
                }

                array_push($output,$currentCaseHistory); 
            }
            else {
                // creo una nuova anamnesi automaticamente e la ritorno
                date_default_timezone_set('Europe/Rome');
                $data = array( 'PatientID' => $pid,
                    'DoctorID' => $doctorID,
                    'DateSort' => date('Y-m-d H:i:s'),
                    'Enabled' => '1');

                $data['LogID'] = $this->createUniqueLogID();
                $db->insert('CaseHistory', $data);
                $lastInsertID = $db->lastInsertId();
                $this->log($db,$data['LogID'],$identity->ID,'create');
                $questionsSelect = $db->select()
                                ->from(array('chq'=>'CaseHistoryQuestion'),array('chq.*'))
                                ->where('chq.Enabled = ?', 1)
                                ->where('chq.DoctorID = ?', $doctorID);
                $questions = $db->fetchAll($questionsSelect);
                foreach ($questions as $value) {
                    $data = array( 'CaseHistoryID' => $lastInsertID,
                        'QuestionID' => $value->ID,
                        'Answer' => '',
                        'Note' => '');
                    $db->insert('CaseHistoryRow', $data);
                }
                
                // e la ritorno
                $selectCaseHistory = $db->select()
                                ->from(array('h'=>'CaseHistory'),array('h.*'))
                                ->join(array('u'=>'User'),'h.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->where('h.PatientID = ?', $pid);
                $caseHistory = $db->fetchAll($selectCaseHistory);
                $value = $caseHistory[0];
                
                //foreach ($caseHistory as $value) {
                $selectCaseHistoryRows = $db->select()
                                ->from(array('chr'=>'CaseHistoryRow'),array('chr.*'))
                                ->join(array('chq'=>'CaseHistoryQuestion'),'chr.QuestionID = chq.ID',array('SortOrder' => 'chq.SortOrder', 'Question' => 'chq.Question', 'Dependency' => 'chq.Dependency', 'AnswerWarning' => 'chq.AnswerWarning', 'NeedYesNo' => 'chq.NeedYesNo'))
                                ->where('chq.Enabled = ?', 1)
                                ->where('chr.CaseHistoryID = ?', $lastInsertID)
                                ->order(array('chq.SortOrder ASC'));
                $caseHistoryRows = $db->fetchAll($selectCaseHistoryRows);
                $value->Questions = $caseHistoryRows;
                $value->Type = 'caseHistory';
                $value->Title = 'Anamnesi';
                $selectBody = $db->select()
                                    ->from(array('b'=>'Body'),array('b.*'))
                                    ->join(array('u'=>'User'),'b.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                    ->where('b.PatientID = ?', $pid);
                $bodyResults = $db->fetchAll($selectBody);
                if (count($bodyResults) > 0) {
                    $body = $bodyResults[0];
                    $selectBodyMeasures = $db->select()
                                    ->from(array('bm'=>'BodyMeasure'),array('bm.*'))
                                    ->where('bm.BodyID = ?', $body->ID);
                    $bodyMeasures = $db->fetchAll($selectBodyMeasures);
                    $body->Measures = $bodyMeasures;

                    $value->Body = $body;
                }

                array_push($output,$value); 
                //}

            }
            
            // album
            // c'è un solo album per ogni paziente
            // i vari interventi sono identificati da tag diverse, da filtrare alla bisogna
            $selectAlbums = $db->select()
                                ->from(array('ia'=>'ImageArchive'),array('ia.*'))
                                //->join(array('u'=>'User'),'ia.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->where('ia.PatientID = ?', $pid);
            $albums = $db->fetchAll($selectAlbums);
            if (count($albums) != 0) {
                $album = $albums[0];
                $album->Type = "album";
                $album->Title = "Foto";
                
                // estraggo le immagini dell'album
                $selectImages = $db->select()
                                    ->from(array('i'=>'Image'),array('i.*'))
                                    ->join(array('ia'=>'ImageArchive'),'i.ImageArchiveID = ia.ID',array())
                                    ->where('i.ImageArchiveID = ?', $album->ID);
                $images = $db->fetchAll($selectImages);
                foreach ($images as $image) {
                    // estraggo tutte le tag dell'immagine
                    $selectTags = $db->select()
                                    ->from(array('te'=>'TagElement'),array('te.*'))
                                    ->where('te.TagPlanID = ?', $image->TagPlanID);
                    $tags = $db->fetchAll($selectTags);   
                    $image->Tags = $tags;
                }
                $album->Images = $images;
                
                array_push($output,$album);
            }
            else {
                // se non c'è, lo creo
                $data = array('DoctorID' => $doctorID,
                    'PatientID' => $pid,
                    'Enabled' => '1');
                $logID = $this->createUniqueLogID();
                $data['LogID'] = $logID;
                $db->insert('ImageArchive', $data);
                $imageArchiveID = $db->lastInsertId();
                $this->log($db,$data['LogID'],$identity->ID,'create');
                
                $album = (object)array();
                $album->Type = "album";
                $album->Title = "Foto";
                $album->LogID = $logID;
                $album->ID = $imageArchiveID;
                $album->PatientID = $pid;
                $album->DoctorID = $doctorID;
                
                // trovo la data di creazione
                $selectCreateLog = $db->select()
                                ->from(array('l'=>'Log'),array('l.*'))
                                //->join(array('u'=>'User'),'l.UserID = u.ID',array('Fullname' => 'u.Fullname'))
                                ->where('l.UniqueID = ?', $logID)
                                ->where('l.Action = ?','create'); 
                $createLog = $db->fetchAll($selectCreateLog);
                if (count($createLog)>0) {
                    $dateCreated = $createLog[0]->Date;
                    $data = array( 'DateSort' => $dateCreated);
                    $db->update('ImageArchive', $data,'ImageArchive.ID = '.$imageArchiveID);
                    $album->DateSort = $dateCreated;
                }
                
                // estraggo le immagini dell'album
                $album->Images = array();
                $album->Enabled = '1';
                array_push($output,$album);
            }
            
            // fatture
            $selectInvoices = $db->select()
                                ->from(array('i'=>'Invoice'),array('i.*'))
                                ->join(array('u'=>'User'),'i.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                //->join(array('a'=>'Appointment'),'i.AppointmentID = a.ID',array('ProcedureID' => 'a.ProcedureID'))
                                //->join(array('mp'=>'MedProcedure'),'mp.ID = ProcedureID',array('ProcedureName' => 'mp.Name'))
                                ->where('i.PatientID = ?', $pid);
            $invoices = $db->fetchAll($selectInvoices);

            foreach ($invoices as $value) {

                // aggiungo l'elenco di righe per la fattura corrente
                $selectInvoiceRows = $db->select()
                                ->from(array('ir'=>'InvoiceRow'),array('ir.ID','ir.Description','ir.Amount'))
                                ->where('ir.InvoiceID = ?', $value->ID);
                $invoiceRows = $db->fetchAll($selectInvoiceRows);
                $value->Rows = $invoiceRows;
                
                $value->Type = 'invoice';
                $value->Title = 'Ricevuta';
                //$value->Enabled = $value->Enabled;
                array_push($output,$value);  
            }
            
            // diary
            $selectDiary = $db->select()
                                ->from(array('d'=>'Diary'),array('d.*'))
                                ->join(array('u'=>'User'),'d.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->where('d.PatientID = ?', $pid);
            $diaries = $db->fetchAll($selectDiary);
            foreach ($diaries as $value) {
                $value->Title = $value->DiaryTitle;
                $value->Type = "diary";
                array_push($output,$value);
            }
            
            // appuntamenti
            $selectAppointments = $db->select()
                                ->from(array('a'=>'Appointment'),array('a.*'))
                                ->join(array('u'=>'User'),'a.DoctorID = u.ID',array('DoctorFullname' => 'u.Fullname'))
                                ->join(array('p'=>'Patient'),'a.PatientID = p.ID',array('PatientFirstName' => 'p.FirstName','PatientLastName' => 'p.LastName'))
                                ->joinLeft(array('at'=>'ActivityType'),'a.ActivityTypeID = at.ID',array('ActivityName' => 'at.Name', 'ActivityColor' => 'at.CalendarColor'))
                                ->joinLeft(array('cr'=>'CancelReason'),'cr.ID = a.CancelReasonID',array('CancelReason' => 'cr.Name'))
                                ->joinLeft(array('r'=>'Room'),'a.RoomID = r.ID',array('RoomName' => 'r.Name','LocationID' => 'r.LocationID'))
                                ->joinLeft(array('l'=>'Location'),'r.LocationID = l.ID',array('LocationName' => 'l.Name'))
                                //->joinLeft(array('act'=>'ActivityType'),'a.ActivityTypeID = act.ID',array('AppointmentName' => 'act.Name'))
                                ->where('a.PatientID = ?', $pid);
            $appointments = $db->fetchAll($selectAppointments);
            foreach ($appointments as $value) {
                $value->Type = "appointment";
                
                // aggiungo il piano procedure
                $selectProcedurePlan = $db->select()
                                ->from(array('prp'=>'MedProcedurePlan'),array('prp.*'))
                                ->where('prp.ID = ?', $value->MedProcedurePlanID);
                $procedurePlanData = $db->fetchAll($selectProcedurePlan);
                $value->PlanTitle = '';
                $value->PlanContent1 = '';
                $value->PlanContent2 = '';
                $value->PlanContent3 = '';
                if (count($procedurePlanData)>0) {
                    $value->PlanTitle = (isset($procedurePlanData[0]->Title))?$procedurePlanData[0]->Title:'';
                    $value->PlanContent1 = (isset($procedurePlanData[0]->Content1))?$procedurePlanData[0]->Content1:'';
                    $value->PlanContent2 = (isset($procedurePlanData[0]->Content2))?$procedurePlanData[0]->Content2:'';
                    $value->PlanContent3 = (isset($procedurePlanData[0]->Content3))?$procedurePlanData[0]->Content3:'';
                }
                
                // aggiungo la lista di procedure
                $selectProcedures = $db->select()
                                ->from(array('pre'=>'MedProcedureElement'),array('pre.*'))
                                ->join(array('mp'=>'MedProcedure'),'mp.ID = pre.MedProcedureID',array('MedProcedureTitle' => 'mp.Name'))
                                ->where('pre.MedProcedurePlanID = ?', $value->MedProcedurePlanID);
                $procedures = $db->fetchAll($selectProcedures);
                $value->Procedures = $procedures;
                $value->Title = $value->ActivityName;
                //$value->Enabled = $value->Enabled;
                
                array_push($output,$value);
            }
            
            usort($output, array('CartellaController','dateCompare'));
            
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'data' => $output,
                'requestID' => $requestID
            );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function changevalidityAction() {
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $doctorID = $inputData['doctorID'];
        if ($doctorID == "")
             $doctorID = $identity->ID;
        $documentID = $inputData['documentID'];
        $documentType = $inputData['documentType'];
        $documentLogID = $inputData['documentLogID'];
        $valid = $inputData['valid'];
        $patientID = $inputData['patientID'];
        $reasonID = $inputData['reasonID'];
        $reasonText = $inputData['reasonText'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            
            if ($documentType == 'journal') {
                $data = array('Enabled' => $valid==='true'?'1':'0');
                $db->update('Journal', $data,'Journal.ID = '.$documentID);
            }
            
            if ($documentType === 'appointment') {
                $data = array('Enabled' => $valid==='false'?'0':'1',
                             'CancelReasonID' => $reasonID,
                             'CancelNote' => $reasonText);
                $db->update('Appointment', $data,'Appointment.ID = '.$documentID);
            }
            
            if ($documentType == 'caseHistory') {
                $data = array('Enabled' => $valid==='true'?'1':'0');
                $db->update('CaseHistory', $data,'CaseHistory.ID = '.$documentID);
            }
            
            if ($documentType == 'invoice') {
                $data = array('Enabled' => $valid==='true'?'1':'0');
                $db->update('Invoice', $data,'Invoice.ID = '.$documentID);
            }
            
            $this->log($db,$documentLogID,$identity->ID,'cancel');
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID
            );
        echo json_encode($jsonResponse);
        exit;
    }
    
    // JOURNAL
    
    public function updatejournalAction() {
        
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $journalID = $inputData['journalID'];
        $doctorID = $inputData['doctorID'];
        $patientID = $inputData['patientID'];
        $content = $inputData['content'];
        $title = urldecode($inputData['title']);
        $procedures = $inputData['procedures'];
        $medProcedurePlanID = $inputData['medProcedurePlanID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            
            // modifico i dati del piano procedura attuale
            $medProcedurePlanData = array( 'Title' => $title,
                'Content1' => urldecode($content['Content1']),
                'Content2' => urldecode($content['Content2']),
                'Content3' => urldecode($content['Content3']));
            $db->update('MedProcedurePlan', $medProcedurePlanData, 'MedProcedurePlan.ID = '.$medProcedurePlanID);
            
            // cancello tutti gli element appartenenti il piano procedura attuale
            $deleteQuery = $db->delete('MedProcedureElement', 'MedProcedurePlanID = ' . $medProcedurePlanID);

            // aggiungo le procedure del nuovo piano procedure
            foreach ($procedures as $value) {
                $procedureID = $value['MedProcedureID'];
                $newProcedureElementData = array( 
                    'MedProcedurePlanID' => $medProcedurePlanID,
                    'MedProcedureID' => $procedureID
                );
                $db->insert('MedProcedureElement', $newProcedureElementData);
            }

            // ho fatto, mi basta solo segnare la modifica nel log
            $testSelect = $db->select()
                        ->from(array('j'=>'Journal'),array('j.*'))
                        ->where('j.ID = ?', $journalID);
            $journals = $db->fetchAll($testSelect);
            $this->log($db,$journals[0]->LogID,$identity->ID,'update');
            
            header ("Content-type: application/json");
            $jsonResponse = array(
                    'response' => 'success',
                    'patientID' => $patientID
                );
            echo json_encode($jsonResponse);
            exit;
            
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    }
    
    public function getjournaltemplatesAction() {
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
            
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $doctorID = $inputData['doctorID'];
        
        try {
            $selectJournalTemplates = $db->select()
                            ->from(array('jt'=>'JournalTemplate'),array('jt.*'))
                            ->where('jt.DoctorID = ?',$doctorID)
                            ->where('jt.Enabled = 1')
                            ->order(array('jt.Name ASC'));
            $journalTemplates = $db->fetchAll($selectJournalTemplates);
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'data' => $journalTemplates,
                'doctorID' => $doctorID
            );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function createjournalAction() {
        
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $doctorID = $inputData['doctorID'];
        $appointmentID = $inputData['appointmentID'];
        $patientID = $inputData['patientID'];
        $content = $inputData['content'];
        $title = urldecode($inputData['title']);
        $enabled = $inputData['enabled'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            
            // innanzitutto creo un nuovo piano procedure e ne ottengo l'id
            $medProcedurePlanData = array( 
                'Title' => urldecode($title),
                'Type' => 'Journal',
                'Content1' => urldecode($content['Content1']),
                'Content2' => urldecode($content['Content2']),
                'Content3' => urldecode($content['Content3']));
            $db->insert('MedProcedurePlan', $medProcedurePlanData);
            $newProcedurePlanID = $db->lastInsertId();

            // infine aggiungo il journal
            date_default_timezone_set('Europe/Rome');
            $data = array( 'DoctorID' => $doctorID,
                'PatientID' => $patientID,
                'AppointmentID' => $appointmentID,
                'Title' => urldecode($title),
                'Enabled' => $enabled,
                'DateSort' => date('Y-m-d H:i:s'),
                'MedProcedurePlanID' => $newProcedurePlanID,
                'LogID' => $this->createUniqueLogID());

            $db->insert('Journal', $data);
            $returnID = $db->lastInsertId();
            $this->log($db,$data['LogID'],$identity->ID,'create');

            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID    // ritorno il patient ID per forzare il refresh dei documenti nell'app
            );
            echo json_encode($jsonResponse);
            exit;
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    }
    
    public function deletejournalAction() {
        
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $journalID = $inputData['journalID'];
        $medProcedurePlanID = $inputData['medProcedurePlanID'];
        $patientID = $inputData['patientID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    
        try {
            $db->delete('Journal', 'ID = ' . $journalID);
            // cancello anche il medProcedurePlan associato
            $db->delete('MedProcedurePlan', 'ID = ' . $medProcedurePlanID);
            $db->delete('MedProcedureElement', array(
                'MedProcedurePlanID = ?' => $medProcedurePlanID
            ));
        } 
        catch (Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID    // ritorno il patient ID per forzare il refresh dei documenti nell'app
            );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    public function createtemplateAction() {
        
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $templateName = urldecode($inputData['templateName']);
        $doctorID = $inputData['doctorID'];
        $templateID = '';
        
        try {
            $selectJournalTemplate = $db->select()
                                ->from(array('jt'=>'JournalTemplate'),array('jt.*'))
                                ->where('jt.Name = ?', $templateName);
            $journalTemplates = $db->fetchAll($selectJournalTemplate);
            if (count($journalTemplates) == 0) {
                // create
                $data = array('Name' => $templateName,
                            'DoctorID' => $doctorID);
                $db->insert('JournalTemplate', $data);
                $templateID = $db->lastInsertId();
            }
            else {
                // ritorno quello che c'è
                $templateID = $journalTemplates[0]->ID;
            }
            
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }

        header ("Content-type: application/json");
        $jsonResponse = array(
            'response' => 'success',
            'doctorID' => $doctorID,
            'templateID' => $templateID
        );
        echo json_encode($jsonResponse);
        exit;
    }
    
    // APPOINTMENTS
    
    public function updateappointmentAction() {
        
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
                    'type' => 'login',
                    'message' => '',
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
                    'type' => 'acl',
                    'message' => '',
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $pid = $inputData['pid'];
        $did = $inputData['did'];
        $startDate = $inputData['startDate'];
        $endDate = $inputData['endDate'];
        $notes = urldecode($inputData['notes']);
        $activityID = $inputData['activityID'];
        $roomID = $inputData['roomID'];
        $procedures = $inputData['procedures'];
        $aptID = $inputData['aptID'];
        $medProcedurePlanID = $inputData['medProcedurePlanID'];
        $toPay = $inputData['toPay'];
        
        if ($did == '')
            $did = $identity->ID;
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
	                'type' => 'database connection',
                    'message' => $e->getMessage(),
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }

        $returnID = '';
             
        try {

            // cancello tutti gli element appartenenti il piano procedura attuale
            $deleteQuery = $db->delete('MedProcedureElement', 'MedProcedurePlanID = ' . $medProcedurePlanID);

            // aggiungo le procedure del nuovo piano procedure
            foreach ($procedures as $value) {
                $procedureID = $value['MedProcedureID'];
                $newProcedureElementData = array( 
                    'MedProcedurePlanID' => $medProcedurePlanID,
                    'MedProcedureID' => $procedureID
                );
                $db->insert('MedProcedureElement', $newProcedureElementData);
            }

            // modifico l'appuntamento
            $data = array( 'StartDateTime' => $startDate,
                'EndDateTime' => $endDate,
                'DoctorID' => $did,
                'RoomID' => $roomID,
                'ActivityTypeID' => $activityID,
                'PatientID' => $pid,
                'HasProcedures' => count($procedures)>0,
                'AppointmentNote' => $notes,
                'PatientToPay' => $toPay);

            $db->update('Appointment', $data,'Appointment.ID = '.$aptID);

            $testSelect = $db->select()
                        ->from(array('a'=>'Appointment'),array('a.*'))
                        ->where('a.ID = ?', $aptID);
            $appointments = $db->fetchAll($testSelect);
            $this->log($db,$appointments[0]->LogID,$identity->ID,'update');
        } 
        catch (Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                    'response' => 'error',
                    'type' => 'database',
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName(),
                    'message' => $e->getMessage()
                );
            echo json_encode($jsonResponse);
            exit;
        }

        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $pid
            );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function changeappointmentstatusAction() {
        
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
                    'type' => 'login',
                    'message' => '',
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
                    'type' => 'acl',
                    'message' => '',
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $type = $inputData['type'];
        $value = $inputData['value'];
        $aptID = $inputData['aptID'];
        $patientID = $inputData['patientID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
	                'type' => 'database connection',
                    'message' => $e->getMessage(),
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        // estraggo gli appuntamenti per la settimana
        $data = array( $type => $value);
        
        try {
            $db->update('Appointment', $data,'Appointment.ID = '.$aptID);
            
            $testSelect = $db->select()
                            ->from(array('a'=>'Appointment'),array('a.*'))
                            ->where('a.ID = ?', $aptID);
            $appointments = $db->fetchAll($testSelect);
            $this->log($db,$appointments[0]->LogID,$identity->ID,'update status');
        } 
        catch (Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                    'response' => 'error',
                    'message' => $e->getMessage(),
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName(),
                    'type' => 'database'
                );
            echo json_encode($jsonResponse);
            exit;
        }

        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID
            );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function deleteappointmentAction() {
        
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
                    'type' => 'login',
                    'message' => '',
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
                    'type' => 'acl',
                    'message' => '',
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $aptID = $inputData['aptID'];
        $doctorID = $inputData['doctorID'];
        $patientID = $inputData['patientID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
	                'type' => 'database connection',
                    'message' => $e->getMessage(),
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }
    
        try {
            $condition = array(
                'ID = ' . $aptID,
                'DoctorID = ' . $doctorID
            );
            $db->delete('Appointment', $condition);
        } catch (Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                    'response' => 'error',
                    'type' => 'database',
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getActionName(),
                    'message' => $e->getMessage()
                );
            echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID
            );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    // PATIENT
    
    public function getpatientAction() {
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $pid = $inputData['patientID'];
        $requestID = $inputData['requestID'];
            
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            $selectPatient = $db->select()
                            ->from(array('p'=>'Patient'),array('p.*'))
                            ->where('p.ID = ?', $pid);
            $patients = $db->fetchAll($selectPatient);
            
            if (count($patients) == 0) {
                header ("Content-type: application/json");
                $jsonResponse = array(
                        'response' => 'error',
                        'type' => 'database',
                        'message' => 'no patient found',
                        'controller' => $this->getRequest()->getControllerName(),
                        'action' => $this->getRequest()->getActionName()
                    );
                echo json_encode($jsonResponse);
                exit;
            }
            else {
                
                header ("Content-type: application/json");
                $jsonResponse = array(
                    'response' => 'success',
                    'data' => $patients[0], // possibile problema se non trova il paziente (notice)
                    'requestID' => $requestID
                );
                echo json_encode($jsonResponse);
                exit;
            }
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    }
    
    public function previewpatientAction() {
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $pid = $inputData['patientID'];
            
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            $selectPatient = $db->select()
                            ->from(array('p'=>'Patient'),array('p.*'))
                            ->where('p.ID = ?', $pid);
            $patients = $db->fetchAll($selectPatient);
            
            if (count($patients) == 0) {
                header ("Content-type: application/json");
                $jsonResponse = array(
                        'response' => 'error',
                        'type' => 'database',
                        'message' => 'no patient found',
                        'controller' => $this->getRequest()->getControllerName(),
                        'action' => $this->getRequest()->getActionName()
                    );
                echo json_encode($jsonResponse);
                exit;
            }
            else {
                // aggiungo lo storico
                /*
                $selectPatientLogs = $db->select()
                                ->from(array('l'=>'Log'),array('l.*'))
                                ->join(array('u'=>'User'),'l.UserID = u.ID',array('Fullname' => 'u.Fullname'))
                                ->where('l.UniqueID = ?', $patients[0]->LogID);
                $patientLogs = $db->fetchAll($selectPatientLogs);
                $patients[0]->Logs = $patientLogs;
                */
                
                header ("Content-type: application/json");
                $jsonResponse = array(
                        'response' => 'success',
                        'data' => $patients[0] // possibile problema se non trova il paziente (notice)
                    );
                echo json_encode($jsonResponse);
                exit;
            }
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    }

    public function deletepatientAction() {
        
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $patientID = $inputData['patientID'];
        $doctorID = $inputData['doctorID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    
        try {
            $db->delete('Patient', 'ID = ' . $patientID);
        } catch (Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
            'response' => 'success'
        );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    public function createpatientAction() {
        
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        
        $currentPatientID = $inputData['currentPatientID'];
        $firstName = urldecode($inputData['firstName']);
        $lastName = urldecode($inputData['lastName']);
        $address = urldecode($inputData['address']);
        $zip = $inputData['zip'];
        $city = urldecode($inputData['city']);
        $cf = $inputData['cf'];
        $country = urldecode($inputData['country']);
        $birthDate = $inputData['birthDate'];
        $mail = urldecode($inputData['mail']);
        $phoneHome = $inputData['phoneHome'];
        $phoneMobile = $inputData['phoneMobile'];
        $phoneWork = $inputData['phoneWork'];
        $gender = $inputData['gender'];
        $note = urldecode($inputData['note']);
        $doctorID = $inputData['doctorID'];
        $referenceID = $inputData['referenceID'];
        $privacy = $inputData['privacy'];
        //if ($doctorID == '')
        //    $doctorID = $identity->ID;
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        // preparo i dati del paziente
        $data = array(
            'FirstName' => $firstName,
		    'LastName' => $lastName,
		    'Address' => $address,
		    'Zip' => $zip,
            'City' => $city,
            'PhoneHome' => $phoneHome,
            'PhoneMobile' => $phoneMobile,
            'PhoneWork' => $phoneWork,
            'Country' => $country,
            'Gender' => $gender,
            'Birthdate' => $birthDate,
            'Email' => $mail,
            'DoctorID' => $doctorID,
            'CF' => $cf,
            'Note' => $note,
            'ReferenceID' => $referenceID,
            'Privacy' => $privacy);
        
        try {
            $testSelect = $db->select()
                            ->from(array('p'=>'Patient'),array('p.*'))
                            ->where('p.ID = ?', $currentPatientID);
            $patients = $db->fetchAll($testSelect);

            if (count($patients) == 0) {
                
                $data['LogID'] = $this->createUniqueLogID();
                $db->insert('Patient', $data);
                $lastInsertID = $db->lastInsertId();
                $this->log($db,$data['LogID'],$identity->ID,'create');
                
                header ("Content-type: application/json");
                $jsonResponse = array(
                        'response' => 'success',
                        'patientID' => $lastInsertID,
                        'patientLastName' => $lastName
                    );
                echo json_encode($jsonResponse);
                exit;

            }
            else {

                $db->update('Patient', $data,'Patient.ID = '.$currentPatientID);
                $this->log($db,$patients[0]->LogID,$identity->ID,'update');
                
                header ("Content-type: application/json");
                $jsonResponse = array(
                        'response' => 'success',
                        'patientID' => $currentPatientID,
                        'patientLastName' => $lastName
                    );
                echo json_encode($jsonResponse);
                exit;
            }
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    }
    
    public function getreferencesAction() {
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
            
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $doctorID = $inputData['doctorID'];
        
        try {
            $selectReferences = $db->select()
                            ->from(array('r'=>'Reference'),array('r.*'))
                            ->where('r.DoctorID = ?',$doctorID)
                            ->where('r.Enabled = 1')
                            ->order(array('r.Description ASC'));
            $references = $db->fetchAll($selectReferences);
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'data' => $references,
                'doctorID' => $doctorID
            );
        echo json_encode($jsonResponse);
        exit;
    }
    // DIARY
    
    public function updatediaryAction() {
        
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $diaryID = $inputData['diaryID'];
        $doctorID = $inputData['doctorID'];
        $patientID = $inputData['patientID'];
        $content = urldecode($inputData['content']);
        $title = urldecode($inputData['title']);
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            // modifico il diario
            $data = array( 'DoctorID' => $doctorID,
                'PatientID' => $patientID,
                'Content' => $content,
                'DiaryTitle' => $title);

            $db->update('Diary', $data,'Diary.ID = ' . $diaryID);

            $testSelect = $db->select()
                        ->from(array('d'=>'Diary'),array('d.*'))
                        ->where('d.ID = ?', $diaryID);
            $diaries = $db->fetchAll($testSelect);
            $this->log($db,$diaries[0]->LogID,$identity->ID,'update');
            
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID
            );
            echo json_encode($jsonResponse);
            exit;
            
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    }
    
    public function creatediaryAction() {
        
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $doctorID = $inputData['doctorID'];
        $patientID = $inputData['patientID'];
        $content = urldecode($inputData['content']);
        $title = urldecode($inputData['title']);
        $enabled = $inputData['enabled'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            
            date_default_timezone_set('Europe/Rome');
            $data = array( 'DoctorID' => $doctorID,
                'PatientID' => $patientID,
                'DiaryTitle' => $title,
                'Content' => $content,
                'Enabled' => $enabled,
                'DateSort' => date('Y-m-d H:i:s'),
                'LogID' => $this->createUniqueLogID());

            $db->insert('Diary', $data);
            $returnID = $db->lastInsertId();
            $this->log($db,$data['LogID'],$identity->ID,'create');

            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID    // ritorno il patient ID per forzare il refresh dei documenti nell'app
            );
            echo json_encode($jsonResponse);
            exit;
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    }
    
    public function deletediaryAction() {
        
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $diaryID = $inputData['diaryID'];
        $patientID = $inputData['patientID'];
        $doctorID = $inputData['doctorID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    
        try {
            $db->delete('Diary', 'ID = ' . $diaryID);
        } catch (Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID    // ritorno il patient ID per forzare il refresh dei documenti nell'app
            );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    // CASE HISTORY
    
    public function createcasehistoryAction() {
     
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        
        $patientID = $inputData['patientID'];
        $doctorID = $inputData['doctorID'];
        if ($doctorID == '')
            $doctorID = $identity->ID;
        $enabled = $inputData['enabled'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            date_default_timezone_set('Europe/Rome');
            $data = array( 'PatientID' => $patientID,
                'DoctorID' => $doctorID,
                'DateSort' => date('Y-m-d H:i:s'),
                'Enabled' => $enabled);
            
            $data['LogID'] = $this->createUniqueLogID();
            $db->insert('CaseHistory', $data);
            $lastInsertID = $db->lastInsertId();
            $this->log($db,$data['LogID'],$identity->ID,'create');
            
            $questionsSelect = $db->select()
                            ->from(array('chq'=>'CaseHistoryQuestion'),array('chq.*'))
                            ->where('chq.DoctorID = ?', $doctorID);
            $questions = $db->fetchAll($questionsSelect);

            foreach ($questions as $value) {
                $data = array( 'CaseHistoryID' => $lastInsertID,
                    'QuestionID' => $value->ID,
                    'Answer' => '',
                    'Note' => '');
                $db->insert('CaseHistoryRow', $data);
            }
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }

        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID
            );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    public function updatecasehistoryAction() {
     
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        
        $patientID = $inputData['patientID'];
        $caseHistoryID = $inputData['caseHistoryID'];
        $caseHistoryRows = $inputData['caseHistoryRows'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            foreach($caseHistoryRows as $caseHistoryRow) {
                $data = array('CaseHistoryID' => $caseHistoryID,
                              'QuestionID' => $caseHistoryRow['QuestionID'],
                              'Answer' => $caseHistoryRow['Answer'],
                              'Note' => urldecode($caseHistoryRow['Note'])
                );
                $db->update('CaseHistoryRow', $data,'CaseHistoryRow.ID = '.$caseHistoryRow['ID']); 
            }
            
            $testSelect = $db->select()
                            ->from(array('ch'=>'CaseHistory'),array('ch.*'))
                            ->where('ch.ID = ?', $caseHistoryID);
            $caseHistory = $db->fetchAll($testSelect);
            $this->log($db,$caseHistory[0]->LogID,$identity->ID,'update');
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }

        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID
            );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    public function deletecasehistoryAction() {
        
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $patientID = $inputData['patientID'];
        $caseHistoryID = $inputData['caseHistoryID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    
        try {
            $db->delete('CaseHistory', 'ID = ' . $caseHistoryID);
            $db->delete('CaseHistoryRow', array(
                'CaseHistoryID = ?' => $caseHistoryID
            ));
            // cancello anche le body measures
            $selectBody = $db->select()
                                ->from(array('b'=>'Body'),array('b.*'))
                                ->where('b.PatientID = ?', $patientID);
            $bodyResults = $db->fetchAll($selectBody);
            if (count($bodyResults) > 0) {
                $body = $bodyResults[0]->ID;
                $db->delete('Body', 'ID = ' . $body);
                $db->delete('BodyMeasure', array(
                    'BodyID = ?' => $body
                ));
            }
        } 
        catch (Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
            'response' => 'success',
            'patientID' => $patientID
        );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    public function getquestionsAction() {
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
            
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            $selectQuestions = $db->select()
                                  ->from(array('q'=>'CaseHistoryQuestion'),array('q.*'));
            $questions = $db->fetchAll($selectQuestions);
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'data' => $questions
            );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function addbodymeasureAction() {
        
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        
        $patientID = $inputData['patientID'];
        $doctorID = $inputData['doctorID'];
        if ($doctorID == '')
            $doctorID = $identity->ID;
        $bodyID = $inputData['bodyID'];
        $weight = $inputData['weight'];
        $height = $inputData['height'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            date_default_timezone_set('Europe/Rome');
            if ($bodyID == '') {
                // devo creare un body nuovo
                $data = array( 'DoctorID' => $doctorID,
                    'PatientID' => $patientID);
                
                $data['LogID'] = $this->createUniqueLogID();
                $db->insert('Body', $data);
                $lastInsertBodyID = $db->lastInsertId();
                $this->log($db,$data['LogID'],$identity->ID,'create');
            
                // aggiungo una nuova misurazione
                $data2 = array( 'Weight' => $weight,
                    'Height' => $height,
                    'BodyID' => $lastInsertBodyID,
                    'ObservationDate' => date('Y-m-d H:i:s'));
                $db->insert('BodyMeasure', $data2);
                
                $this->log($db,$data['LogID'],$identity->ID,'update');
            }
            else {
                // aggiungo una nuova misurazione
                $data = array( 'Weight' => $weight,
                    'Height' => $height,
                    'BodyID' => $bodyID,
                    'ObservationDate' => date('Y-m-d H:i:s'));
                $db->insert('BodyMeasure', $data);
                
                $testSelect = $db->select()
                            ->from(array('b'=>'Body'),array('b.*'))
                            ->where('b.ID = ?', $bodyID);
                $body = $db->fetchAll($testSelect);
                $this->log($db,$body[0]->LogID,$identity->ID,'update');
            }
            
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID
            );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    public function deletelastbodymeasureAction() {
        
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        
        $patientID = $inputData['patientID'];
        $doctorID = $inputData['doctorID'];
        if ($doctorID == '')
            $doctorID = $identity->ID;
        $bodyID = $inputData['bodyID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            
            date_default_timezone_set('Europe/Rome');
            // rimuovo l'ultima misurazione
            $bodyMeasureSelect = $db->select()
                        ->from(array('bm'=>'BodyMeasure'),array('bm.*'))
                        ->where('bm.BodyID = ?', $bodyID)
                        ->order(array('bm.ObservationDate ASC'));
            $bodyMeasure = $db->fetchAll($bodyMeasureSelect);
            
            if (count($bodyMeasure) > 0) {
                $lastBodyMeasure = end($bodyMeasure);
                $lastBodyMeasureID = $lastBodyMeasure->ID;

                $db->delete('BodyMeasure', 'ID = ' . $lastBodyMeasureID);

                $testSelect = $db->select()
                            ->from(array('b'=>'Body'),array('b.*'))
                            ->where('b.ID = ?', $bodyID);
                $body = $db->fetchAll($testSelect);
                $this->log($db,$body[0]->LogID,$identity->ID,'delete');
            }

        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID
            );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    // INVOICE
    
    public function createinvoiceAction() {
        
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $doctorID = $inputData['doctorID'];
        $patientID = $inputData['patientID'];
        //$dateCreated = $inputData['dateCreated'];
        $appointmentID = $inputData['appointmentID'];
        $invoiceData = $inputData['invoiceData'];
        //$invoiceNumber = '-1';
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            
            // creo una nuova fattura

            // trovo l'ultimo numero di fattura disponibile in quest'anno
            // ottengo l'anno corrente
            $currentYear = gmdate("Y");
            $maxSelect = $db->select()
                            ->from(array('i'=>'Invoice'),array('MAX(InvoiceNumber) AS maxInvoiceNumber'))
                            //->join(array('l'=>'Log'),'l.UniqueID = i.LogID')
                            ->where('i.Closed = ?','1')
                            ->where('i.DoctorID = ?',$doctorID)
                            //->where('l.Action = ?','create')
                            //->where('YEAR(l.Date) = ' . $currentYear);
                            ->where('YEAR(i.DateSort) = ' . $currentYear);
            $maxInvoiceNumber = $db->fetchOne($maxSelect);
            if ($maxInvoiceNumber == -1)
                $maxInvoiceNumber = 0;
            $invoiceNumber = $maxInvoiceNumber+1;
            
            // prima inserisco la fattura del database...
            date_default_timezone_set('Europe/Rome');
            $data = array('DoctorID' => $doctorID,
                'PatientID' => $patientID,
                'AppointmentID' => $appointmentID,
                'DateSort' => date('Y-m-d H:i:s'),
                'InvoiceNumber' => $invoiceNumber,
                'Closed' => '0');

            $data['LogID'] = $this->createUniqueLogID();
            $db->insert('Invoice', $data);
            $lastInsertID = $db->lastInsertId();
            $this->log($db,$data['LogID'],$identity->ID,'create');

            // se l'inserimento è andato a buon fine, inserisco le righe della fattura
            foreach($invoiceData as $invoiceRow) {
                $data = array('InvoiceID' => $lastInsertID,
                              'Description' => urldecode($invoiceRow['Description']),
                              'Amount' => $invoiceRow['Amount']
                );
                $db->insert('InvoiceRow', $data);
            }
            
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID    // ritorno il patient ID per forzare il refresh dei documenti nell'app
            );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    public function closeinvoiceAction() {
        
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $doctorID = $inputData['doctorID'];
        $patientID = $inputData['patientID'];
        $invoiceID = $inputData['invoiceID'];
        
        // ottengo l'anno corrente
        $currentYear = gmdate("Y");
        // trovo il numero di fattura più alto
        $maxSelect = $db->select()
                        ->from(array('i'=>'Invoice'),array('MAX(InvoiceNumber) AS maxInvoiceNumber'))
                        //->join(array('l'=>'Log'),'l.UniqueID = i.LogID')
                        ->where('i.Closed = ?','1')
                        ->where('i.DoctorID = ?',$doctorID)
                        //->where('l.Action = ?','create')
                        //->where('YEAR(l.Date) = ' . $currentYear);
                        ->where('YEAR(i.DateSort) = ' . $currentYear);
        $maxInvoiceNumber = $db->fetchOne($maxSelect);
        if ($maxInvoiceNumber == -1)
            $maxInvoiceNumber = 0;
        $invoiceNumber = $maxInvoiceNumber+1;
        
        try {
            $data = array('InvoiceNumber' => $invoiceNumber, 'Closed' => '1');
            $db->update('Invoice', $data, 'Invoice.ID = '.$invoiceID); // da aggiungere patientID e doctorID come controllo...

            $testSelect = $db->select()
                            ->from(array('i'=>'Invoice'),array('i.*'))
                            ->where('i.ID = ?', $invoiceID);
            $invoices = $db->fetchAll($testSelect);
            $this->log($db,$invoices[0]->LogID,$identity->ID,'update');
            
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID    // ritorno il patient ID per forzare il refresh dei documenti nell'app
            );
        echo json_encode($jsonResponse);
        exit;
    }

    public function updateinvoiceappointmentlinkAction() {
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $doctorID = $inputData['doctorID'];
        $appointmentID = $inputData['appointmentID'];
        $invoiceID = $inputData['invoiceID'];
        $patientID = $inputData['patientID'];

        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }

        try {
            $data = array( 'AppointmentID' => $appointmentID);
            $db->update('Invoice', $data, 'Invoice.ID = '.$invoiceID);
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }

        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID    // ritorno il patient ID per forzare il refresh dei documenti nell'app
            );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function updateinvoiceAction() {
        
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $doctorID = $inputData['doctorID'];
        $patientID = $inputData['patientID'];
        //$dateCreated = $inputData['dateCreated'];
        $appointmentID = $inputData['appointmentID'];
        $invoiceID = $inputData['invoiceID'];
        $invoiceData = $inputData['invoiceData'];
        $invoiceNumber = $inputData['invoiceNumber'];
        $paymentType = $inputData['paymentType'];
        $ritenuta = $inputData['ritenuta'];
        $invoiceDate = $inputData['invoiceDate'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            
            $data = array( 'InvoiceNumber' => $invoiceNumber,
                          'PaymentType' => $paymentType,
                          'Ritenuta' => $ritenuta,
                          'DateSort' => $invoiceDate);
            $db->update('Invoice', $data, 'Invoice.ID = '.$invoiceID);
            
            // cancello tutte le righe preesistenti (faccio prima...)
            $db->delete('InvoiceRow', array(
                'InvoiceID = ?' => $invoiceID
            ));

            foreach ($invoiceData as $value) {
                $description = $value['Description'];
                $amount = $value['Amount'];
                //$amount = number_format($value['Amount'], 2, '.', '');

                
                $data = array( 'Description' => urldecode($description),
                    'Amount' => $amount,
                    'InvoiceID' => $invoiceID);

                $db->insert('InvoiceRow', $data);
                
            }

            $testSelect = $db->select()
                            ->from(array('i'=>'Invoice'),array('i.*'))
                            ->where('i.ID = ?', $invoiceID);
            $invoices = $db->fetchAll($testSelect);
            $this->log($db,$invoices[0]->LogID,$identity->ID,'update');
            
        }
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID    // ritorno il patient ID per forzare il refresh dei documenti nell'app
            );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    public function deleteinvoiceAction() {
        
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $patientID = $inputData['patientID'];
        $invoiceID = $inputData['invoiceID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    
        try {
            $db->delete('Invoice', 'ID = ' . $invoiceID);
            $db->delete('InvoiceRow', array(
                'InvoiceID = ?' => $invoiceID
            ));
        } catch (Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
            'response' => 'success',
            'patientID' => $patientID
        );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    // IMAGE AND TAGS
    
    public function deleteimageAction() {
        
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $doctorID = $inputData['doctorID'];
        $patientID = $inputData['patientID'];
        $filePath = $inputData['filePath'];
        $imageID = $inputData['imageID'];
        $imageArchiveID = $inputData['imageArchiveID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
    
        try {
            
            // cancello le tag
            $imageSelect = $db->select()
                            ->from(array('i'=>'Image'),array('i.*'))
                            ->where('i.ID = ?', $imageID);
            $images = $db->fetchAll($imageSelect);
            if (count($images) > 0) {
                $tagPlanID = $images[0]->TagPlanID;
                $db->delete('TagPlan', 'ID = ' . $tagPlanID);
                $db->delete('TagElement', 'TagPlanID = ' . $tagPlanID);
            }
            
            // cancello l'immagine
            $db->delete('Image', 'ID = ' . $imageID);
            
            // metto un update sul log
            $testSelect = $db->select()
                            ->from(array('ia'=>'ImageArchive'),array('ia.*'))
                            ->where('ia.ID = ?', $imageArchiveID);
            $selectImageArchive = $db->fetchAll($testSelect);
            $this->log($db,$selectImageArchive[0]->LogID,$identity->ID,'update');
            
            // infine cancello l'immagine da S3
            $s3 = S3Client::factory(array(
                'key'    => 'AKIAJURCZ3DPUKLJ6SPQ',
                'secret' => '84/BS0pjz85MJO5D+2UsKp0IYesYK+MjFm74nYFB'
            ));
            $s3->deleteMatchingObjects('dfmimagearchive', $filePath);
            $filePathThumb = str_replace('.jpg','_thumb.jpg', $filePath);
            $s3->deleteMatchingObjects('dfmimagearchive', $filePathThumb);

        } catch (Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }
        
        header ("Content-type: application/json");
        $jsonResponse = array(
            'response' => 'success',
            'patientID' => $patientID
        );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    public function uploadimageAction() {
     
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        
        $imagePath = $inputData['imagePath'];
        $tags = $inputData['tags'];
        $patientID = $inputData['patientID'];
        $doctorID = $inputData['doctorID'];
        //$aptID = $inputData['appointmentID'];
        $imageArchiveID = $inputData['imageArchiveID'];
        $createdDate = $inputData['createdDate'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        // ottengo il logID dell'imageAlbumArchive
        $selectAlbum = $db->select()
                        ->from(array('ia'=>'ImageArchive'),array('ia.*'))
                        ->where('ia.ID = ?', $imageArchiveID);
        $albums = $db->fetchAll($selectAlbum);
        $logID = $albums[0]->LogID;
        
        try {
            
            $testSelect = $db->select()
                    ->from(array('i'=>'Image'),array('i.*'))
                    ->where('i.Filepath = ?', $imagePath); 
            $testImage = $db->fetchAll($testSelect);
            if (count($testImage) == 0) {
                // se l'immagine non esiste:
                
                // creo un TagPlan 
                $data = array('DoctorID' => $doctorID);
                $db->insert('TagPlan', $data);
                $tagPlanID = $db->lastInsertId();
                // ...con un TagElement per ogni tag
                foreach ($tags as $value) {
                    $tagValue = urldecode($value['Value']);
                    $tagType = $value['Type'];
                    $data = array( 
                        'TagPlanID' => $tagPlanID,
                        'Type' => $tagType,
                        'Value' => $tagValue);
                    $db->insert('TagElement', $data);
                }
                
                // e poi aggiungo l'immagine  
                $data = array( 
                    'Filepath' => $imagePath,
                    'ImageArchiveID' => $imageArchiveID,
                    'TagPlanID' => $tagPlanID,
                    'CreatedDate' => $createdDate
                );
                $db->insert('Image', $data);
            }
            else {
                // altrimenti aggiorno solo le tag   
                // tolgo tutte le tag presenti
                $db->delete('TagElement', 'TagPlanID = ' . $testImage[0]->TagPlanID);
                // ...e rimetto le nuove
                foreach ($tags as $value) {
                    $tagValue = urldecode($value['Value']);
                    $tagType = $value['Type'];
                    $data = array( 
                        'TagPlanID' => $testImage[0]->TagPlanID,
                        'Type' => $tagType,
                        'Value' => $tagValue);
                    $db->insert('TagElement', $data);
                }
            }
            
            // segno l'update nel log
            $this->log($db,$logID,$identity->ID,'update');
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }

        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID,
                'imagePath' => $imagePath
            );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    public function updateimagetagsAction() {
     
        $auth = Zend_Auth::getInstance(); 
        
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'login',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'acl',
                'message' => '',
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        
        $imageID = $inputData['imageID'];
        $tags = $inputData['tags'];
        $patientID = $inputData['patientID'];
        $doctorID = $inputData['doctorID'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                'response' => 'error',
                'type' => 'database connection',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        try {
            
            $testSelect = $db->select()
                    ->from(array('i'=>'Image'),array('i.*'))
                    ->where('i.ID = ?', $imageID); 
            $testImage = $db->fetchAll($testSelect);
            if (count($testImage) > 0) {
                
                // ottengo il logID dell'imageAlbumArchive per segnare l'update
                $selectAlbum = $db->select()
                                ->from(array('ia'=>'ImageArchive'),array('ia.*'))
                                ->where('ia.ID = ?', $testImage[0]->ImageArchiveID)
                                ->where('ia.PatientID = ?', $patientID) 
                                ->where('ia.DoctorID = ?', $doctorID); 
                $albums = $db->fetchAll($selectAlbum);
                $logID = $albums[0]->LogID;

                // tolgo tutte le tag presenti
                $db->delete('TagElement', 'TagPlanID = ' . $testImage[0]->TagPlanID);
                // ...e rimetto le nuove
                foreach ($tags as $value) {
                    $tagValue = urldecode($value['Value']);
                    $tagType = $value['Type'];
                    $data = array( 
                        'TagPlanID' => $testImage[0]->TagPlanID,
                        'Type' => $tagType,
                        'Value' => $tagValue);
                    $db->insert('TagElement', $data);
                }
            }
            
            // segno l'update nel log
            $this->log($db,$logID,$identity->ID,'update');
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
            $jsonResponse = array(
                'response' => 'error',
                'type' => 'database',
                'message' => $e->getMessage(),
                'controller' => $this->getRequest()->getControllerName(),
                'action' => $this->getRequest()->getActionName()
            );
            echo json_encode($jsonResponse);
            exit;
        }

        header ("Content-type: application/json");
        $jsonResponse = array(
                'response' => 'success',
                'patientID' => $patientID
            );
        echo json_encode($jsonResponse);
        exit;
        
    }
    
    // LOG
    
    public function getlogAction() {
        
        $auth = Zend_Auth::getInstance(); 
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
                    'type' => 'login',
                    'message' => '',
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getControllerName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $identity = $auth->getIdentity();
        
        $registry = Zend_Registry::getInstance();
        $acl = $registry->get('acl');
        if (!$this->isAllowed($identity)) {
        //if (!$acl->isAllowed($identity->role,$this->getRequest()->getControllerName(),$this->getRequest()->getActionName())) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
                    'type' => 'acl',
                    'message' => '',
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getControllerName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }
            
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        
        $logID = $inputData['logID'];
        $type = $inputData['type'];
        
        $registry = Zend_Registry::getInstance();  
        $db = $registry['DB'];
        try {
            $db->getConnection();
        } 
        catch (Zend_Exception $e) {
            header ("Content-type: application/json");
		    $jsonResponse = array(
                    'response' => 'error',
	                'type' => 'database connection',
                    'message' => $e->getMessage(),
                    'controller' => $this->getRequest()->getControllerName(),
                    'action' => $this->getRequest()->getControllerName()
	            );
		    echo json_encode($jsonResponse);
            exit;
        }
        
        $selectLogs = $db->select()
                    ->from(array('l'=>'Log'),array('l.*'))
                    ->join(array('u'=>'User'),'l.UserID = u.ID',array('Fullname' => 'u.Fullname'))
                    ->where('l.UniqueID = ?', $logID)
                    ->order(array('l.Date DESC'));
        $logs = $db->fetchAll($selectLogs);

        header ("Content-type: application/json");
        $jsonResponse = array(
            'response' => 'success',
            'logs' => $logs,
            'type' => $type
        );
        echo json_encode($jsonResponse);
        exit;
    }

    // Android Google Foto: ottiene tutte le foto di tutti i pazienti del dottore
    public function getallphotosAction() {
        $this->_helper->viewRenderer->setNoRender();

        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity() == false) {
            header ("Content-type: application/json");
            echo json_encode(array('response' => 'error', 'message' => 'Not logged in'));
            exit;
        }

        $identity = $auth->getIdentity();
        if (!$this->isAllowed($identity)) {
            header ("Content-type: application/json");
            echo json_encode(array('response' => 'error', 'message' => 'Access denied'));
            exit;
        }

        $input = file_get_contents("php://input");
        $inputData = json_decode($input, true);

        if ($inputData === null || !isset($inputData['doctorID'])) {
            header ("Content-type: application/json");
            echo json_encode(array('response' => 'error', 'message' => 'Invalid parameters'));
            exit;
        }

        $doctorID = $inputData['doctorID'];

        $registry = Zend_Registry::getInstance();
        $db = $registry->get('DB');

        // Seleziona tutte le foto di tutti i pazienti del dottore, ordinate per data decrescente
        $selectImages = $db->select()
            ->from(array('i'=>'Image'), array('i.*'))
            ->join(array('ia'=>'ImageArchive'), 'i.ImageArchiveID = ia.ID',
                   array('AlbumTitle' => 'ia.Title', 'PatientID' => 'ia.PatientID'))
            ->join(array('p'=>'Patient'), 'ia.PatientID = p.ID',
                   array('PatientName' => new Zend_Db_Expr("CONCAT(p.Firstname, ' ', p.Lastname)")))
            ->where('ia.DoctorID = ?', $doctorID)
            ->where('ia.Enabled = 1')
            ->order('i.CreatedDate DESC')
            ->limit(200);  // Limita a 200 foto per performance

        $images = $db->fetchAll($selectImages);

        // Per ogni immagine, carica i tags
        foreach ($images as &$image) {
            $selectTags = $db->select()
                ->from(array('te'=>'TagElement'), array('te.*'))
                ->where('te.ImageID = ?', $image->ID);
            $tags = $db->fetchAll($selectTags);
            $image->Tags = $tags;
        }

        header ("Content-type: application/json");
        $jsonResponse = array(
            'response' => 'success',
            'images' => $images,
            'count' => count($images)
        );
        echo json_encode($jsonResponse);
        exit;
    }

}