<?php
/*

ALTER TABLE `tblCourse` DROP FOREIGN KEY `tblCourse.strCourseType`;
ALTER TABLE `tblCourse` ADD CONSTRAINT `tblCourse.strCourseType` FOREIGN KEY ( `refCourseTypeID` ) REFERENCES `tblCourseType` ( `CourseTypeID` ) ON DELETE CASCADE ON UPDATE CASCADE ;


 * 
20130829 - added WS indicator (public function __construct($DataKey, $blnWorkshop=0)) - pj
-2013-09-03 getLearnerCopy() uses the currentCourseID and Course type as arguments and builds a small container under learner list
   on the course details page with a submit button and a dropdown list populated by course names of all courses that have the same course type
   as the current course but is not the current course and it's end date is not earlier then today. -christiaan
-2013-09-03 CopyLearnerCourse() takes the current course for an array of learners and changes it to the new specified course
   and it also sends and course start email to the learners email -christiaan
-2013-10-02 CopyLearnerCourse() Also copies response, milestone, and assessment details for the learner. -Christiaan
-20150324 - remove coursetype dropdown for WI page-Christiaan
20150723 - Upgrade to be php 5.6 compliant - Christiaan
20160329 - Force end date to start date depreceated , asked by Alida - Christiaan
//20181106 - Course/CPD - ClassOfBusiness - pj
//20181114 - Added AML Addition Manual Import - Rachel
//20181206 - Sync To Live - pj/R
//20190801 - LOOK INTO GIVING USER ACCESS TO ONLY 1 COURSE - JACQUES
//20190830 - Manually Add Learners for all other courses (Non AML and IBC Courses) - Rachel
 */

include_once("_nemo.list.cls.php");

//2013 -09-03 Added includes statement for email handling in the move Learner method below -christiaan
include_once("_nemo.email.cls.php");

class Course extends NemoList
{
   private $ID = 0;
   public $controler;

   public function __construct($DataKey, $blnWorkshop=0, $blnWI=0)
   {
      //20130829 - added WS indicator - pj
      $this->blnWorkshop = $blnWorkshop;
      $this->blnWI = $blnWI;

      if($this->blnWorkshop == 0)
         $this->controler = "course.php";
      else
         $this->controler = "workshop.php";

      if($this->blnWI == 1)
         $this->controler = "wealth.intelligence.php";

      //filters


      $this->Filters[frCourseType]->tag = "select";
      $this->Filters[frCourseType]->html->value = "0"; //defalt value = 0, -1 = '- Unassigned -'
      $this->Filters[frCourseType]->html->class = "controlText";
      $this->Filters[frCourseType]->sql = "
                        SELECT 0 AS ControlValue, '- All -' AS ControlText
                        UNION ALL
                        SELECT `CourseTypeID` AS ControlValue, concat(strCourseType,' (',count(CourseID),')') AS ControlText
                        FROM tblCourseType INNER JOIN tblCourse ON tblCourseType.CourseTypeID = tblCourse.refCourseTypeID
                        WHERE tblCourseType.blnActive = 1 AND tblCourseType.blnWorkshop = $blnWorkshop
                        GROUP BY CourseTypeID, strCourseType
                        ORDER BY ControlText ASC";
      //20150324 - if the course is a WI course, course type is always = INT , so remove the dropdown -Christiaan
      if($this->blnWI == 1)
      {
         //$this->Filters[frCourseType]->html->disabled = "disabled";
         unset($this->Filters[frCourseType]);
      }

      $this->Filters[frStatus]->tag = "select";
      $this->Filters[frStatus]->html->value = "1";
      $this->Filters[frStatus]->html->class = "controlText";
      $this->Filters[frStatus]->sql = "SELECT -1 AS ControlValue, '- All -' AS ControlText
                        UNION ALL
                        SELECT 1 AS ControlValue, 'Active' AS ControlText
                        UNION ALL
                        SELECT 0 AS ControlValue, 'Inactive' AS ControlText

                        ORDER BY ControlText ASC";

      $this->Filters[frShowCPDCourses]->tag = "select";
      $this->Filters[frShowCPDCourses]->html->value = "-1";
      $this->Filters[frShowCPDCourses]->html->class = "controlText";
      $this->Filters[frShowCPDCourses]->sql = "SELECT -1 AS ControlValue, '- All Courses -' AS ControlText
                        UNION ALL
                        SELECT 1 AS ControlValue, 'CPD Only' AS ControlText

                        ORDER BY ControlText ASC";

      $this->Filters[frSearch]->tag = "input";
      $this->Filters[frSearch]->html->value = "";
      $this->Filters[frSearch]->html->type = "text";
      $this->Filters[frSearch]->html->class = "controlText";

      parent::__construct($DataKey);
   }

   protected function ToolBar()
   {
      return "
      <div id='divToolBar' style='min-height: 90px;'>
         <div style='float:left;'>
            <table class='tblBlank'>
               <tr>
                  <td><img src='images/extraimages/header/icon-48-module.png' height='44'></img></td>
                  <td style='padding: 16px;'><span class='textHeading'>". $this->ToolBar->Label ."</span></td>
                  <td style='position: relative; border: 0px dashed orange; padding: 0px;'>". $this->ToolBar->Block . $this->renderFilters() ."</td>
               </tr>
            </table>
         </div>
         <div class='divButtons'>
            ". $this->renderToolbarButtons() ."
         </div>
      </div>
      ";
   }

   private function getListSQL($Having = "", $where ="", $blnEnableFiltering=1)
   {
      global $SystemSettings;
      $Where = "";
      if($blnEnableFiltering)
      {
         if($this->Filters[frSearch]->html->value != "")
         {
            $like = "LIKE(". $this->db->qs("%".$this->Filters[frSearch]->html->value."%") .")";
            $Where .= " AND (tblCourse.CourseID $like
               OR tblCourse.strCourse $like
               OR tblCourse.strCourseCode $like
               OR tblCourse.strFPIReferenceNumber $like
               OR tblCourse.refCPDCategory $like
               OR tblCourse.txtNotes $like )";

         }
         if($this->Filters[frCourseType]->html->value != 0)
         {
            $Where .= " AND tblCourse.refCourseTypeID = ". $this->Filters[frCourseType]->html->value;
         }
         if($this->Filters[frStatus]->html->value != -1)
         {
            $Where .= " AND tblCourse.blnActive = ". $this->Filters[frStatus]->html->value;
         }
         if($this->Filters[frShowCPDCourses]->html->value != -1)
         {
            $Where .= " AND (IFNULL(tblCourse.strFPIReferenceNumber,'') <> '')";
         }

         // if($this->blnWorkshop <> 2)
         // {//20130829 - added WS indicator
         // 20151008 - disabled: show mix of courses and workshops (see BMS course type) - pj
         //    $Where .= " AND tblCourse.blnWorkshop = $this->blnWorkshop";
         // }
      }

