<?php
require_once 'Zend/Controller/Action.php';
require_once 'Zend/Auth.php';
require_once 'Zend/Auth/Adapter/DbTable.php';
    
class SettingsController 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);
    }
    
    public function getsettingsAction() {
        
        $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'];
        
        $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;
        }
        
        $db->query("SET NAMES 'utf8'");
        
        try {
            $selectActivities = $db->select()
                            ->from(array('a'=>'ActivityType'),array('a.*'))
                            ->where('a.DoctorID = ?',$doctorID)
                            ->order(array('a.Name ASC'));
            $activities = $db->fetchAll($selectActivities);

            $selectRooms = $db->select()
                            ->from(array('r'=>'Room'),array('r.*'))
                            ->order(array('r.Name ASC'))
                            ->where('r.DoctorID = ?',$doctorID);
                            //->orWhere('r.DoctorID = ?',0); // valide per tutti i dottori
            $rooms = $db->fetchAll($selectRooms);

            $selectProcedures = $db->select()
                            ->from(array('mp'=>'MedProcedure'),array('mp.*'))
                            ->where('mp.DoctorID = ?',$doctorID)
                            ->order(array('mp.Name ASC'));
            $procedures = $db->fetchAll($selectProcedures);

            $selectQuestions = $db->select()
                            ->from(array('q'=>'CaseHistoryQuestion'),array('q.*'))
                            ->where('q.DoctorID = ?',$doctorID)
                            ->order(array('q.SortOrder ASC'));
            $questions = $db->fetchAll($selectQuestions);

            $selectLocations = $db->select()
                            ->from(array('l'=>'Location'),array('l.*'))
                            ->where('l.DoctorID = ?',$doctorID)
                            ->order(array('l.Name ASC'));
            $locations = $db->fetchAll($selectLocations);

            $selectTemplates = $db->select()
                            ->from(array('jt'=>'JournalTemplate'),array('jt.*'))
                            ->where('jt.DoctorID = ?',$doctorID);
            $templates = $db->fetchAll($selectTemplates);
            
            $selectReferences = $db->select()
                            ->from(array('ref'=>'Reference'),array('ref.*'))
                            ->where('ref.DoctorID = ?',$doctorID);
            $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;
        }
        
        $output = array(
            'activities' => $activities,
            'procedures' => $procedures,
            'rooms' => $rooms,
            'questions' => $questions,
            'locations' => $locations,
            'template' => $templates,
            'reference' => $references
        );
        
        header ("Content-type: application/json; charset=utf-8");
        $jsonResponse = array(
            'response' => 'success',
            'data' => $output
        );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function createorupdateactivityAction() {
        
        $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);
        $activityID = $inputData['activityID'];
        $activityName = $inputData['activityName'];
        $activityNameEN = isset($inputData['activityNameEN']) ? $inputData['activityNameEN'] : null;
        $activityColor = $inputData['activityColor'];
        $doctorID = $inputData['doctorID'];

        try {
            if ($activityID == '') {
                // inserimento nuova attività
                $data = array('Name' => $activityName,
                    'NameEN' => $activityNameEN,
                    'CalendarColor' => $activityColor,
                    'DoctorID' => $doctorID);

                $db->insert('ActivityType', $data);
            }
            else {
                // aggiornamento attività esistente
                $data = array( 'ID' => $activityID,
                    'Name' => $activityName,
                    'NameEN' => $activityNameEN,
                    'CalendarColor' => $activityColor,
                    'DoctorID' => $doctorID);

                $db->update('ActivityType', $data, 'ActivityType.ID = '.$activityID);
            }
        }
        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'
            );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function createorupdateroomAction() {
        
        $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;
        }
        
        //$db->query("SET NAMES 'utf8'");
        
        $input = file_get_contents("php://input");
        $inputData = json_decode($input,true);
        $roomID = $inputData['roomID'];
        $roomName = $inputData['roomName'];
        $locationID = $inputData['locationID'];
        $doctorID = $inputData['doctorID'];
        $roomColor = $inputData['roomColor'];
        
        try {    
            if ($roomID == '') {
                // estraggo gli appuntamenti per la settimana
                $data = array('Name' => $roomName,
                    'LocationID' => $locationID,
                    'DoctorID' => $doctorID,
                    'RoomColor' => $roomColor);

                $db->insert('Room', $data);
            }
            else {
                // estraggo gli appuntamenti per la settimana
                $data = array( 'ID' => $roomID,
                    'Name' => $roomName,
                    'LocationID' => $locationID,
                    'DoctorID' => $doctorID,
                    'RoomColor' => $roomColor);

                $db->update('Room', $data, 'Room.ID = '.$roomID);
            }
        }
        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'
            );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function createorupdatelocationAction() {
        
        $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);
        $locationID = $inputData['locationID'];
        $locationName = $inputData['locationName'];
        $locationAddress = $inputData['locationAddress'];
        $locationZip = $inputData['locationZip'];
        $locationCity = $inputData['locationCity'];
        $locationState = $inputData['locationState'];
        $locationColor = $inputData['locationColor'];
        $doctorID = $inputData['doctorID'];
        
        try {
            if ($locationID == '') {
                $data = array('Name' => $locationName,
                              'Address' => $locationAddress,
                              'Zip' => $locationZip,
                              'City' => $locationCity,
                              'State' => $locationState,
                              'LocationColor' => $locationColor,
                              'DoctorID' => $doctorID);
                $db->insert('Location', $data);
            }
            else {
                $data = array('Name' => $locationName,
                              'Address' => $locationAddress,
                              'Zip' => $locationZip,
                              'City' => $locationCity,
                              'State' => $locationState,
                              'LocationColor' => $locationColor,
                              'DoctorID' => $doctorID);

                $db->update('Location', $data, 'Location.ID = '.$locationID);
            }
        }
        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'
            );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function createorupdatequestionAction() {
        
        $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);
        $questionID = $inputData['questionID'];
        $question = urldecode($inputData['question']);
        $questionEN = isset($inputData['questionEN']) ? urldecode($inputData['questionEN']) : null;
        $answerWarning = $inputData['answerWarning'];
        $dependency = $inputData['dependency'];
        $doctorID = $inputData['doctorID'];

        try {
            if ($questionID == '') {
                // create
                $data = array('Question' => $question,
                            'QuestionEN' => $questionEN,
                            'DoctorID' => $doctorID,
                            'AnswerWarning' => $answerWarning,
                            'Dependency' => $dependency);
                $db->insert('CaseHistoryQuestion', $data);
            }
            else {
                // update
                $data = array('Question' => $question,
                    'QuestionEN' => $questionEN,
                    'DoctorID' => $doctorID,
                    'AnswerWarning' => $answerWarning,
                    'Dependency' => $dependency);
                $db->update('CaseHistoryQuestion', $data, 'CaseHistoryQuestion.ID = '.$questionID);
            }
        }
        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'
            );
        echo json_encode($jsonResponse);
        exit;
    }

    /**
     * Crea o aggiorna una domanda anamnesi con supporto V2
     * Salva sia nella tabella legacy (CaseHistoryQuestion) che V2 (CaseHistoryQuestion_V2 + CaseHistoryQuestionText)
     */
    public function createorupdatequestionv2Action() {

        $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)) {
            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);

        // Parametri base (compatibilità legacy)
        $questionID = $inputData['questionID'];
        $question = urldecode($inputData['question']);
        $questionEN = isset($inputData['questionEN']) ? urldecode($inputData['questionEN']) : null;
        $answerWarning = $inputData['answerWarning'];
        $dependency = $inputData['dependency'];
        $doctorID = $inputData['doctorID'];

        // Parametri V2
        $answerType = isset($inputData['answerType']) ? $inputData['answerType'] : 'yesno';
        $decimalPlaces = isset($inputData['decimalPlaces']) ? intval($inputData['decimalPlaces']) : 0;
        $unit = isset($inputData['unit']) ? $inputData['unit'] : null;
        $minValue = isset($inputData['minValue']) && $inputData['minValue'] !== '' ? $inputData['minValue'] : null;
        $maxValue = isset($inputData['maxValue']) && $inputData['maxValue'] !== '' ? $inputData['maxValue'] : null;
        $warningMinValue = isset($inputData['warningMinValue']) && $inputData['warningMinValue'] !== '' ? $inputData['warningMinValue'] : null;
        $warningMaxValue = isset($inputData['warningMaxValue']) && $inputData['warningMaxValue'] !== '' ? $inputData['warningMaxValue'] : null;
        $formula = isset($inputData['formula']) ? $inputData['formula'] : null;
        $formulaAlias = isset($inputData['formulaAlias']) ? $inputData['formulaAlias'] : null;

        // Determina NeedYesNo per tabella legacy
        $needYesNo = ($answerType === 'yesno') ? 1 : 0;

        try {
            $db->beginTransaction();

            $legacyID = null;

            if ($questionID == '') {
                // === CREATE ===

                // 1. Inserisci in tabella legacy
                $dataLegacy = array(
                    'Question' => $question,
                    'QuestionEN' => $questionEN,
                    'DoctorID' => $doctorID,
                    'AnswerWarning' => $answerWarning,
                    'Dependency' => $dependency,
                    'NeedYesNo' => $needYesNo
                );
                $db->insert('CaseHistoryQuestion', $dataLegacy);
                $legacyID = $db->lastInsertId();

                // 2. Inserisci in tabella V2
                $dataV2 = array(
                    'DoctorID' => $doctorID,
                    'AnswerType' => $answerType,
                    'DecimalPlaces' => $decimalPlaces,
                    'Unit' => $unit,
                    'MinValue' => $minValue,
                    'MaxValue' => $maxValue,
                    'WarningMinValue' => $warningMinValue,
                    'WarningMaxValue' => $warningMaxValue,
                    'AnswerWarning' => $answerWarning,
                    'Formula' => $formula,
                    'FormulaAlias' => $formulaAlias,
                    'DependencyID' => ($dependency && $dependency !== '0') ? $dependency : null,
                    'LegacyID' => $legacyID,
                    'Enabled' => 1
                );
                $db->insert('CaseHistoryQuestion_V2', $dataV2);
                $v2ID = $db->lastInsertId();

                // 3. Inserisci testi multilingua
                $db->insert('CaseHistoryQuestionText', array(
                    'QuestionID' => $v2ID,
                    'LanguageCode' => 'IT',
                    'QuestionText' => $question
                ));
                if ($questionEN) {
                    $db->insert('CaseHistoryQuestionText', array(
                        'QuestionID' => $v2ID,
                        'LanguageCode' => 'EN',
                        'QuestionText' => $questionEN
                    ));
                }
            }
            else {
                // === UPDATE ===

                // 1. Aggiorna tabella legacy
                $dataLegacy = array(
                    'Question' => $question,
                    'QuestionEN' => $questionEN,
                    'DoctorID' => $doctorID,
                    'AnswerWarning' => $answerWarning,
                    'Dependency' => $dependency,
                    'NeedYesNo' => $needYesNo
                );
                $db->update('CaseHistoryQuestion', $dataLegacy, 'ID = '.$questionID);
                $legacyID = $questionID;

                // 2. Trova o crea record V2
                $selectV2 = $db->select()
                    ->from('CaseHistoryQuestion_V2', array('ID'))
                    ->where('LegacyID = ?', $legacyID);
                $v2Row = $db->fetchRow($selectV2);

                $dataV2 = array(
                    'DoctorID' => $doctorID,
                    'AnswerType' => $answerType,
                    'DecimalPlaces' => $decimalPlaces,
                    'Unit' => $unit,
                    'MinValue' => $minValue,
                    'MaxValue' => $maxValue,
                    'WarningMinValue' => $warningMinValue,
                    'WarningMaxValue' => $warningMaxValue,
                    'AnswerWarning' => $answerWarning,
                    'Formula' => $formula,
                    'FormulaAlias' => $formulaAlias,
                    'DependencyID' => ($dependency && $dependency !== '0') ? $dependency : null,
                    'LegacyID' => $legacyID,
                    'Enabled' => 1
                );

                if ($v2Row) {
                    // Update V2
                    $v2ID = $v2Row->ID;
                    $db->update('CaseHistoryQuestion_V2', $dataV2, 'ID = '.$v2ID);

                    // Update testi
                    $db->delete('CaseHistoryQuestionText', 'QuestionID = '.$v2ID);
                } else {
                    // Insert V2
                    $db->insert('CaseHistoryQuestion_V2', $dataV2);
                    $v2ID = $db->lastInsertId();
                }

                // 3. Inserisci testi multilingua
                $db->insert('CaseHistoryQuestionText', array(
                    'QuestionID' => $v2ID,
                    'LanguageCode' => 'IT',
                    'QuestionText' => $question
                ));
                if ($questionEN) {
                    $db->insert('CaseHistoryQuestionText', array(
                        'QuestionID' => $v2ID,
                        'LanguageCode' => 'EN',
                        'QuestionText' => $questionEN
                    ));
                }
            }

            $db->commit();
        }
        catch (Zend_Exception $e) {
            $db->rollBack();
            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',
            'legacyID' => $legacyID
        );
        echo json_encode($jsonResponse);
        exit;
    }

    public function createorupdateprocedureAction() {
        
        $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);
        $procedureID = $inputData['procedureID'];
        $procedureName = $inputData['procedureName'];
        $procedureNameEN = isset($inputData['procedureNameEN']) ? $inputData['procedureNameEN'] : null;
        $doctorID = $inputData['doctorID'];

        try {
            if ($procedureID == '') {
                // create
                $data = array('Name' => $procedureName,
                    'NameEN' => $procedureNameEN,
                    'DoctorID' => $doctorID);
                $db->insert('MedProcedure', $data);
            }
            else {
                // update
                $data = array( 'ID' => $procedureID,
                    'Name' => $procedureName,
                    'NameEN' => $procedureNameEN,
                    'DoctorID' => $doctorID);
                $db->update('MedProcedure', $data, 'MedProcedure.ID = '.$procedureID);
            }
        }
        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'
        );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function createorupdatetemplateAction() {
        
        $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);
        $templateID = $inputData['templateID'];
        $templateName = $inputData['templateName'];
        $doctorID = $inputData['doctorID'];
        
        try {
            if ($templateID == '') {
                // create
                $data = array('Name' => $templateName,
                    'DoctorID' => $doctorID);
                $db->insert('JournalTemplate', $data);
            }
            else {
                // update
                $data = array('Name' => $templateName,
                    'DoctorID' => $doctorID);
                $db->update('JournalTemplate', $data, 'JournalTemplate.ID = '.$templateID);
            }
        }
        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'
        );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function createorupdatereferenceAction() {
        
        $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);
        $referenceID = $inputData['referenceID'];
        $referenceName = $inputData['referenceName'];
        $doctorID = $inputData['doctorID'];
        
        try {
            if ($referenceID == '') {
                // create
                $data = array('Description' => $referenceName,
                    'DoctorID' => $doctorID,
                    'Enabled' => 1);
                $db->insert('Reference', $data);
            }
            else {
                // update
                $data = array('Description' => $referenceName,
                    'DoctorID' => $doctorID);
                $db->update('Reference', $data, 'Reference.ID = '.$referenceID);
            }
        }
        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'
        );
        echo json_encode($jsonResponse);
        exit;
    }
    
    public function updatedoctorcolorAction() {
        
        $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'];
        $doctorColor = $inputData['doctorColor'];
        
        // update
        $data = array( 'id' => $doctorID,
            'userColor' => $doctorColor);

        try {
            $db->update('User', $data, 'User.ID = '.$doctorID);
        } 
        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 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;
        }
        
        $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'];
        $ID = $inputData->ID;
        $type = $inputData['type'];
        $enabled = $inputData['enabled'];
        
        // update
        $data = array( 'Enabled' => $enabled);
        
        try {
            $db->update($type, $data, 'ID = ' . $ID);
        } 
        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;
    }

}