      return "
         SELECT tblCourse.CourseID, tblCourse.strCourseHTML AS Course, tblCourse.strCourseCode AS Code, tblCourse.dtStartDate AS 'Start Date', tblCourse.dtEndDate AS 'End Date', Count(tblCourseLearners.refLearnerID) AS 'No Learners',  tblCourse.blnActive AS Active, tblCourse.strLastUser AS 'Last User', tblCourse.dtLastEdit AS 'Last Edit'
         FROM tblCourse
         LEFT JOIN (
            SELECT tblLicence.refCourseID, tblLicence.refLearnerID
            FROM tblLicence INNER JOIN tblLearner ON tblLicence.refLearnerID = tblLearner.LearnerID
            WHERE tblLicence.strStatus='Active'
            GROUP BY tblLicence.refCourseID, tblLicence.refLearnerID
         ) AS tblCourseLearners ON tblCourse.CourseID = tblCourseLearners.refCourseID
         WHERE 1=1 $Where $where AND tblCourse.blnWI = 0
         GROUP BY tblCourse.CourseID, tblCourse.strCourseHTML, tblCourse.strCourseCode, tblCourse.dtStartDate, tblCourse.dtEndDate, tblCourse.strCourseHTML
         HAVING 1=1 $Having
         ORDER BY tblCourse.dtStartDate DESC , tblCourse.strCourse, tblCourse.strCourseCode ";
   }


   public function getListWI($CourseTypeID=null)
   {
      global $SystemSettings;

      $Where = "";
      if($CourseTypeID != null)
      {
         $Where = " AND tblCourse.refCourseTypeID = '$CourseTypeID'";
      }else{
         if($this->Filters[frSearch]->html->value != "")
         {
            $like = "LIKE(". $this->db->qs("%".$this->Filters[frSearch]->html->value."%") .")";
            $Where .= " AND (tblCourse.CourseID $like OR tblCourse.strCourse $like OR tblCourse.strCourseCode $like )";
         }

         if($this->Filters[frStatus]->html->value != -1)
         {
            $Where .= " AND vieWealthIntelligence.blnActive = ". $this->Filters[frStatus]->html->value;
         }
      }


      $sql = "
         SELECT vieWealthIntelligence.CourseID, tblCourse.strCourseHTML AS Assignment, vieWealthIntelligence.dtReleaseDate AS 'Release Date', vieWealthIntelligence.dblCPDPointsFPI AS 'CPD Points', COUNT(tblCPDPoints.ID) AS 'No Learners', vieWealthIntelligence.blnActive AS Active, vieWealthIntelligence.strLastUser AS 'Last User', vieWealthIntelligence.dtLastEdit AS 'Last Edit'
         FROM tblCPDPoints RIGHT JOIN (tblCourse INNER JOIN vieWealthIntelligence ON tblCourse.CourseID = vieWealthIntelligence.CourseID) ON tblCPDPoints.refEventID = vieWealthIntelligence.CourseID
         WHERE 1=1 $Where
         GROUP BY vieWealthIntelligence.CourseID, tblCourse.strCourseHTML, vieWealthIntelligence.dtReleaseDate, vieWealthIntelligence.dblCPDPointsFPI, vieWealthIntelligence.blnActive, vieWealthIntelligence.strLastUser, vieWealthIntelligence.dtLastEdit
         ORDER BY vieWealthIntelligence.dtReleaseDate DESC";

      $this->ListSQL($sql, 0, "wealth.intelligence.php");
      return $this->renderTable("WI Assignments");
   }

   //HDP - 21/11/2016 - Added CTUC
   public function getListCTUC($CourseTypeID=null)
   {
      global $SystemSettings;

      // $Where = "";
      // if($CourseTypeID != null)
      // {
      //    $Where = " AND tblCourse.refCourseTypeID = '$CourseTypeID'";
      // }else{
      //    if($this->Filters[frSearch]->html->value != "")
      //    {
      //       $like = "LIKE(". $this->db->qs("%".$this->Filters[frSearch]->html->value."%") .")";
      //       $Where .= " AND (tblCourse.CourseID $like OR tblCourse.strCourse $like OR tblCourse.strCourseCode $like )";
      //    }

      //    if($this->Filters[frStatus]->html->value != -1)
      //    {
      //       $Where .= " AND vieWealthIntelligence.blnActive = ". $this->Filters[frStatus]->html->value;
      //    }
      // }


      $this->isSelectable = 0;
      $sql = "
            SELECT UserCategoryID, strUserCategory AS 'Course Type User Category', SUM(blnCTUCSelected) AS `Select` FROM (

            SELECT UserCategoryID, strUserCategory, 0 AS blnCTUCSelected
            FROM tblUserCategory
            WHERE blnActive = 1

            UNION ALL

            SELECT UserCategoryID, strUserCategory, 1 AS blnCTUCSelected
            FROM tblUserCategory
               INNER JOIN tblCourseTypeUserCategory on tblUserCategory.UserCategoryID = tblCourseTypeUserCategory.refUserCategoryID
            WHERE refCourseTypeID=$CourseTypeID

            ) AS tCTUC
            GROUP BY UserCategoryID, strUserCategory
            ORDER BY strUserCategory
            ";

      $this->ListSQL($sql, 0);

      foreach ($this->Data as $i => $row)
      {
         $this->Data[$i]["Select"] = "<input type=checkbox name=blnCTUCSelected[". $row["UserCategoryID"] ."] id=blnCTUCSelected value=1 ". ($row["Select"] == 1 ? "checked":"") ." />";
      }

      $this->Columns["Select"]->html->width = "5% ";
      $this->Columns["Select"]->html->align = "center";
      unset($this->Columns["UserCategoryID"]);

      return $this->renderTable("CTUC");
   }

   public function getList($frCourseTypeID=0, $frLearnerID=0, $blnEnableFiltering=1)
   {
      global $SystemSettings, $xdb;
//vd($frCourseTypeID);
      if($frCourseTypeID != 0)
         $where = " AND refCourseTypeID = ". $xdb->qs($frCourseTypeID);

      if($frLearnerID != 0)
         $where = " AND refLearnerID = ". $xdb->qs($frLearnerID);

      $this->ListSQL($this->getListSQL(null, $where, $blnEnableFiltering) , 0,"course.php");
      return $this->renderTable("All Courses");
   }

   public function getListCurrent()
   {
      global $SystemSettings;

      $dt = date("Y-m-d");

      //20190801 - LOOK INTO GIVING USER ACCESS TO ONLY 1 COURSE - JACQUES
      //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

      if($_SESSION[USER]->SECURITYGROUPID == 13)
      { 
         $this->ListSQL($this->getListSQL(" AND CourseID = 477 AND dtStartDate <= '$dt' AND dtEndDate >= '$dt'"),0, $this->controler);
      }
      elseif($_SESSION[USER]->SECURITYGROUPID == 14)
      { 
         $this->ListSQL($this->getListSQL(" AND CourseID = -533 AND dtStartDate <= '$dt' AND dtEndDate >= '$dt'"),0, $this->controler);
      }
      else
      {
         $this->ListSQL($this->getListSQL(" AND dtStartDate <= '$dt' AND dtEndDate >= '$dt'"),0, $this->controler);
      }

      //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

      // $this->ListSQL($this->getListSQL(" AND dtStartDate <= '$dt' AND dtEndDate >= '$dt'"),0, $this->controler);
      return $this->renderTable("Current Courses");
   }
   public function getListPast()
   {
      global $SystemSettings;

      $dt = date("Y-m-d");

      //20190801 - LOOK INTO GIVING USER ACCESS TO ONLY 1 COURSE - JACQUES
      //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

      if($_SESSION[USER]->SECURITYGROUPID == 13)
      { 
         $this->ListSQL($this->getListSQL(" AND CourseID = 477 AND dtEndDate < '$dt'"),0, $this->controler);
      }
      elseif($_SESSION[USER]->SECURITYGROUPID == 14)
      { 
         $this->ListSQL($this->getListSQL(" AND CourseID = -533 AND dtEndDate < '$dt'"),0, $this->controler);
      }
      else
      {
         $this->ListSQL($this->getListSQL(" AND dtEndDate < '$dt'"),0, $this->controler);
      }

      //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

      // $this->ListSQL($this->getListSQL(" AND dtEndDate < '$dt'"),0, $this->controler);
      return $this->renderTable("Past Courses");
   }
   public function getListFuture()
   {
      global $SystemSettings;

      $dt = date("Y-m-d");

      //20190801 - LOOK INTO GIVING USER ACCESS TO ONLY 1 COURSE - JACQUES
      //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

      if($_SESSION[USER]->SECURITYGROUPID == 13)
      { 
         $this->ListSQL($this->getListSQL(" AND CourseID = 477 AND dtStartDate > '$dt'"),0, $this->controler);
      }
      elseif($_SESSION[USER]->SECURITYGROUPID == 14)
      { 
         $this->ListSQL($this->getListSQL(" AND CourseID = -533 AND dtStartDate > '$dt'"),0, $this->controler);
      }
      else
      {
         $this->ListSQL($this->getListSQL(" AND dtStartDate > '$dt'"),0, $this->controler);
      }

      //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

      // $this->ListSQL($this->getListSQL(" AND dtStartDate > '$dt'"),0, $this->controler);
      return $this->renderTable("Future Courses");
   }

   //2013-09-03 getLearnerMove() uses the currentCourseID and Course type as arguments and builds a small container under learner list
   //on the course details page with a submit button and a dropdown list populated by course names of all courses that have the same course type
   //as the current course but is not the current course and it's end date is not earlier then today. - christiaan
   public static function getLearnerCopy($CurrentCourseID, $CourseTypeID)
   {
      global $xdb, $SystemSettings, $DT;

      //if($CourseTypeID != 7)// 7=OMW
       //  $where .= "AND refCourseTypeID = $CourseTypeID";

      // $rst = $xdb->doQuery("SELECT CourseID, strCourse ,dtStartDate
      //    FROM tblCourse
      //    WHERE dtEndDate >= ".date('Y-m-d')." AND CourseID != $CurrentCourseID AND blnActive = 1 $where
      //    ORDER BY strCourse",0);

      // $spacer = "&nbsp;&nbsp;";

      // $hResult = $xdb->doQuery("
      //    SELECT tblCourseType.strCourseType, tblCourseType.CourseTypeID
      //    FROM tblCourseType INNER JOIN tblCourse ON tblCourseType.CourseTypeID = tblCourse.refCourseTypeID
      //    GROUP BY tblCourseType.strCourseType, tblCourseType.CourseTypeID");


      // $ddlCourseList = "<option value = 0 >- Select -</option>";

      // while($heading = $xdb->fetch_object($hResult))
      // {

      //    if($heading)
      //    {
      //       $ddlCourseList .= "<option value='$heading->CourseTypeID'>- $heading->strCourseType -</option>";

      //       $fResult = $xdb->doQuery("
      //             SELECT tblCourse.CourseID, tblCourse.strCourse, tblCourse.dtStartDate, tblCourseType.strCourseType, tblCourseType.CourseTypeID
      //             FROM tblCourseType INNER JOIN tblCourse ON tblCourseType.CourseTypeID = tblCourse.refCourseTypeID
      //             WHERE tblCourse.dtEndDate >= ".date('Y-m-d')." AND tblCourse.CourseID != $CurrentCourseID AND tblCourse.blnActive = 1 AND tblCourseType.CourseTypeID = $heading->CourseTypeID
      //             GROUP BY tblCourseType.strCourseType, tblCourse.strCourse, tblCourse.dtStartDate");

      //       while($field = $xdb->fetch_object($fResult))
      //       {
      //          if($field)
      //          {
      //             $ddlCourseList .= "<option value='$field->CourseID'>$spacer$field->strCourse - $field->dtStartDate </option>";

      //          }
      //       }
      //    }

      // }

      $rst = $xdb->doQuery("
         SELECT tblCourseType.strCourseType, tblCourse.CourseID, tblCourse.strCourseHTML, tblCourse.dtStartDate
         FROM tblCourseType INNER JOIN tblCourse ON tblCourseType.CourseTypeID = tblCourse.refCourseTypeID
         WHERE (((tblCourse.blnActive)=1) AND ((tblCourseType.blnActive)=1)) AND tblCourse.CourseID != $CurrentCourseID
         ORDER BY tblCourseType.strCourseType, tblCourse.strCourseHTML, tblCourse.dtStartDate");

            $currentCourseType = "";

            $ddlCourseList = "<option value = 0 >- Select -</option>";

            while($row = $xdb->fetch_object($rst))
            {
               //init
               if($currentCourseType != $row->strCourseType)
               {
                  if($currentCourseType != "")
                  {
                     $ddlCourseList .="</optgroup>";
                  }
                  $ddlCourseList .="<optgroup label='$row->strCourseType'>";

               }


               //processing
                  $ddlCourseList .= "<option value='$row->CourseID'>$row->strCourseHTML - $row->dtStartDate</option>";

               //post

               $currentCourseType = $row->strCourseType;
            }


      $strOutput = "
        <table width='100%' cellspacing='1' cellpadding='2' border='0'>
               <caption>Copy Learners</caption>
               <tr>
                  <td align='right'>
                     Select course to copy Learner(s) to:
                     <select name='newCourseID' id='newCourseID' class='controlText controlWide'>
                        $ddlCourseList
                        </optgroup>
                     </select>
                     <input type='submit' name='Action' id='btnMoveLearnerCourse' class='btn' value ='Copy Learners' onClick= &quot if(confirm(\'Are you sure you want to Copy the selected Learners?\'){return true;}else{return false;}; &quot>
                  </td>
               </tr>
         </table>"
         .js("");

      return $strOutput;
      //return $this->renderTable("Venue");
   }

   //20181114 - Added AML Addition Manual Import - Rachel
   public static function getNewLearnerSetup($strCourseCode)
   {
      global $SystemSettings,$ldb,$xdb, $arrSys, $BR, $TR, $SP, $HR, $PHP_SELF, $DATABASE_SETTINGS, $DT, $dt;


      $thHeadings = "<tr>
                        <th align='center' style='width: 60px;' rowspan='100%'><img src='images/add.png' width='24px;'/></th>
                        <th style=''>Name</th>
                        <th style='width: 150px' nowrap >Surname</th>
                        <th style='width: 150px' nowrap >Email</th>
                        <th> </th>
                     </tr>";
      
      //go

      // blank row template

      $Add .= "<tr class='itemRowNewLearner' id='extraRowNewLearner' >
                  <td align='left' style='width: 150px'><input type='text' id='strName' name='strName' value='' class='controlText' style='width:95%;'></td>
                  <td align='left' style='width: 150px' ><input type='text' id='strSurname' name='strSurname' value='' class='controlText' style='width:95%;'></td>
                  <td align='left' style='width: 150px' ><input type='text' id='strEmail' name='strEmail' value='' class='controlText' style='width:95%;'></td>
                  <td style='width: 150px'> <input type='submit' name='Action' id='btnAddLearner' class='btn' style='width:100%;' value ='Add Learner' tag='input' onclick='return jsValidateLearner();'></td>
               </tr>";

      return " <div >         
                  <table cellpadding=2 cellspacing=1 border=0 class='tblNemoDetails' style='width: 100%; margin: 0px;'>
                     <caption>Add Learner</caption>
                     $thHeadings
                     $trCS
                     $Add
                  </table>
               </div>

               ".js("

                  //Validates Required fields
                  function jsValidateLearner()
                  {
                     var msg = '';

                     if($('#strName').val() == '')
                     {
                        msg += '\\nName';
                     } 

                     if($('#strSurname').val() == '')
                     {
                        msg += '\\nSurname';
                     }

                     if($('#strEmail').val() == '')
                     {
                        msg += '\\nEmail';
                     }

                     if(msg != '')
                     {
                        alert('Please complete all the required fields: \\n' + msg);
                        return false;
                     }
                     else{
                        return true;
                     }
                  }


                  ");
   }

   //20181114 - Added AML Addition Manual Import - Rachel
   public static function AddNewLearnerAML(&$CourseID)
   {
      global $xdb, $SystemSettings;

      $row = $xdb->getRowSQL("SELECT strCourseCode FROM tblCourse WHERE CourseID =".$xdb->qs($CourseID)." ", 0);

      $db = new NemoDatabase("tmpLearnerAML", 0, null, 0);

      $db->Fields[strName] = $_POST["strName"];
      $db->Fields[strSurname] = $_POST["strSurname"];
      $db->Fields[strEmail] = $_POST["strEmail"];
      $db->Fields[strCourseCode1] = $row->strCourseCode;
      $db->Fields[strCourseCode2] = "NULL";
      $db->Fields[strCourseCode3] = "NULL";
      $db->Fields[blnProcessed] = 0;

      $result = $db->Save();

      if($result->Error == 1)
         return $result->Message;
      else{
         //Process learners
         //return ajax call to cron.daily and ignore prints
         $jsProcessAMLLearners = js("

               var strAction = 'Process AML Learners';
               $.ajax(
                     {
                        type: 'GET',
                        url: 'cron.daily.php',
                        data: 'Action='+ strAction,
                        success: function(data)
                        {
                           //alert('Worked');
                           //alert(this.url);
                           //do nothing
                        }
                     });");

         return "Learner Added. ".$jsProcessAMLLearners;
      }
   }


   public static function AddNewLearnerIBC(&$CourseID)
   {
      global $xdb, $SystemSettings;

      $row = $xdb->getRowSQL("SELECT strCourseCode FROM tblCourse WHERE CourseID =".$xdb->qs($CourseID)." ", 0);

      $db = new NemoDatabase("tmpLearnerIBC", 0, null, 0);

      $db->Fields[strName] = $_POST["strName"];
      $db->Fields[strSurname] = $_POST["strSurname"];
      $db->Fields[strEmail] = $_POST["strEmail"];
      $db->Fields[strCourseCode1] = $row->strCourseCode;
      $db->Fields[blnProcessed] = 0;

      $result = $db->Save();

      if($result->Error == 1)
         return $result->Message;
      else{
         //Process learners
         //return ajax call to cron.daily and ignore prints
         $jsProcessIBCLearners = js("

               var strAction = 'Process IBC Learners';
               $.ajax(
                     {
                        type: 'GET',
                        url: 'cron.daily.php',
                        data: 'Action='+ strAction,
                        success: function(data)
                        {
                           //alert('Worked');
                           //alert(this.url);
                           //do nothing
                        }
                     });");

         return "Learner Added. ".$jsProcessIBCLearners;
      }
   }

   //20190830 - Manually Add Learners for all other courses (Non AML and IBC Courses) - Rachel
   public static function AddNewLearner(&$CourseID, $strEmailTemplate = "Register")
   {
      global $xdb, $SystemSettings, $DT;

      //print_rr($_POST);

      //Get all temporary learners
      //$rstTmpLearner = $xdb->doQuery("SELECT * FROM tmpLearnerAML WHERE blnProcessed = 0", 1);


      //Check if learner already exists

      $rowLearner = $xdb->getRowSQL("SELECT * FROM tblLearner WHERE strEmail like TRIM(". $xdb->qs($_POST["strEmail"]).")", 0);
      $password = "<i>Please use your existing Password alternatively make use of the \"Forgot Password\" button</i>";
      $LearnerID = $rowLearner->LearnerID;

      
      //process
      //if learner email DNE in tblLearner, i.e learner is new, create Learner + Password and return LearnerID
      if(!$rowLearner) 
      {
         //Create Learner
         $xdb->doQuery("
            INSERT INTO tblLearner (strLearner
                  , strName, strSurname
                  , strDisplayName, strEmail
                  , dtRegistered, strLastUser )
         VALUES ( CONCAT(TRIM(".$xdb->qs($_POST["strSurname"])."), ', ', TRIM(".$xdb->qs($_POST["strName"])."), ' (' , TRIM(".$xdb->qs($_POST["strName"])."), ')' )
                  , TRIM(".$xdb->qs($_POST["strName"])."), TRIM(".$xdb->qs($_POST["strSurname"]).")
                  , TRIM(".$xdb->qs($_POST["strName"])."), TRIM(".$xdb->qs($_POST["strEmail"]).")
                  , NOW(), 'Add Course Learners Manually')", 0);

         //Get New LearnerID
         $LearnerID = $xdb->getLastID();

         //Create Password
         $np = new NemoPassword();
         $password = Obfuscate().date("Ymd");
         $np->createPassword($password);
         $np->savePassword("Learner", $LearnerID, date("Y-m-d"), 0);
      } //eoIfLearner

         $idb = new NemoDatabase("tblInvoice", 0, null, 0);
         $UID = Obfuscate();

         $idb->Fields[strInvoiceNumber] = $UID;
         $idb->Fields[refLearnerID] = $LearnerID;
         $idb->Fields[refClientID] = "-1";
         $idb->Fields[refPracticeID] = "NULL";
         $idb->Fields[TransactionID] = 0;
         $idb->Fields[dtInvoiceDate] = $DT;
         $idb->Fields[blnTermsAndConditions] = 1;
         $idb->Fields[blnElectronicInvoices] = 1;
         $idb->Fields[strPaymentMethod] = "Internal";
         $idb->Fields[blnLocked] = 0;
         $idb->Fields[blnActive] = 1;
         $idb->Fields[strFirstUser] = "Purchase Process EFT";
         $idb->Fields[dtFirstEdit] = $dt;
         $idb->Fields[strLastUser] = "Purchase Process EFT";

         $rstInvoice = $idb->Save(0, 0);

      //Set LicenseID 
      $rowCourse = $xdb->getRowSQL("SELECT *, tblCourse.dblCost as dblCost FROM tblCourse INNER JOIN tblCourseType ON CourseTypeID = refCourseTypeID WHERE CourseID = ". $xdb->qs($_POST["CourseID"]),0);

      $LicenseID = $rowCourse->strCourseTypeCode ."PVT". Obfuscate();

      //Assign Learner to course
      $xdb->doQuery("
         INSERT INTO tblLicence (LicenceID, refCourseID, refLearnerID, refInvoiceID, strStatus, strFirstUser, dtFirstEdit, strLastUser)
         VALUES('$LicenseID', $CourseID, $LearnerID, ".$idb->InvoiceID.", 'Active',  'Add Course Learners Manually', NOW(), 'Add Course Learners Manually') ", 0);

      //Assumption: NO REGISTRATION ORDER EMAIL REQUIRED.The assumption is that the learner has already paid.

      $BASE_URL = str_replace("/webadmin", "", $SystemSettings[BASE_URL]);

      //Send Registration Email
      $row = $xdb->getRowSQL("SELECT * FROM tblLearner WHERE LearnerID = ". $LearnerID, 0);
      $fields[DisplayName] = $row->strDisplayName;
      $fields[Email] = $row->strEmail;
      $fields[Password] = $password;
      $fields[strEmail] = $row->strEmail;
      $fields[Course] = $_POST["strCourse"];
      $fields[link] = $BASE_URL;
      //print_rr($fields);

      $Nemail = new NemoEmail($fields[strEmail] , "" , 0);
      $Nemail->LoadEmailTemplate($strEmailTemplate);

      //20150713 -Moved substituted custom Logo's outside of nemo.email class - Christiaan
      $fields[LogoPFI] = "<a href='".$BASE_URL."index.php"."'><img src='".$BASE_URL.$SystemSettings[EmailLogoPFI]."' ></a>";
      $fields[InviteHeader] = "<img src='".$BASE_URL.$SystemSettings[EmailLogoInvite]."' >";

      $Nemail->Substitute($fields);

      $Nemail->addHeader("FROM", $SystemSettings["SMTP Send As"]);
      $Nemail->From = $SystemSettings["SMTP Send As"];
      //$Nemail->addHeader("BCC", $page->SystemSettings["SMTP BCC"]);
      //$Nemail->Bcc = $page->SystemSettings["SMTP BCC"];

      $Nemail->arrFields[txtNotes] = "Add Course Learners Manually";

      $result = $Nemail->Send(); //print_rr($Nemail); die("lknsfdfjhh");

      if($result){
         return "Learner Added.";
      }else{
         return "Learner failed to add. Please check if the email is correct.";
      }

   }


   public static function getCourseVenue($CourseID)
   {
      global $xdb, $SystemSettings, $DT;

      // $rowCourseVenue = $xdb->getRowSQL("SELECT tblCourseVenue.*, tblVenue.intMaxCapacity
      //                                        FROM tblCourseVenue INNER JOIN tblVenue ON tblCourseVenue.refVenueID = tblVenue.VenueID
      //                                        WHERE tblCourseVenue.refCourseID=$CourseID",0);
      $rowCourseVenue = $xdb->getRowSQL("SELECT * FROM tblCourseVenue WHERE refCourseID=$CourseID",0);
      $rowCourse = $xdb->getRowSQL("SELECT * FROM tblCourse WHERE CourseID = $CourseID");

      $rst = $xdb->doQuery("SELECT tblVenue.* FROM tblVenue Where blnActive = 1 ORDER BY strVenue");

      while($row = $xdb->fetch_object($rst))
      {
         //ini
         $strCourseVenue = "";
         $disabled = "";
         $venueNotes ="";
         //$courseVenue ='('.$rowCourseVenue->strCourse.': '.$rowCourseVenue->dtStartDate.' --> '.$rowCourseVenue->dtEndDate.')';
         //print_rr($courseVenue);

         //process
         $rowCV = $xdb->getRowSQL("SELECT tblCourse.*
                                    FROM tblCourseVenue INNER JOIN tblCourse on tblCourseVenue.refCourseID = tblCourse.CourseID
                                    WHERE tblCourseVenue.refVenueID = $row->VenueID AND dtStartDate <= '$rowCourse->dtStartDate' AND '$rowCourse->dtEndDate' <= dtEndDate");

         if($rowCV && $rowCV->CourseID != $CourseID)
         {//disabled!
            $disabled = "disabled";
            $strCourseVenue = " ($rowCV->strCourse: $rowCV->dtStartDate > $rowCV->dtEndDate)";     //strCourse or strCourseCode??
         }
         if($row->txtNotes != "")
         {
            $venueNotes = ' ( '.$row->txtNotes.' )';
         }
         $ddlVenue .= "<option value='$row->VenueID' ".($row->VenueID == $rowCourseVenue->refVenueID ? "Selected" : "")." $disabled >$row->strVenue$strCourseVenue$venueNotes</option>";
         //print_rr($rowCV->strCourse);
      }

      $strOutput = "
        <table width='100%' cellspacing='1' cellpadding='2' border='0'>
            <caption>Course Venue</caption>
               <tr>
                  <td class='tdDetailsLeft' align='right'>Venue :</td>
                  <td class='tdDetailsRight' align='left'>
                     <select name='refVenueID' id='refVenueID' onChange='jsGetMaxCapacity(this.value);' class='controlText'>
                        <option value='0'>- None -</option>
                           $ddlVenue
                     </select>
                  </td>
               </tr>
               <tr>
                  <td class='tdDetailsLeft' align='right'>Capacity: </td>
                  <td class='tdDetailsRight' align='left'>
                     <input type = 'text' name='intCapacity' id='intCapacity' value=\"$rowCourseVenue->intCapacity\" class='controlText controlNumeric' onBlur='removeAlpha(this);'>
                  </td>
               </tr>
         </table>"
         .js("
            function jsGetMaxCapacity(VID)
            {
               $('#intCapacity').hide('fast');

               $.ajax(
               {
                  type: 'POST',
                  url: 'ajaxfunctions.php',
                  data: 'header=text&type=getMaxCapacity&VenueID=' + VID,
                  success: function(data)
                  {
                     //$('#intCapacity').value = data;
                     d('intCapacity').value = data;
                  }
               });
               $('#intCapacity').show('fast');
            }");

      return $strOutput;
      //return $this->renderTable("Venue");
   }

     //2013-10-02 Just copies only the learner information and DOES NOT send an email - christiaan
   public static function BasicCopyLearnerCourse($newCourseID, $CurrentCourseID, $LearnerID)
   {
      global $xdb, $SystemSettings, $DT, $BR;
      $copyCount = 0;
      $errorMsg = "";

      $rowLearner = $xdb->getRowSQL("SELECT * FROM tblLearner WHERE LearnerID=$LearnerID");
      if($rowLearner)
      {
         $rowCourse = $xdb->getRowSQL("
            SELECT tblCourse.* , tblVenue.strVenue, tblVenue.txtAddress
            FROM tblCourse
            LEFT JOIN tblCourseVenue ON tblCourse.CourseId = tblCourseVenue.refCourseID
            LEFT JOIN tblVenue ON tblVenue.VenueID = tblCourseVenue.refVenueID
            WHERE tblCourse.CourseID=$newCourseID",0);
         if($rowCourse)
         {
            //2013-08-29 build email & send
            $nemoEmail = new NemoEmail("" , "" , 0);

            $nemoEmail->LoadEmailTemplate(getCourseTypeEmailTemplate("Course Start", "Course Start", $rowCourse->refCourseTypeID));

            $arrValues[DisplayName] = $rowLearner->strDisplayName;
            $arrValues[Email] = "";
            $arrValues[Password] = $rowLearner->strPassword;
            $arrValues[Course] = "$rowCourse->strCourse [$rowCourse->strCourseCode]";
            $arrValues[StartDate] = $rowCourse->dtStartDate;
            $arrValues[StartTime] = $rowCourse->strStartTime;

            if($rowCourse->strVenue == "")
               $rowCourse->strVenue = "n/a";

            $arrValues[Venue] = "$rowCourse->strVenue$BR". mynl2br($rowCourse->txtAddress);
            $nemoEmail->Substitute($arrValues);

            $nemoEmail->addHeader("FROM", $SystemSettings["SMTP Send As"]);
            $nemoEmail->addHeader("BCC", $SystemSettings["SMTP BCC"]);
            $nemoEmail->Bcc = $SystemSettings["SMTP BCC"];
            $nemoEmail->From = $SystemSettings["SMTP Send As"];
            //print_rr($nemoEmail); die;
            $nemoEmail->Send();

            //copy licence records
             $xdb->doQuery("
               INSERT IGNORE INTO tblLicence ( LicenceID, refCourseID, refLearnerID, refInvoiceID, strStatus, dblAmountExcl, dblAmountIncl, dtDateIssued, dtDateActivated, dtDateExpiry, strFirstUser, dtFirstEdit, strLastUser )
               SELECT concat(left(tblLicence.LicenceID,6),'". $nemoEmail->UID ."') as LicenceID, $newCourseID as refCourseID, tblLicence.refLearnerID, tblLicence.refInvoiceID, 'Active' AS strStatus, tblLicence.dblAmountExcl, tblLicence.dblAmountIncl, tblLicence.dtDateIssued, tblLicence.dtDateActivated, tblLicence.dtDateExpiry, tblLicence.strFirstUser, tblLicence.dtFirstEdit, 'Learner Move' AS strLastUser
               FROM tblLicence
               WHERE (((tblLicence.refLearnerID)=$LearnerID) AND ((tblLicence.refCourseID)=$CurrentCourseID))
               ", 0);

            return "Learner copied. ";

         }
         else
         {
            return "No course found for courseID $newCourseID. ";
         }
      }
      else
      {
         return "No Learners found for learnerID $LearnerID. ";
      }

   }

   //2013-10-02 CopyLearnerCourse():  Copy all learner Assessment, Milestones and Responce records to new course
   public static function CopyLearnerCourse($newCourseID, $CurrentCourseID, $arrLearner)
   {
      global $xdb, $MYSQLI, $SystemSettings, $DT, $BR;
      $copyCount = 0;
      $errorMsg = "";
      if(is_array($arrLearner))
      {
         $LearnerIDs = implode(", ", array_keys($arrLearner));

         //2013-10-01 Get all list of ModuleIDs-TO/FROM & AssignmentIDs-To/FROM linked on refCTMID
         $rst = $xdb->doQuery("
            SELECT modModule.ModuleID as oldModuleID, modModule_1.ModuleID as newModuleID, modAssignment.AssignmentID AS oldAssignmentID, modAssignment_1.AssignmentID As newAssignmentID, modModule.refCourseID, modModule_1.refCourseID, modAssignment.strType
            FROM (modModule INNER JOIN modModule AS modModule_1 ON modModule.refCTMID = modModule_1.refCTMID) INNER JOIN (modAssignment INNER JOIN modAssignment AS modAssignment_1 ON modAssignment.strAssignment = modAssignment_1.strAssignment) ON (modModule.ModuleID = modAssignment.refModuleID) AND (modModule_1.ModuleID = modAssignment_1.refModuleID)
            WHERE (((modModule.refCourseID)=$CurrentCourseID) AND ((modModule_1.refCourseID)=$newCourseID) AND ((modAssignment.strType)='Assignment'));
            ",0);

         //2013-10-11 if there is no results, try doing the join on strModuleName -christiaan
         if($xdb->num_rows($rst) == 0)
         {
            $rst = $xdb->doQuery("
               SELECT modModule.ModuleID as oldModuleID, modModule_1.ModuleID as newModuleID, modAssignment.AssignmentID AS oldAssignmentID, modAssignment_1.AssignmentID As newAssignmentID, modModule.refCourseID, modModule_1.refCourseID, modAssignment.strType
               FROM modModule AS modModule_1 INNER JOIN (modModule INNER JOIN (modAssignment INNER JOIN modAssignment AS modAssignment_1 ON modAssignment.strAssignment = modAssignment_1.strAssignment) ON modModule.ModuleID = modAssignment.refModuleID) ON (modModule.strModuleName = modModule_1.strModuleName) AND (modModule_1.ModuleID = modAssignment_1.refModuleID)
               WHERE (((modModule.refCourseID)=$CurrentCourseID) AND ((modModule_1.refCourseID)=$newCourseID) AND ((modAssignment.strType)='Assignment'));
               ",0);
         }

         while($row = $xdb->fetch_object($rst))
         {//print_rr($row);



            // 2013-10-01 Copy Assessments
               $xdb->doQuery("
               INSERT IGNORE INTO modAssessment ( refModuleID, refLearnerID, refAssignmentID, dblAssignmentMark, percAssignmentMark, txtComments, txtNotes, strFilename, dtUpload, dtAssessment, strLastUser )
               SELECT ".$row->newModuleID." AS refModuleID, modAssessment.refLearnerID, '".$row->newAssignmentID."' AS refAssignmentID, modAssessment.dblAssignmentMark, modAssessment.percAssignmentMark, modAssessment.txtComments, modAssessment.txtNotes, modAssessment.strFilename, modAssessment.dtUpload, modAssessment.dtAssessment, 'Learner Move' as strLastUser
               FROM modAssessment
               WHERE (((modAssessment.refLearnerID) In ($LearnerIDs)) AND ((modAssessment.refAssignmentID)='".$row->oldAssignmentID."'));
               ",0);

            // 2013-10-01 Copy Milestones
               $xdb->doQuery("
               INSERT IGNORE INTO modMilestone ( UniqueID, refModuleID, refLearnerID, strType, strStatus, strLastUser  )
               SELECT '".$row->newAssignmentID."' AS UniqueID, ".$row->newModuleID." AS refModuleID, modMilestone.refLearnerID, modMilestone.strType, modMilestone.strStatus , 'Learner Move' as strLastUser
               FROM modMilestone
               WHERE (((modMilestone.refLearnerID) In ($LearnerIDs)) AND ((modMilestone.UniqueID)='".$row->oldAssignmentID."'));
               ", 0);

            // 2013-10-02 Get Learner OptionID and QuestionID for their oldAssignmentID and insert in the newAssignmentID - Christiaan
               $xdb->doQuery("
               INSERT IGNORE INTO surResponse ( AssignmentID, LearnerID, QuestionID, OptionID, response, txtComment )
               SELECT modAssignment_1.AssignmentID , surResponse.LearnerID, surQuestion_1.QuestionID, surOption_1.OptionID, surResponse.response, surResponse.txtComment
               FROM (surOption INNER JOIN (surQuestion INNER JOIN (surResponse INNER JOIN modAssignment ON surResponse.AssignmentID = modAssignment.AssignmentID) ON surQuestion.refAssignmentID = modAssignment.AssignmentID) ON (surOption.refQuestionID = surQuestion.QuestionID) AND (surOption.OptionID = surResponse.OptionID)) INNER JOIN (surOption AS surOption_1 INNER JOIN (surQuestion AS surQuestion_1 INNER JOIN modAssignment AS modAssignment_1 ON surQuestion_1.refAssignmentID = modAssignment_1.AssignmentID) ON surOption_1.refQuestionID = surQuestion_1.QuestionID) ON (surQuestion.strQuestion = surQuestion_1.strQuestion) AND (surQuestion.intOrder = surQuestion_1.intOrder) AND (surResponse.response = surOption_1.strOption)
               WHERE (((modAssignment.AssignmentID)='".$row->oldAssignmentID."') AND ((modAssignment_1.AssignmentID)='".$row->newAssignmentID."') AND ((surResponse.LearnerID) In ($LearnerIDs)))
               GROUP BY modAssignment_1.AssignmentID, surResponse.LearnerID, surQuestion_1.QuestionID, surOption_1.OptionID, surResponse.response ;
               ", 0);

         }

         foreach($arrLearner as $LearnerID => $value)
         {

            $rowLearner = $xdb->getRowSQL("SELECT * FROM tblLearner WHERE LearnerID=$LearnerID");
            $rowCourse = $xdb->getRowSQL("
               SELECT tblCourse.* , tblVenue.strVenue, tblVenue.txtAddress
               FROM tblCourse
               LEFT JOIN tblCourseVenue ON tblCourse.CourseId = tblCourseVenue.refCourseID
               LEFT JOIN tblVenue ON tblVenue.VenueID = tblCourseVenue.refVenueID
               WHERE tblCourse.CourseID=$newCourseID",0);

            //2013-08-29 build email & send
            $nemoEmail = new NemoEmail($rowLearner->strEmail , "" , 0);

            $nemoEmail->LoadEmailTemplate(getCourseTypeEmailTemplate("Course Start", "Course Start", $rowCourse->refCourseTypeID));


            $arrValues[DisplayName] = $rowLearner->strDisplayName;
            $arrValues[Email] = $rowLearner->strEmail;
            $arrValues[Password] = $rowLearner->strPassword;
            $arrValues[Course] = "$rowCourse->strCourse [$rowCourse->strCourseCode]";
            $arrValues[StartDate] = $rowCourse->dtStartDate;
            $arrValues[StartTime] = $rowCourse->strStartTime;

            if($rowCourse->strVenue == "")
               $rowCourse->strVenue = "n/a";

            $arrValues[Venue] = "$rowCourse->strVenue$BR". mynl2br($rowCourse->txtAddress);
            $nemoEmail->Substitute($arrValues);

            $nemoEmail->addHeader("FROM", $SystemSettings["SMTP Send As"]);
            $nemoEmail->addHeader("BCC", $SystemSettings["SMTP BCC"]);
            $nemoEmail->Bcc = $SystemSettings["SMTP BCC"];
            $nemoEmail->From = $SystemSettings["SMTP Send As"];
            //print_rr($nemoEmail); die;
            $nemoEmail->Send();

            //copy licence records
             $xdb->doQuery("
               INSERT IGNORE INTO tblLicence ( LicenceID, refCourseID, refLearnerID, refInvoiceID, strStatus, dblAmountExcl, dblAmountIncl, dtDateIssued, dtDateActivated, dtDateExpiry, strFirstUser, dtFirstEdit, strLastUser )
               SELECT concat(left(tblLicence.LicenceID,6),'". $nemoEmail->UID ."') as LicenceID, $newCourseID as refCourseID, tblLicence.refLearnerID, tblLicence.refInvoiceID, 'Active' AS strStatus, tblLicence.dblAmountExcl, tblLicence.dblAmountIncl, tblLicence.dtDateIssued, tblLicence.dtDateActivated, tblLicence.dtDateExpiry, tblLicence.strFirstUser, tblLicence.dtFirstEdit, 'Learner Move' AS strLastUser
               FROM tblLicence
               WHERE (((tblLicence.refLearnerID)=$LearnerID) AND ((tblLicence.refCourseID)=$CurrentCourseID))
               ", 0);

            //2013-10-3 Code to set original licence to REVOKED -christiaan
            //$xdb->doQuery("UPDATE tblLicence SET strStatus = 'Revoked' WHERE refLearnerID = $LearnerID AND refCourseID = $CurrentCourseID",0);


            $copyCount++;


         }

         return "$copyCount Learner(s) copied. ";
      }
      else
      {
         return "No Learners selected. ";
      }

   }


   public static function SaveWI(&$CourseID)
   {
      global $xdb, $MYSQLI, $SystemSettings;

//ini
      $REFERENCE_INCLUDE = true;
      include_once("ajaxfunctions.php");
      //print_rr($_POST);

//go
      $cdb = new NemoDatabase("tblCourse", $CourseID, null, 0);
      $cdb->SetValues($_POST);

      $cdb->Fields["refCourseTypeID"] = -1; //HC
      $cdb->Fields["strCourse"] =
      $cdb->Fields["strCourseHTML"] = $_POST[strAssignment];
      $cdb->Fields["refModuleReleaseMode"] = "Free";
      $cdb->Fields["dblCost"] = 0;
      $cdb->Fields["dtStartDate"] = $_POST[dtReleaseDate];
      $cdb->Fields["dtEndDate"] = null;
      $cdb->Fields["intPassRate"] = 100;
      $cdb->Fields["blnWI"] = 1; //HC
      $cdb->Fields["blnActive"] = ($_POST[blnActive] ? 1:0);
      if($cdb->Fields["strCourseCode"] == "")
         $cdb->Fields["strCourseCode"] = getNextCourseCode($cdb->Fields["refCourseTypeID"], $cdb->Fields["dtStartDate"]); //from ajaxF
      $cdb->Fields["strLastUser"] = $_SESSION['USER']->USERNAME;

      //print_rr($cdb->Fields); die;
      $resultC = $cdb->Save(0,0); //die;

      if($CourseID == 0)
      {
         $CourseID = $cdb->ID[CourseID];

         //INSERT DEFAULT MODULES
         $xdb->doQuery("INSERT INTO modModule ( refCourseID, refCTMID, strModuleName, intModuleNumber, txtIntro, txtOutcome )
                        SELECT '$CourseID' AS refCourseID, tblCourseTypeModule.CourseTypeModuleID, tblCourseTypeModule.strModuleName, tblCourseTypeModule.intModuleNumber, tblCourseTypeModule.txtIntro, tblCourseTypeModule.txtOutcome
                        FROM tblCourseTypeModule
                        WHERE refCourseTypeID = ". $cdb->Fields["refCourseTypeID"],0);
         $ModuleID =
         //$_POST[refModuleID] = mysql_insert_id(); //vd($ModuleID); die;
         $_POST[refModuleID] = $xdb->getLastID();

         //create assignment
         $rowMCCT = $xdb->getRowSQL("SELECT * FROM (modModule INNER JOIN tblCourse ON modModule.refCourseID = tblCourse.CourseID) INNER JOIN tblCourseType ON tblCourse.refCourseTypeID = tblCourseType.CourseTypeID WHERE modModule.ModuleID=". $xdb->qs($ModuleID),0);
         $strUniqueID_Prefix = $rowMCCT->strCourseTypeCode."ASS";
         include_once("includes/assignment.cls.php");
         Assignment::Save($AssignmentID,$strUniqueID_Prefix);
         //vd($AssignmentID);
      }else{
         $ModuleID = $_POST[ModuleID];

         $rowMCCT = $xdb->getRowSQL("SELECT * FROM (modModule INNER JOIN tblCourse ON modModule.refCourseID = tblCourse.CourseID) INNER JOIN tblCourseType ON tblCourse.refCourseTypeID = tblCourseType.CourseTypeID WHERE modModule.ModuleID=". $xdb->qs($ModuleID),0);
         $strUniqueID_Prefix = $rowMCCT->strCourseTypeCode."ASS";
         $AssignmentID = $_POST[AssignmentID];

      }

      unset($_POST[ModuleID]);
      unset($_POST[AssignmentID]); //unset else SetValues() breaks on new records.

      //save module
      $mdb = new NemoDatabase("modModule", $ModuleID, null, 0);
      $mdb->SetValues($_POST);

      $mdb->Fields[strModuleName] = $_POST[strAssignment];
      $mdb->Fields[intModuleNumber] = 1;
      $mdb->Fields[blnActive] = ($_POST[blnActive] ? 1:0);
      $mdb->Fields[strLastUser] = $_SESSION['USER']->USERNAME;

      //print_rr($mdb->Fields);
      $resultM = $mdb->Save(0,0); //die;

      //save assignment

      $rowQ = $xdb->getRowSQL("SELECT COUNT(*) as intQuestions FROM surQuestion WHERE refAssignmentID = '$AssignmentID' ",0);
      $adb = new NemoDatabase("modAssignment", $AssignmentID, null, 0);
      $adb->SetValues($_POST);

      $adb->Fields[strType] = "Assignment";
      $adb->Fields[intMarks] = $rowQ->intQuestions;
      $adb->Fields[dtDueDate] = null;
      $adb->Fields[blnActive] = ($_POST[blnActive] ? 1:0);
      $adb->Fields[strLastUser] = $_SESSION['USER']->USERNAME;

      //print_rr($adb->Fields);
      $resultA = $adb->Save(0,0,$strUniqueID_Prefix);


      //20181106 - Course/CPD - ClassOfBusiness - pj
      if($_POST["chkUpdateFPIRef"] == 1){
         $xdb->doQuery("
            UPDATE tblCPDPoints INNER JOIN tblCourse ON tblCPDPoints.refEventID = tblCourse.CourseID
            SET tblCPDPoints.strFPIReferenceNumber = tblCourse.strFPIReferenceNumber
            , tblCPDPoints.dtLastEdit = tblCPDPoints.dtLastEdit
            WHERE tblCourse.CourseID = ". $xdb->qs($CourseID) ." AND YEAR(dtEventDate) = YEAR(CURDATE())", 0);
      }    

      if($_POST["chkUpdateCOB"] == 1){
         $xdb->doQuery("
            UPDATE tblCPDPoints INNER JOIN tblCourse ON tblCPDPoints.refEventID = tblCourse.CourseID            
            SET tblCPDPoints.strCPDClassOfBusiness = tblCourse.strCPDClassOfBusiness
            , tblCPDPoints.dtLastEdit = tblCPDPoints.dtLastEdit
            WHERE tblCourse.CourseID = ". $xdb->qs($CourseID) ." AND YEAR(dtEventDate) = YEAR(CURDATE())", 0);
      }   

      if($resultC->Error == 1 || $resultM->Error == 1 || $resultA->Error == 1 )
         return $resultC->Message ." ". $resultM->Message ." ". $resultA->Message;
      else
         return "Details Saved. ";

   }

   public static function Save(&$CourseID, $blnWorkshop=0)
   {
      global $xdb, $MYSQLI, $SystemSettings;
      //print_rr($_REQUEST); //die;
      //error_reporting(E_ERROR);
      $db = new NemoDatabase("tblCourse", $CourseID, null, 0);

      $db->SetValues($_POST);

      $db->Fields[strLastUser] = $_SESSION['USER']->USERNAME;

      $db->Fields[blnWorkshop] = $blnWorkshop;

      //20160329 - Force end date to start date depreceated , asked by Alida - Christiaan
      // if($db->Fields[blnWorkshop] == 1)
      // {
      //    $db->Fields[dtEndDate] = $db->Fields[dtStartDate];
      // }
      $result = $db->Save(0,0); //die;

      if($CourseID == 0)
      {
         $CourseID = $db->ID[CourseID];
         //print_rr("refCourseTypeID: ". $_POST[refCourseTypeID]);

         //INSERT DEFAULT MODULES
         $db->doQuery("INSERT INTO modModule ( refCourseID, refCTMID, strModuleName, intModuleNumber, txtIntro, txtOutcome )
                        SELECT '$CourseID' AS refCourseID, tblCourseTypeModule.CourseTypeModuleID, tblCourseTypeModule.strModuleName, tblCourseTypeModule.intModuleNumber, tblCourseTypeModule.txtIntro, tblCourseTypeModule.txtOutcome
                        FROM tblCourseTypeModule
                        WHERE refCourseTypeID = ". $_POST[refCourseTypeID], 0);

         //UPDATE Release dates
         $i = 0;
         $dtRelease = $_POST[dtStartDate];
         $db->doQuery(" SELECT modModule.ModuleID, tblCourseTypeModule.strDefaultReleaseSchedule
                        FROM modModule INNER JOIN tblCourseTypeModule ON modModule.refCTMID = tblCourseTypeModule.CourseTypeModuleID
                        WHERE modModule.refCourseID = $CourseID", 0);

         while($row = $db->fetch())
         {
            $mdb = new NemoDatabase("modModule", $row->ModuleID, null, 0);
            if($i == 0)
               $dtRelease = $_POST["dtStartDate"];
            else
               $dtRelease = date("Y-m-d", strtotime("$dtRelease $row->strDefaultReleaseSchedule"));
            //vd($dtRelease);
            $mdb->Fields[dtReleaseDate] = $dtRelease;
            $mdb->Save(0,0);
            $i++;
         }

         //replicate! copy all module child object from the previous course to the new course
         $row = $db->getRowSQL("SELECT * FROM tblCourse
                                 WHERE CourseID<>$CourseID AND refCourseTypeID=". $_POST["refCourseTypeID"] ."
                                 ORDER BY dtStartDate DESC", 0);
         if($row)
            Course::Replicate($CourseID, $row->CourseID);
      }

      //Save Course venue details
      $intCapacity = $_POST[intCapacity];
      $refVenueID = $_POST[refVenueID];

      if($intCapacity == "")
      {
         $intCapacity = 0;
      }
      //delete cv w cid=cid
      $db->doQuery("DELETE FROM tblCourseVenue WHERE refCourseID = $CourseID");
      //insert
      if($refVenueID > 0)
      {
         $db->doQuery("INSERT INTO tblCourseVenue (refCourseID, refVenueID, intCapacity) VALUES ($CourseID, $refVenueID, $intCapacity)");
      }

      //$db->doQuery("UPDATE tblCourseVenue SET refVenueID = ".$_POST[refVenueID].", intCapacity = ".$_POST[intCapacity]." WHERE refCourseID =$CourseID");

      //20181106 - Course/CPD - ClassOfBusiness - pj
      if($_POST["chkUpdateFPIRef"] == 1){
         $xdb->doQuery("
            UPDATE tblCPDPoints INNER JOIN tblCourse ON tblCPDPoints.refEventID = tblCourse.CourseID
            SET tblCPDPoints.strFPIReferenceNumber = tblCourse.strFPIReferenceNumber
            , tblCPDPoints.dtLastEdit = tblCPDPoints.dtLastEdit
            WHERE tblCourse.CourseID = ". $xdb->qs($CourseID) ." AND YEAR(dtEventDate) = YEAR(CURDATE())", 0);
      }    

      if($_POST["chkUpdateCOB"] == 1){
         $xdb->doQuery("
            UPDATE tblCPDPoints INNER JOIN tblCourse ON tblCPDPoints.refEventID = tblCourse.CourseID            
            SET tblCPDPoints.strCPDClassOfBusiness = tblCourse.strCPDClassOfBusiness
            , tblCPDPoints.dtLastEdit = tblCPDPoints.dtLastEdit
            WHERE tblCourse.CourseID = ". $xdb->qs($CourseID) ." AND YEAR(dtEventDate) = YEAR(CURDATE())", 0);
      }   


      if($result->Error == 1)
         return $result->Message;
      else
         return "Details Saved. ";
   }

   public static function Delete($chkSelect)
   {
      global $xdb;
      //print_rr($chkSelect);
      if(count($chkSelect) > 0){
      foreach($chkSelect as $key => $value)
      {
         $xdb->doQuery("DELETE FROM tblCourse WHERE CourseID = ". $xdb->qs($key));
      }
         return "Records Deleted.";
      }
   }

   public static function Replicate($CourseToID, $CourseFromID)
   {
      global $xdb, $DT, $MYSQLI,$SystemSettings;

   //ini
   //$xdb->Debug=1;
      $rowCT = $xdb->getRowSQL("SELECT * FROM tblCourseType INNER JOIN tblCourse ON refCourseTypeID = CourseTypeID WHERE CourseID = $CourseToID"); //get CT details

      $arrChildren["modAssignment"]->PK = "AssignmentID";
      $arrChildren["modAssignment"]->UID_Prefix = $rowCT->strCourseTypeCode."ASS";
      $arrChildren["modAssignment"]->Unique_Restrition = array("refModuleID","strAssignment");
      $arrChildren["modAssignment"]->DueDate = "+7 Days"; //BR: Assignment due dates = mod.startdate + 7days
      $arrChildren["modNote"]->PK = "NoteID";
      $arrChildren["modNote"]->UID_Prefix = $rowCT->strCourseTypeCode."NOT";
      $arrChildren["modNote"]->Unique_Restrition = array("refModuleID","strNote");
      $arrChildren["modPractical"]->PK = "PracticalID";
      $arrChildren["modPractical"]->UID_Prefix = $rowCT->strCourseTypeCode."PRA";
      $arrChildren["modPractical"]->Unique_Restrition = array("refModuleID","strPractical");
      $arrChildren["modVideo"]->PK = "VideoID";
      $arrChildren["modVideo"]->UID_Prefix = $rowCT->strCourseTypeCode."VID";
      $arrChildren["modVideo"]->Unique_Restrition = array("refModuleID","strVideo");

   //go
      $rstMain = $xdb->doQuery("
         SELECT modTo.ModuleID AS ModuleToID, modFrom.ModuleID as ModuleFromID, modTo.*
         FROM modModule AS modTo INNER JOIN modModule AS modFrom ON modTo.refCTMID = modFrom.refCTMID
         WHERE modTo.refCourseID=$CourseToID AND modFrom.refCourseID=$CourseFromID");
      while($rowModule = $xdb->fetch_object($rstMain))
      {//print_rr($rowModule);
         foreach($arrChildren as $table => $Child)
         {//print_rr($Child);
            $rst = $xdb->doQuery("SELECT * FROM $table WHERE refModuleID = $rowModule->ModuleFromID AND blnActive = 1");
            while($row = $xdb->fetch_object($rst))
            {//print_rr($row);

            //ini
               $UID = $Child->PK;
               $UID = $row->$UID;

               $dbFrom = new NemoDatabase($table, $UID, null, 0);//print_rr($dbFrom->Fields);

               $dbTo = new NemoDatabase($table, "", $Child->Unique_Restrition, 0);

            //go
               $dbTo->Fields = $dbFrom->Fields; //copy

               $dbTo->Fields["$Child->PK"] = ""; //reassign
               $dbTo->Fields["refModuleID"] = $rowModule->ModuleToID;
               $dbTo->Fields["strLastUser"] = "New Course Replication";//print_rr($dbTo->Fields);

               if($Child->DueDate != "" && $dbTo->Fields["dtDueDate"] != "0000-00-00")
               {
                  $dbTo->Fields[dtDueDate] = date("Y-m-d", strtotime("$rowModule->dtReleaseDate $Child->DueDate"));
               }//print_rr($dbTo->Fields); die;


               $newChild = $dbTo->Save(1, 0, $Child->UID_Prefix); //save
               //print_rr($newChild);

            //post
               //add old->new child array for DC!!!
               if($newChild->Error == 0)
                  $arrDC[$UID] = $newChild->ID;

               //add to Assignment array
               if($Child->PK == "AssignmentID")
                  $arrAssignment[$UID] = $newChild->ID;

            }//eoW2
         }//eoF
      }//eoW1

   //post
      //print_rr($arrDC);

      //copy any existing DC records and files
      if(is_array($arrDC)){
      foreach($arrDC as $fromUID => $toUID)
      {
         $row = $xdb->getRowSQL("SELECT *, REPLACE(strFilename, '$fromUID', '$toUID') AS toFilename FROM modDownloadContent WHERE UniqueID = '$fromUID'");
         if($row){
            $xdb->doQuery("
               INSERT INTO modDownloadContent(UniqueID, strFilename, strLastUser)
               VALUES ('$toUID','$row->toFilename','New Course Replication')");
            if(!copy($SystemSettings[DownloadableContentDirAdmin].$row->strFilename, $SystemSettings[DownloadableContentDirAdmin].$row->toFilename))
            {
               //print_rr(error_get_last());
            }
         }
      }}

      //copy assignment questions and options to new assignment
      //$arrAssignment["CHMASS46EEP9"] = "CHMASS93CDGE";
      if(is_array($arrAssignment)){
      foreach($arrAssignment as $fromUID => $toUID)
      {
         $rstQ = $xdb->doQuery("SELECT * FROM surQuestion WHERE refAssignmentID = '$fromUID'");
         while($rowQ = $xdb->fetch_object($rstQ))
         {
            $dbFrom = new NemoDatabase("surQuestion", $rowQ->QuestionID, null, 0);//print_rr($dbFrom->Fields);
            $dbTo = new NemoDatabase("surQuestion", 0, null, 0);
            $dbTo->Fields = $dbFrom->Fields; //copy

            $dbTo->Fields["QuestionID"] = ""; //reassign
            $dbTo->Fields["refAssignmentID"] = $toUID;
            $dbTo->Fields["strLastUser"] = "New Course Replication";

            $newQ = $dbTo->Save(1,0);
            $xdb->doQuery("
               INSERT INTO surOption ( refQuestionID, strOption, intWeighting, intOrder )
               SELECT $newQ->ID AS refQuestionID, strOption, intWeighting, intOrder
               FROM surOption
               WHERE refQuestionID=$rowQ->QuestionID");
         }
      }}

      //copy co-ordinators
      $xdb->doQuery("INSERT INTO tblCourseCoordinator ( refCourseID, refUserID )
         SELECT $CourseToID AS refCourseID, refUserID
         FROM tblCourseCoordinator
         WHERE refCourseID=$CourseFromID");
   }

   public static function ReplicateAssignments($CourseToID, $CourseFromID)
   {//20130806 - replicate PW1 assignments from IW1 cid=68
      global $xdb, $DT, $MYSQLI, $SystemSettings;

   //ini

   //go
      $rstMain = $xdb->doQuery("
         SELECT modModule.refCourseID AS CIDFrom, modModule_1.refCourseID AS CourseID, modAssignment.*, modModule_1.ModuleID AS refModuleID, 1 as blnActive, 'Replicate - PJ' as strLastUser
         FROM modModule AS modModule_1 INNER JOIN (modAssignment INNER JOIN modModule ON modAssignment.refModuleID = modModule.ModuleID) ON modModule_1.strModuleName = modModule.strModuleName
         WHERE modModule.refCourseID=$CourseFromID AND modModule_1.refCourseID IN ($CourseToID)
         ORDER BY modModule.intModuleNumber",0);
      while($rowAss = $xdb->fetch_object($rstMain))
      {  //print_rr($rowAss);
         $adb = new NemoDatabase("modAssignment", null, null);

         $adb->SetValues((array)$rowAss);
         $adb->Fields[blnActive] = 1;

         $result = $adb->Save(0,1, "PC1ASS");

         $arrAssignment[$rowAss->AssignmentID] = $result->ID; //add to arrAss[OldUID] = NewUID

      }//eoW1
     // print_rr($arrAssignment);

      //copy assignment questions and options to new assignment
      //$arrAssignment["CHMASS46EEP9"] = "CHMASS93CDGE";
      if(is_array($arrAssignment)){
      foreach($arrAssignment as $fromUID => $toUID)
      {
         $rstQ = $xdb->doQuery("SELECT * FROM surQuestion WHERE refAssignmentID = '$fromUID'");
         while($rowQ = $xdb->fetch_object($rstQ))
         {
            $dbFrom = new NemoDatabase("surQuestion", $rowQ->QuestionID, null, 0);//print_rr($dbFrom->Fields);
            $dbTo = new NemoDatabase("surQuestion", 0, null, 0);
            $dbTo->Fields = $dbFrom->Fields; //copy

            $dbTo->Fields["QuestionID"] = ""; //reassign
            $dbTo->Fields["refAssignmentID"] = $toUID;
            $dbTo->Fields["strLastUser"] = "New Course Replication";

            $newQ = $dbTo->Save(1,0);
            $xdb->doQuery("
               INSERT INTO surOption ( refQuestionID, strOption, intWeighting, intOrder )
               SELECT $newQ->ID AS refQuestionID, strOption, intWeighting, intOrder
               FROM surOption
               WHERE refQuestionID=$rowQ->QuestionID",0);
         }
      }}
   }

   public static function ReplicateAssignment($CourseToID, $AssignmentIDFrom)
   {//20130806 - replicate PW1 assignments from IW1 cid=68
      global $xdb, $DT, $MYSQLI, $SystemSettings;

   //ini

   //go
      //creates new Assi in CourseTo
      $rstMain = $xdb->doQuery("
         SELECT modModule.refCourseID AS CIDFrom, modModule_1.refCourseID AS CourseID, modAssignment.*, modModule_1.ModuleID AS refModuleID, 1 as blnActive, 'Replicate - PJ' as strLastUser
         FROM modModule AS modModule_1 INNER JOIN (modAssignment INNER JOIN modModule ON modAssignment.refModuleID = modModule.ModuleID) ON modModule_1.strModuleName = modModule.strModuleName
         WHERE AssignmentID = '$AssignmentIDFrom' AND modModule_1.refCourseID IN ($CourseToID)
         ORDER BY modModule.intModuleNumber",0);
      while($rowAss = $xdb->fetch_array($rstMain))
      {
         $adb = new NemoDatabase("modAssignment", null, null);

         $adb->SetValues($rowAss);
         $adb->Fields[blnActive] = 1;

         $result = $adb->Save(0,1, "TCFASS");

         $arrAssignment[$rowAss[AssignmentID]] = $result->ID; //add to arrAss[OldUID] = NewUID

      }//eoW1
      /**/

      //$arrAssignment["OMWASSBHP2G0"] = "PW1ASSCNN2AE";
      //$arrAssignment["PW1ASSCNN2AE"] = "OMWASSBHP2G0"; // lamp

      // $arrAssignment["PW1ASS13266K"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS1870K0"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS1HEDB0"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS29CDD9"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS2EH85A"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS3G1KPP"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS406FBK"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS4K1N10"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS51C758"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS56H1N9"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS65C47A"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS681EBP"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS6D693P"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS7C1BDK"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS7PGGA8"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS8NBNK9"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS90183N"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASS9562GP"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASSA4155K"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASSA6BFA7"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASSBABCC9"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASSBD11GH"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASSCH0PNP"] = "OMWASSBHP2G0";
      // $arrAssignment["PW1ASSCPB926"] = "OMWASSBHP2G0";

//       print_rr($arrAssignment);

      //copy assignment questions and options to new assignment
      //$arrAssignment[$AssignmentIDFrom] = $AssignmentIDTo;
      //print_rr($arrAssignment);
      if(is_array($arrAssignment)){
      foreach($arrAssignment as $fromUID => $toUID)
      {
         $rstQ = $xdb->doQuery("SELECT * FROM surQuestion WHERE refAssignmentID = '$fromUID'",0);
         while($rowQ = $xdb->fetch_object($rstQ))
         {
            $dbFrom = new NemoDatabase("surQuestion", $rowQ->QuestionID, null, 0);//print_rr($dbFrom->Fields);
            $dbTo = new NemoDatabase("surQuestion", 0, null, 0);
            $dbTo->Fields = $dbFrom->Fields; //copy

            $dbTo->Fields["QuestionID"] = ""; //reassign
            $dbTo->Fields["refAssignmentID"] = $toUID;
            $dbTo->Fields["strLastUser"] = "New Course Replication";

            $newQ = $dbTo->Save(1,0);
            //print_rr($newQ);
            $xdb->doQuery("
               INSERT INTO surOption ( refQuestionID, strOption, intWeighting, intOrder )
               SELECT $newQ->ID AS refQuestionID, strOption, intWeighting, intOrder
               FROM surOption
               WHERE refQuestionID=$rowQ->QuestionID",0);
         }
      }}
   }

   public static function ReplicateModule($CourseToID, $CourseFromID, $ModuleFromID, $CTMID="")
   {
      global $xdb, $DT, $MYSQLI, $SystemSettings;

      //ini
$xdb->Debug=1;
      $rowCT = $xdb->getRowSQL("SELECT * FROM tblCourseType INNER JOIN tblCourse ON refCourseTypeID = CourseTypeID WHERE CourseID = $CourseToID"); //get CT details

      $arrChildren["modAssignment"]->PK = "AssignmentID";
      $arrChildren["modAssignment"]->UID_Prefix = $rowCT->strCourseTypeCode."ASS";
      $arrChildren["modAssignment"]->Unique_Restrition = array("refModuleID","strAssignment");
      $arrChildren["modAssignment"]->DueDate = "+7 Days"; //BR: Assignment due dates = mod.startdate + 7days
      $arrChildren["modNote"]->PK = "NoteID";
      $arrChildren["modNote"]->UID_Prefix = $rowCT->strCourseTypeCode."NOT";
      $arrChildren["modNote"]->Unique_Restrition = array("refModuleID","strNote");
      $arrChildren["modPractical"]->PK = "PracticalID";
      $arrChildren["modPractical"]->UID_Prefix = $rowCT->strCourseTypeCode."PRA";
      $arrChildren["modPractical"]->Unique_Restrition = array("refModuleID","strPractical");
      $arrChildren["modVideo"]->PK = "VideoID";
      $arrChildren["modVideo"]->UID_Prefix = $rowCT->strCourseTypeCode."VID";
      $arrChildren["modVideo"]->Unique_Restrition = array("refModuleID","strVideo");

    $rowModFromDetail = $xdb->getRowSQL("SELECT * FROM modModule WHERE ModuleID = $ModuleFromID"); //get ModuleFrom details

   //Create NEW Replicated module
      $dbModule = new NemoDatabase("modModule", 0, null, 0);
      $dbModule->Fields["refCourseID"] = $CourseToID;
      $dbModule->Fields["refCTMID"] = $rowModFromDetail->refCTMID;
      if($CTMID !="")
      {
         $dbModule->Fields["refCTMID"] = $CTMID;
      }
      $dbModule->Fields["strModuleName"] = $rowModFromDetail->strModuleName;
      $dbModule->Fields["intModuleNumber"] = $rowModFromDetail->intModuleNumber;
      $dbModule->Fields["dtReleaseDate"] = $rowModFromDetail->dtReleaseDate;
      $dbModule->Fields["txtIntro"] = $rowModFromDetail->txtIntro;
      $dbModule->Fields["txtOutcome"] = $rowModFromDetail->txtOutcome;
      $dbModule->Fields["txtTimeRequired"] = $rowModFromDetail->txtTimeRequired;
      $dbModule->Fields["blnActive"] = $rowModFromDetail->blnActive;
      $dbModule->Fields["strLastUser"] = $rowModFromDetail->strLastUser;
      $dbModule->Fields["dtLastEdit "] = $rowModFromDetail->dtLastEdit ;
      $result = $dbModule->Save(0,1);

      $ModuleIDTo = $dbModule->ID[ModuleID];

   //go
      $rstMain = $xdb->doQuery("
         SELECT modTo.ModuleID AS ModuleToID, modFrom.ModuleID as ModuleFromID, modTo.*
         FROM modModule AS modTo INNER JOIN modModule AS modFrom ON modTo.refCTMID = modFrom.refCTMID
         WHERE modTo.refCourseID=$CourseToID AND modFrom.refCourseID=$CourseFromID AND modTo.ModuleID=$ModuleIDTo AND modFrom.ModuleID=$ModuleFromID");
      while($rowModule = $xdb->fetch_object($rstMain))
      {//print_rr($rowModule);
         foreach($arrChildren as $table => $Child)
         {//print_rr($Child);
            $rst = $xdb->doQuery("SELECT * FROM $table WHERE refModuleID = $rowModule->ModuleFromID AND blnActive = 1");
            while($row = $xdb->fetch_object($rst))
            {//print_rr($row);

            //ini
               $UID = $Child->PK;
               $UID = $row->$UID;

               $dbFrom = new NemoDatabase($table, $UID, null, 0);//print_rr($dbFrom->Fields);

               $dbTo = new NemoDatabase($table, "", $Child->Unique_Restrition, 0);

            //go
               $dbTo->Fields = $dbFrom->Fields; //copy

               $dbTo->Fields["$Child->PK"] = ""; //reassign
               $dbTo->Fields["refModuleID"] = $rowModule->ModuleToID;
               $dbTo->Fields["strLastUser"] = "New Module Replication";//print_rr($dbTo->Fields);

               if($Child->DueDate != "" && $dbTo->Fields["dtDueDate"] != "0000-00-00")
               {
                  $dbTo->Fields[dtDueDate] = date("Y-m-d", strtotime("$rowModule->dtReleaseDate $Child->DueDate"));
               }//print_rr($dbTo->Fields); die;


               $newChild = $dbTo->Save(1, 0, $Child->UID_Prefix); //save
               //print_rr($newChild);

            //post
               //add old->new child array for DC!!!
               if($newChild->Error == 0)
                  $arrDC[$UID] = $newChild->ID;

               //add to Assignment array
               if($Child->PK == "AssignmentID")
               {
                  $arrAssignment[$UID] = $newChild->ID;
               }

            }//eoW2
         }//eoF
      }//eoW1

   //post
      //print_rr($arrDC);

      //copy any existing DC records and files
      if(is_array($arrDC)){
      foreach($arrDC as $fromUID => $toUID)
      {
         $row = $xdb->getRowSQL("SELECT *, REPLACE(strFilename, '$fromUID', '$toUID') AS toFilename FROM modDownloadContent WHERE UniqueID = '$fromUID'");
         if($row){
            $xdb->doQuery("
               INSERT INTO modDownloadContent(UniqueID, strFilename, strLastUser)
               VALUES ('$toUID','$row->toFilename','New Module Replication')");
            if(!copy($SystemSettings[DownloadableContentDirAdmin].$row->strFilename, $SystemSettings[DownloadableContentDirAdmin].$row->toFilename))
               print_rr(error_get_last());

         }
      }}

      //copy assignment questions and options to new assignment
      //$arrAssignment["CHMASS46EEP9"] = "CHMASS93CDGE";
      if(is_array($arrAssignment)){
      foreach($arrAssignment as $fromUID => $toUID)
      {
         $rstQ = $xdb->doQuery("SELECT * FROM surQuestion WHERE refAssignmentID = '$fromUID'");
         while($rowQ = $xdb->fetch_object($rstQ))
         {
            $dbFrom = new NemoDatabase("surQuestion", $rowQ->QuestionID, null, 0);//print_rr($dbFrom->Fields);
            $dbTo = new NemoDatabase("surQuestion", 0, null, 0);
            $dbTo->Fields = $dbFrom->Fields; //copy

            $dbTo->Fields["QuestionID"] = ""; //reassign
            $dbTo->Fields["refAssignmentID"] = $toUID;
            $dbTo->Fields["strLastUser"] = "New Module Replication";

            $newQ = $dbTo->Save(1,0);
            $xdb->doQuery("
               INSERT INTO surOption ( refQuestionID, strOption, intWeighting, intOrder )
               SELECT $newQ->ID AS refQuestionID, strOption, intWeighting, intOrder
               FROM surOption
               WHERE refQuestionID=$rowQ->QuestionID");
         }
      }}
   }

   //20181206 - Sync To Live - pj/R
   public static function syncToLive($CourseID)
   {
      global $xdb, $DT, $BR, $MYSQLI, $SystemSettings, $DATABASE_SETTINGS2;

$BR = chr(13);
      header("Content-type: text");

      //0 - INI: SET All related entities.strLastUser to "SYNC TO LIVE" [e=CT<(tCTM, CTUC, C<(CCoord, CVenue, M<(Notes, Prac, Vid, Assi<(sQ<sO)) > DC)]
      //0.1 CT: update CT.strLU where CT-C.CID=$CID
         //0.2 CTM: update CTM.strLU where CTM-CT-C.CID=$CID
         //0.3 CTUC: update CTUC.strLU where CTUC-CT-C.CID=$CID 
         //0.4 C: update C.strLU where C.CID=$CID
            //0.5 CCoord: update CCoord.strLU where CCoord-C.CID=$CID
            //0.6 CVenue: update CVenue.strLU where CVenue-C.CID=$CID
            //0.7 M: update M.strLU where M-C.CID=$CID
               //0.8 Notes: update Notes.strLU where N-M-C.CID=$CID
               //0.9 Prac: update Prac.strLU where P-M-C.CID=$CID
               //0.A Vid: update Vid.strLU where V-M-C.CID=$CID
               //0.B Assi: update Assi.strLU where A-M-C.CID=$CID
                  //0.C sQ: update sQ.strLU where sQ-A-M-C.CID=$CID
                     //0.D sO: update sO.strLU where sO-sQ-A-M-C.CID=$CID
               //0.E DC: update DC.strLU where DC-(N|P|V|A)-M-C.CID=$CID

      //1 - PREP DATA EXPORT where *.strLU = "SYNC TO LIVE"
      //1.1 CT: select * from CT where strLU = S2L
      //1.2 CTM: select * from CTM w...
      //1.3 CTUC: select * from CTUC w...
      //1.4 C: select *, CID*-1 AS CID from C w...
      //1.5 CCoord: select *, refCID*-1 AS refCID from CCoord w...
      //1.6 CVenue: select *, refCID*-1 AS refCID from CVenue w...
      //1.7 M: select *, refCID*-1 AS refCID, MID*-1 as MID from M w...
      //1.8 Notes: select *, refMID*-1 as refMID from Notes w...
      //1.9 Prac: select *, refMID*-1 as refMID from Prac w...
      //1.A Vid: select *, refMID*-1 as refMID from Vid w...
      //1.B Assi: select *, refMID*-1 as refMID from Assi w...
      //1.C sQ: select *, QID*-1 as QID from sQ w...
      //1.D sO: select *, refQID*-1 AS refQID, OID*-1 as OID from sO w...
      //1.E DC: select * from DC w...



//       //3.E Upload files found in select * from DC w...



// //0 - INI: SET All related entities.strLastUser to "SYNC TO LIVE" [e=CT<(tCTM, CTUC, C<(CCoord, CVenue, M<(Notes, Prac, Vid, Assi<(sQ<sO)) > DC)]
//       echo "$BR#0.1 CT: update CT.strLU where CT-C.CID=$CourseID";
//       $xdb->doQuery("UPDATE tblCourseType INNER JOIN tblCourse ON refCourseTypeID = CourseTypeID
//       SET tblCourseType.strLastUser = 'SYNC TO LIVE' 
//       WHERE CourseID =".$xdb->qs($CourseID), 1);

//       echo "$BR#0.2 CTM: update CTM.strLU where CTM-CT-C.CID=$CourseID ";
//       $xdb->doQuery("UPDATE ((tblCourseTypeModule INNER JOIN tblCourseType ON tblCourseTypeModule.refCourseTypeID = CourseTypeID)
//          INNER JOIN tblCourse ON CourseTypeID = tblCourse.refCourseTypeID)
//          SET tblCourseTypeModule.strLastUser = 'SYNC TO LIVE'
//          WHERE CourseID = ".$xdb->qs($CourseID), 1);

//       echo "$BR#0.3 CTUC: update CTUC.strLU where CTUC-CT-C.CID=$CourseID"; vd("NO LASTUSER Column!! $BR");  //No strLastUser
//       // $xdb->doQuery("SELECT tblCourseTypeUserCategory.strLastUser FROM tblCourseTypeUserCategory INNER JOIN tblCourseType ON tblCourseTypeUserCategory.refCourseTypeID = CourseTypeID INNER JOIN tblCourse ON CourseTypeID = tblCourse.refCourseTypeID WHERE CourseID = ".$xdb->qs($CourseID), 1);

//       echo "$BR#0.4 C: update C.strLU where C.CID=$CourseID";
//       $xdb->doQuery("UPDATE tblCourse SET strLastUser = 'SYNC TO LIVE' WHERE CourseID = ".$xdb->qs($CourseID), 1);

//        echo "$BR#0.5 CCoord: update CCoord.strLU where CCoord-C.CID=$CourseID"; vd("NO LASTUSER Column!! $BR"); //No strLastUser
//       // $xdb->doQuery("SELECT strLastUser FROM tblCourseCoordinator WHERE refCourseID = ".$xdb->qs($CourseID), 1);

//        echo "$BR#0.6 CVenue: update CVenue.strLU where CVenue-C.CID=$CourseID"; vd("NO LASTUSER Column!! $BR");  //No LastUser
//       // $xdb->doQuery("SELECT strLastUser FROM tblCourseVenue WHERE refCourseID =".$xdb->qs($CourseID), 1);

//       echo "$BR#0.7 M: update M.strLU where M-C.CID=$CourseID";
//       $xdb->doQuery("UPDATE modModule INNER JOIN tblCourse ON CourseID = refCourseID
//          SET modModule.strLastUser = 'SYNC TO LIVE'
//          WHERE CourseID =".$xdb->qs($CourseID), 1);

//       echo "$BR#0.8 Notes: update Notes.strLU where N-M-C.CID=$CourseID";
//       $xdb->doQuery("UPDATE  modNote INNER JOIN modModule ON ModuleID = refModuleID INNER JOIN tblCourse ON CourseID = refCourseID 
//          SET modNote.strLastUser = 'SYNC TO LIVE'
//          WHERE CourseID =".$xdb->qs($CourseID), 1);

//       echo "$BR#0.9 Prac: update Prac.strLU where P-M-C.CID=$CourseID";
//       $xdb->doQuery("UPDATE ((modPractical INNER JOIN modModule ON ModuleID = refModuleID) INNER JOIN tblCourse ON CourseID = refCourseID)
//          SET modPractical.strLastUser = 'SYNC TO LIVE'
//          WHERE CourseID =".$xdb->qs($CourseID), 1);

//       echo "$BR#0.A Vid: update Vid.strLU where V-M-C.CID=$CourseID";
//       $xdb->doQuery("UPDATE ((modVideo INNER JOIN modModule ON ModuleID = refModuleID) INNER JOIN tblCourse ON CourseID = refCourseID)
//          SET modVideo.strLastUser = 'SYNC TO LIVE'
//          WHERE CourseID =".$xdb->qs($CourseID), 1);

//       echo "$BR#0.B Assi: update Assi.strLU where A-M-C.CID=$CourseID";
//       $xdb->doQuery("UPDATE ((modAssignment INNER JOIN modModule ON ModuleID = refModuleID) INNER JOIN tblCourse ON CourseID = refCourseID) 
//          SET modAssignment.strLastUser = 'SYNC TO LIVE'
//          WHERE CourseID = ".$xdb->qs($CourseID), 1);

//       echo "$BR#0.C sQ: update sQ.strLU where sQ-A-M-C.CID=$CourseID";
//       $xdb->doQuery("UPDATE (((surQuestion INNER JOIN modAssignment ON refAssignmentID = AssignmentID) INNER JOIN modModule ON ModuleID =  refModuleID) INNER JOIN tblCourse ON CourseID = refCourseID)
//          SET surQuestion.strLastUser = 'SYNC TO LIVE'
//          WHERE CourseID = ".$xdb->qs($CourseID), 1);

//        echo "$BR#0.D sO: update sO.strLU where sO-sQ-A-M-C.CID=$CourseID"; vd("NO LASTUSER Column!! $BR"); //No LastUser
//       // $xdb->doQuery("SELECT surOption.strLastUser FROM surOption INNER JOIN surQuestion ON QuestionID = refQuestionID INNER JOIN modAssignment ON AssignmentID = refAssignmentID INNER JOIN modModule ON ModuleID = refModuleID INNER JOIN tblCourse ON CourseID =  refCourseID WHERE CourseID = ".$xdb->qs($CourseID), 1);

//       echo "$BR#0.E DC: update DC.strLU where DC-(N|P|V|A)-M-C.CID=$CourseID";
//       //TODO:
//       // $xdb->doQuery("SELECT * FROM modDownloadContent INNER JOIN TOBESELECTED ON UniqueID = TOBESELECTED.ID INNER JOIN modModule ON 
//       //    ModuleID = TOBESELECTED.refModuleID INNER JOIN tblCourse ON CourseID = refCourseID");
//       $xdb->doQuery("UPDATE (((((((modDownloadContent LEFT JOIN modVideo ON modDownloadContent.UniqueID = modVideo.VideoID) LEFT JOIN modAssignment ON modDownloadContent.UniqueID = modAssignment.AssignmentID) LEFT JOIN modNote ON modDownloadContent.UniqueID = modNote.NoteID) LEFT JOIN modPractical ON modDownloadContent.UniqueID = modPractical.PracticalID) LEFT JOIN modModule AS modModule_1 ON modVideo.refModuleID = modModule_1.ModuleID) LEFT JOIN modModule AS modModule_2 ON modAssignment.refModuleID = modModule_2.ModuleID) LEFT JOIN modModule AS modModule_3 ON modNote.refModuleID = modModule_3.ModuleID) LEFT JOIN modModule AS modModule_4 ON modPractical.refModuleID = modModule_4.ModuleID 
//          SET modDownloadContent.strLastUser = 'SYNC TO LIVE'
//          WHERE (((modModule_1.refCourseID)=". $xdb->qs($CourseID) .")) OR (((modModule_2.refCourseID)=". $xdb->qs($CourseID) .")) OR (((modModule_3.refCourseID)=". $xdb->qs($CourseID) .")) OR (((modModule_4.refCourseID)=". $xdb->qs($CourseID) ."));", 1);


//1 - PREP DATA EXPORT where *.strLU = "SYNC TO LIVE"
      echo "$BR$BR#1.1 CT: select * from CT where strLU = S2L$BR";
      $edb = new NemoDatabase("tblCourseType", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM tblCourseType WHERE strLastUser = 'SYNC TO LIVE'", 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         //print_rr($edb);
         //update statement: $edb->Save(1,2); vd($edb->sql);
         //insert statement: 
         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));

         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);


         //Switch to Current DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
//            , $DATABASE_SETTINGS2["lamp"]->username
//            , $DATABASE_SETTINGS2["lamp"]->password
//            , $DATABASE_SETTINGS2["lamp"]->database); 

         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }
      // die("sdfguiu");

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 

      echo "$BR#1.2 CTM: select * from CTM w...$BR";
      $edb = new NemoDatabase("tblCourseTypeModule", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM tblCourseTypeModule WHERE strLastUser = 'SYNC TO LIVE'", 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);
         
         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));

         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);


         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 

      


      echo "$BR#1.3 CTUC: select * from CTUC w...$BR";
      $edb = new NemoDatabase("tblCourseTypeUserCategory", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT tblCourseTypeUserCategory.* FROM tblCourseTypeUserCategory INNER JOIN tblCourseType ON tblCourseTypeUserCategory.refCourseTypeID = CourseTypeID INNER JOIN tblCourse ON CourseTypeID = tblCourse.refCourseTypeID WHERE CourseID = ".$xdb->qs($CourseID), 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));

         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 

         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 


      echo "$BR#1.4 C: select *, CID*-1 AS CID from C w...$BR";
      $edb = new NemoDatabase("tblCourse", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM tblCourse WHERE strLastUser = 'SYNC TO LIVE'", 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->Fields["CourseID"] *= -1; //NB! CID is negative
 
         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));

         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 


      echo "$BR#1.5 CCoord: select *, refCID*-1 AS refCID from CCoord w...$BR";
      $edb = new NemoDatabase("tblCourseCoordinator", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM tblCourseCoordinator WHERE refCourseID = ".$xdb->qs($CourseID), 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->Fields["refCourseID"] *= -1; //NB! CID is negative

         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));


         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 

      echo "$BR#1.6 CVenue: select *, refCID*-1 AS refCID from CVenue w...$BR";
      $edb = new NemoDatabase("tblCourseVenue", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM tblCourseVenue WHERE refCourseID =".$xdb->qs($CourseID), 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->Fields["refCourseID"] *= -1;

         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));

         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 

      echo "$BR#1.7 M: select *, refCID*-1 AS refCID, MID*-1 as MID from M w...$BR";
      $edb = new NemoDatabase("modModule", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM modModule WHERE strLastUser = 'SYNC TO LIVE'", 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->Fields["refCourseID"] *= -1; //NB! CID is negative
         $edb->Fields["ModuleID"] *= -1; //NB! MID is negative

         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));


         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 

         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 

      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 


      echo "$BR#1.8 Notes: select *, refMID*-1 as refMID from Notes w...$BR";
      $edb = new NemoDatabase("modNote", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM modNote WHERE strLastUser = 'SYNC TO LIVE'", 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->Fields["refModuleID"] *= -1; //NB! MID is negative

         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);

         $sqlNote = str_replace($edb->ID["NoteID"], $edb->Fields["NoteID"], $edb->sql);
         echo (str_replace("INSERT", "REPLACE", $BR. $sqlNote .";$BR"));


         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $sqlNote), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 

         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 


      echo "$BR#1.9 Prac: select *, refMID*-1 as refMID from Prac w...$BR";
      $edb = new NemoDatabase("modPractical", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM modPractical WHERE strLastUser = 'SYNC TO LIVE'", 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->Fields["refModuleID"] *= -1; //NB! MID is negative

         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));


         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 


         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 

         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 


      echo "$BR#1.A Vid: select *, refMID*-1 as refMID from Vid w...$BR";
      $edb = new NemoDatabase("modVideo", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM modVideo WHERE strLastUser = 'SYNC TO LIVE'", 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->Fields["refModuleID"] *= -1; //NB! MID is negative
         
         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));


         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 

         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 

         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 


      echo "$BR#1.B Assi: select *, refMID*-1 as refMID from Assi w...$BR";
      $edb = new NemoDatabase("modAssignment", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM modAssignment WHERE strLastUser = 'SYNC TO LIVE'", 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->Fields["AssignmentID"] = $row->AssignmentID;
         $edb->Fields["refModuleID"] *= -1; //NB! MID is negative
         
         $edb->ID[0] = null;
         $edb->blnCustomID = true; //20190221 - This causes issues when copying Questions, references different AssignmentID from QA which causes referencing issues, so copy AssignemtID as is - Rachel
         $edb->Save(0,2);

         //20190221 - Use the AssigmentID from QA instead of new AssignmentID's, else there will be referencing issues when migrating Questions - Rachel
         $AssignmentSQL = str_replace($edb->ID["AssignmentID"], $edb->Fields["AssignmentID"], $edb->sql);

         // echo (str_replace("INSERT", "REPLACE", $BR. $AssignmentSQL .";$BR"));
         echo (str_replace("INSERT", "REPLACE", $BR. $edb->sql .";$BR"));

         //Connect to LIVE DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         // $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql ), 1);
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $AssignmentSQL ), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 

         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 


      echo "$BR#1.C sQ: select *, QID*-1 as QID from sQ w...$BR";
      $edb = new NemoDatabase("surQuestion", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM surQuestion WHERE strLastUser = 'SYNC TO LIVE'", 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->Fields["QuestionID"] *= -1; //NB! QID is negative
         
         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));

         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 


      echo "$BR#1.D sO: select *, refQID*-1 AS refQID, OID*-1 as OID from sO w...$BR";
      $edb = new NemoDatabase("surOption", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT surOption.* 
         FROM ((((surOption INNER JOIN surQuestion ON QuestionID = refQuestionID) 
               INNER JOIN modAssignment ON AssignmentID = refAssignmentID) 
                  INNER JOIN modModule ON ModuleID = refModuleID) 
                     INNER JOIN tblCourse ON CourseID =  refCourseID
               ) 
         WHERE CourseID = ".$xdb->qs($CourseID), 0);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->Fields["OptionID"] *= -1;
         $edb->Fields["refQuestionID"] *= -1; //NB! QID & OID is negative
         
         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));

         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 

         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
         //            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
      }

      //Switch to Current DB - Do the switching outside the while loop, otherwise doesnt switch back if $rst returns nothing
      $db = 
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                 , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 


      echo "$BR#1.E DC: select * from DC w...$BR";
      $edb = new NemoDatabase("modDownloadContent", null, null, 0); //print_rr($edb);
      $rst = $xdb->doQuery("SELECT * FROM modDownloadContent WHERE strLastUser = 'SYNC TO LIVE'", 1);
      while($row = $xdb->fetch_object($rst)){
         $edb->SetValues((array) $row);

         $edb->Fields["DownloadID"] *= -1; //NB! DID is negative

         //insert statement: 
         $edb->ID[0] = null;
         $edb->blnCustomID = true;
         $edb->Save(0,2);
         echo (str_replace("INSERT", "REPLACE", $BR.$edb->sql.";$BR"));

         //Connect to LIVE DB
// $db = 
// $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
//            , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 
         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.knowmore.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->username
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->password
                    , $DATABASE_SETTINGS2["www.knowmore.co.za"]->database); 
         //Export Data
         $xdb->doQuery(str_replace("INSERT", "REPLACE", $edb->sql), 1);

         //Switch to Current DB
         // $db = 
         // $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["lamp"]->hostname
         //            , $DATABASE_SETTINGS2["lamp"]->username
         //            , $DATABASE_SETTINGS2["lamp"]->password
         //            , $DATABASE_SETTINGS2["lamp"]->database); 

         $db = 
         $MYSQLI = mysqli_connect($DATABASE_SETTINGS2["www.qa-celestis.co.za"]->hostname
                    , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->username
                    , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->password
                    , $DATABASE_SETTINGS2["www.qa-celestis.co.za"]->database); 


         //FTP Files from QA to LIVE
         // connect and login to FTP server
         $ftpServer = "www.knowmore.co.za";
         $ftpConnection = ftp_connect($ftpServer);


         if($ftpConnection){ //Check if connected to Server

            //Attempt FTP Server Login
            ftp_login($ftpConnection, "knowmvpnxm", "yi8Dv6N23J0"); 
            
            if(is_array(ftp_nlist($ftpConnection, "."))){ //Check if FTP Server login succeeded

               $strFilename = str_replace(" ", "%20",$row->strFilename);
               $strFile = str_replace("webadmin", "/training/dcontent", $SystemSettings["BASE_URL"]).$strFilename;
            
               // upload file
               if(ftp_put($ftpConnection, "public_html/training/dcontent/".$strFilename, $strFile, FTP_BINARY)){ 
                  echo "Successfully uploaded $strFile.";

                  /* 
                  NOTE:
                     FTP_BINARY = .pdf files
                     FTP_ASCII = .txt & .csv files
                  */

               }else{
                 echo "Error uploading $strFile.";
               }

            }else{
               echo "FTP Server Login Failed";
            }

         }else{
            echo "Failed to connect to FTP Server";
         }

         // close connection
         ftp_close($ftpConnection);

      }

      die("DIE");
   }

}
?>
