<?php
/*
   201512?? - implementing AVP Typography - CL
   20170119 - Updating landing page content - christiaan
   //20170203 - Show User => category if blnShow = 1 - christiaan
   //20170203 - Default WPS to -10 if WPS is not set for learner => practice - christiaan
   //20170308 - Perminently hide user category section and WPS block - CL [KM: Feedback PH 3.docx]
*/
   //ini_set('display_errors', '1');
   global $SystemSettings, $System;

   $System = "Overview"; //This is important! this fixes any wierd styling

   include_once("_nemo.basic.cls.php");
   //echo session_name();
   $page = new NemoBasic();
  // if($System)


   //Create iFrame for articles
   $strLatestArticles .= getTypoIframe2($id="latestblogposts/?limit=2");

   //print_rr(getTypoIframe2($id="latestblogposts/?limit=2"));

   //Set Current user login Date and time Text
   $rowLogin = $xdb->getRowSQL("SELECT * FROM sysLogin WHERE strUsername = ". $xdb->qs($page->Learner->strEmail) ." AND LEFT(strDateTime,10) <> '". date("Y-m-d") ."' ORDER BY LoginID DESC");
   if($rowLogin)
   {
      $strLastLogin = "You last logged in on ". date("j F Y H:i", strtotime($rowLogin->strDateTime));
   }

   //Set User Category Text
   if(isset($_SESSION[LEARNER]->USERCATEGORYID))
   {
      $refUserCategoryID = $_SESSION[LEARNER]->USERCATEGORYID;
   }
   else
   {
      $refUserCategoryID = -1; //default
   }
   //print_rr($_SESSION[LEARNER]);
   $rowUser = $xdb->getRowSQL("SELECT tblLearner.*, tblUserCategory.strUserCategory, tblUserType.strUserType, tblUserCategory.txtWelcomeMessage, tblUserCategory.blnShow
                              FROM (tblUserType INNER JOIN tblUserCategory ON tblUserType.refUserCategoryID = tblUserCategory.UserCategoryID) INNER JOIN tblLearner ON tblUserType.UserTypeID = tblLearner.refUserTypeID
                              WHERE LearnerID =". $_SESSION[LEARNER]->ID ,0);

   //Show/Hide WPS section
   $strHideWPS = "display: none;";
   $strHideUserCategory = "display: none;";
   $refWPSID = -10; //default WPSID
   
   if($rowUser->refPracticeID != 0 && $rowUser->refPracticeID != NULL)
   {
      $rowPractice = $xdb->getRowSQL("SELECT * FROM tblPractice WHERE PracticeID = '". $rowUser->refPracticeID . "'",0);
      $refWPSID = $rowPractice->refWPSID;
      if($refWPSID == NULL)
      {
         $refWPSID = -10;
      }
   }

   //20170203 - Default WPS to -10 if WPS is not set for learner => practice - christiaan
   $rowWPS = $xdb->getRowSQL("SELECT * FROM vieWPS WHERE WPSID = $refWPSID",0);


//Pillar query
      $PrID = $rowUser->refPracticeID;
      $CurrYear = date("Y");
      $rstCurrentAssessment = $xdb->doQuery("
         SELECT dwfBatResults_2020.PracticeID, dwfBatResults_2020.ClusterID, dwfBatResults_2020.PillarID, Max(dwfBatResults_2020.strDate) AS strDate, tblQQ_2020.intOrder
         FROM tblQQ_2020 INNER JOIN dwfBatResults_2020 ON tblQQ_2020.refClusterID = dwfBatResults_2020.ClusterID
         WHERE refQuestionnaireID =  4 AND strDate LIKE '$CurrYear%'
         GROUP BY dwfBatResults_2020.PracticeID, dwfBatResults_2020.ClusterID
         HAVING dwfBatResults_2020.PracticeID='$PrID'
         ORDER BY tblQQ_2020.intOrder ASC, strDate DESC  ", 0);

//OVERALL RAG INI
      $i = 
      $intOverallRedCurrent = 
      $intOverallAmberCurrent = 
      $intOverallGreenCurrent = 0;
      $currentAssessmentDate = "";

    

      while($row = $xdb->fetch_object($rstCurrentAssessment))
      {
  
        if($i == 0){
          $currentAssessmentDate = $row->strDate;

        }

         //Query for Overall Results
         $rowX = $xdb->getRowSQL("SELECT dwfBatResults_2020.PracticeID, dwfBatResults_2020.ClusterID, dwfBatResults_2020.PillarID, dwfBatResults_2020.intQuestions, dwfBatResults_2020.intQuestionsMax, dwfBatResults_2020.strDate, intRed, intAmber, intGreen, intTCFRed, intTCFAmber, intTCFGreen, intRDRRed, intRDRAmber, intRDRGreen
            FROM dwfBatResults_2020 
            GROUP BY dwfBatResults_2020.PracticeID, dwfBatResults_2020.ClusterID, dwfBatResults_2020.intQuestions, dwfBatResults_2020.intQuestionsMax, dwfBatResults_2020.strDate
            HAVING (((dwfBatResults_2020.PracticeID)='$PrID') AND ((dwfBatResults_2020.ClusterID)=$row->ClusterID) AND ((dwfBatResults_2020.strDate)='$row->strDate'))
            
            ", 0);

         //SUM of Overall RAG Results (sum of all the sections)
            //Overrall Assessment percentages
            $intOverallRedCurrent += $rowX->intRed;
            $intOverallAmberCurrent += $rowX->intAmber;
            $intOverallGreenCurrent += $rowX->intGreen;

            $i++;
      }

      // print_rr($arrSectionResults[16]);

//PIE CHARTS SECTION 
//NOTE: only draw a chart if there is results

      //OVERALL ASSESSMENT CHART
      $intOverralTotalCurrent = $intOverallRedCurrent + $intOverallAmberCurrent + $intOverallGreenCurrent;


      $PrevYear = date("Y", strtotime("-1 year"));
      
      $PrID = $rowUser->refPracticeID;
      $rstPrevAssessment = $xdb->doQuery("
         SELECT dwfBatResults_2020.PracticeID, dwfBatResults_2020.ClusterID, dwfBatResults_2020.PillarID, Max(dwfBatResults_2020.strDate) AS strDate, tblQQ_2020.intOrder
         FROM tblQQ_2020 INNER JOIN dwfBatResults_2020 ON tblQQ_2020.refClusterID = dwfBatResults_2020.ClusterID
         WHERE refQuestionnaireID =  4 AND strDate LIKE '$PrevYear%'
         GROUP BY dwfBatResults_2020.PracticeID, dwfBatResults_2020.ClusterID
         HAVING dwfBatResults_2020.PracticeID='$PrID'
         ORDER BY tblQQ_2020.intOrder ASC, strDate DESC  ", 0);

//OVERALL RAG INI
      $i =
      $intOverallRedPrev = 
      $intOverallAmberPrev = 
      $intOverallGreenPrev = 0;

      $prevAssessmentDate = "";

      while($row = $xdb->fetch_object($rstPrevAssessment))
      {

        if($i == 0){
          $prevAssessmentDate = $row->strDate;

        }

         //Query for Overall Results
         $rowX = $xdb->getRowSQL("SELECT dwfBatResults_2020.PracticeID, dwfBatResults_2020.ClusterID, dwfBatResults_2020.PillarID, dwfBatResults_2020.intQuestions, dwfBatResults_2020.intQuestionsMax, dwfBatResults_2020.strDate, intRed, intAmber, intGreen, intTCFRed, intTCFAmber, intTCFGreen, intRDRRed, intRDRAmber, intRDRGreen
            FROM dwfBatResults_2020 
            GROUP BY dwfBatResults_2020.PracticeID, dwfBatResults_2020.ClusterID, dwfBatResults_2020.intQuestions, dwfBatResults_2020.intQuestionsMax, dwfBatResults_2020.strDate
            HAVING (((dwfBatResults_2020.PracticeID)='$PrID') AND ((dwfBatResults_2020.ClusterID)=$row->ClusterID) AND ((dwfBatResults_2020.strDate)='$row->strDate'))
            
            ", 0);

         //SUM of Overall RAG Results (sum of all the sections)
            //Overrall Assessment percentages
            $intOverallRedPrev += $rowX->intRed;
            $intOverallAmberPrev += $rowX->intAmber;
            $intOverallGreenPrev += $rowX->intGreen;

          $i++;
      }

      // print_rr($arrSectionResults[16]);

//PIE CHARTS SECTION 
//NOTE: only draw a chart if there is results

      //OVERALL ASSESSMENT CHART
      $intOverralTotalPrev = $intOverallRedPrev + $intOverallAmberPrev + $intOverallGreenPrev;


      $pieChartArea = "";




      if($intOverralTotalCurrent > 0 || $intOverralTotalPrev > 0){
        $pieChartArea = "
        <div style=''>
        <h2 style='text-align:center;color:#797979;font-size:21px!important;'><u>Business Assessment Tool</u></h2>

        <table>

         ";

         if($intOverralTotalCurrent > 0 && $intOverralTotalPrev > 0)
         {

            $pieChartArea .= "           
            <tr>
              <td width='50%' align='center' style='color:#797979;height:43px;'>Status of your current assessment completed on
                 ".date("Y-m-d", strtotime($currentAssessmentDate))."
               </td>
             <td width='50%' align='center' style='color:#797979;height:43px;'>Status of your previous assessment completed on
             ".date("Y-m-d", strtotime($prevAssessmentDate))."
             </td>
            </tr>

            <tr>
             <br> <br>
                   <td align='center' style='border: solid 1px #FFF;'>
                       <div class='chartTitle' style='text-align:center;font-size:15px;'><b>Overall Assessment<b></div>
                         <div id='currentAssessment'>
                       </div></td>
                   <td align='center' style='border: solid 1px #FFF;'>
                     <div class='chartTitle' style='text-align:center;font-size:15px;'><b>Overall Assessment<b></div>
                     <div id='prevAssessment'>
                       </div>
                   </td>
            </tr>";
         }elseif ($intOverralTotalCurrent > 0) {
         // print_rr("here");

            $pieChartArea .= "           
            <tr>
              <td  width='50%' align='center' style='color:#797979;height:43px;'>Status of your current assessment completed on
                 ".date("Y-m-d", strtotime($currentAssessmentDate))."
               </td>
            </tr>
            <tr>
                   <td align='center' style='border: solid 1px #FFF;'>
                       <div class='chartTitle' style='text-align:center;font-size:15px;'><b>Overall Assessment<b></div>
                         <div id='currentAssessment'>
                       </div></td>
            </tr>";

         }elseif ($intOverralTotalPrev > 0) {
            $pieChartArea .= "           
            <tr>
             <td width='50%' align='center' style='color:#797979;height:43px;'>Status of your previous assessment completed on
             ".date("Y-m-d", strtotime($prevAssessmentDate))."
             </td>
            </tr>
            <tr>
                   <td align='center' style='border: solid 1px #FFF;'>
                     <div class='chartTitle' style='text-align:center;font-size:15px;'><b>Overall Assessment<b></div>
                     <div id='prevAssessment'>
                       </div>
                   </td>
            </tr>";
         }


      }else{
         $pieChartArea .= "
         <div style='padding:9px;'>
         <h3>If you are the owner of a financial planning business or manage a client book, how do you know if you are managing your business optimally? </h3>

         <p style='font-size:14px!important;'>There are six key areas in a financial planning business that are required to be managed effectively. An impact in one area could possibly impact another. We have designed an online Business Assessment Tool, specifically for use for our Wealth and Strategic Partner businesses to help identify and address potential gaps that may prevent them from operating within a future fit environment. </p> <br>

         <p style='font-size:14px!important;'>These six integrated areas revolve around: </p>

         <img src='../images/BMSOverview.jpg' alt='Smiley face' width='41%' height='' style='margin-left:25%'> 
         
         <br>

         <p style='font-size:14px!important;'>To acquire access to our business tool, contact your Wealth Account Manager or email <a href='mailto:info@knowmore.co.za'>info@knowmore.co.za</a>.</p>

         <br><br>
         </div>

         ";
      }

      $pieChartArea .= "</table> </div>";

      // var_dump($pieChartArea);
    $CPDStartPeriod = $SystemSettings["CPDStartPeriod"];
    $CPDEndPeriod = $SystemSettings["CPDEndPeriod"];


    // $rowCPDPoints = $xdb->getRowSQL("SELECT SUM(dblPointsFPI) AS CPDPointsObtained FROM tblCPDPoints WHERE refLearnerID = ".$_SESSION[LEARNER]->ID." AND dtEventDate BETWEEN '$CPDStartPeriod' AND '$CPDEndPeriod'", 1);

    $rowCPDPoints = $xdb->getRowSQL("SELECT SUM(dblPointsFPI) AS CPDPointsObtained FROM tblCPDPoints WHERE refLearnerID = ".$_SESSION[LEARNER]->ID." ", 0);

    $maxCPDPoints = 37; //Default
    $CPDPointsObtained = $rowCPDPoints->CPDPointsObtained;

    if($rowUser->intCPDPointsRequired > 0){
        $maxCPDPoints = $rowUser->intCPDPointsRequired;
    }

    $CPDDivider = $maxCPDPoints/3;
    $CPDRed = $CPDDivider;
    $CPDAmber = $CPDDivider * 2;
    $CPDGreen = $CPDDivider * 3;

   $CPDPointsArea = "";
   if($CPDPointsObtained > 0 && ($rowUser->intCPDPointsRequired != 0 && $rowUser->intCPDPointsRequired != "N/A")){     
      $CPDPointsArea = "  
      <div style=''>   
      <h2 style='text-align:center;color:#797979;font-size:21px!important;'><u>MY CPD POINTS</u></h2>
     <br>
     <p style='text-align:center;font-size:14px!important;'>CPD earned through Old Mutual Wealth for the period ".date("d M Y", strtotime($CPDStartPeriod))." to ".date("d M Y", strtotime($CPDEndPeriod)).".</p>
     <div style='display: block;margin-left: auto;margin-right: auto;width: 32%;' id='speedometer'>
     </div>
    </div>";
   }



   if($pieChartArea != "" && $CPDPointsArea != "")
   {
      $strOutput .= $pieChartArea. "<div style='border-bottom: 3px solid #50b848;padding: 9px;'> </div>". ($CPDPointsArea) ;
   }else{
      $strOutput .= $pieChartArea.($CPDPointsArea) ;
   }


   $page->Content = "

   <style>
     .h1LandingPage
     {
        border-bottom-width:2px;
        border-bottom-color:#00785F;
        border-bottom-style: solid;
        text-align:left;
        margin: 0px;We have updated the Know<b>more</b> site to make it more user friendly.
        padding: 0px;
        margin-bottom: 20px;
     }

     .divSectionEntireWrapper
     {
        xpadding: 0px 20px 0px 20px; //top, right, bottom , left;
     }

     .divSectionAll
     {
        background-color: #FFFFFF;
        vertical-align: top;
        margin: 0;
        padding: 12px; //top, right, bottom , left;

     }

     #divSection1
     {
        margin-left: 12px;
        height: 638px /*700px*/;
     }

     .divSection1
     {
        float: right;
     }

     .divSection2n3
     {

        float: left;
     }

     #divSection4
     {
        min-height:240px;
     }
     .divSection4
     {
        clear:both;
     }

     .divSectionSpacer
     {
        padding: 0px 0px 20px 0px; //top, right, bottom , left;
        vertical-align: top;
        margin: 0px;
     }

     .divSectionWidthThin
     {
        width: 50%;
     }

     .divSectionWidthWide
     {
        width: 100%;
     }

     .divSectionNoSpacing
     {
        vertical-align: top;
        padding: 0px;
        margin: 0px;
     }

     p
     {
        margin-bottom: 10px;
     }

     .imgLoading
     {
        width: 40px;
        position: absolute;

        top: 25%;
        left: 70%;
        margin-left: 20px;
        margin-top: 20px;
     }


   </style>

   <div id='divLandingContentWrapper' class='divSectionWidthWide divSectionNoSpacing' xstyle='background-color: red;'>
      <div id='divLandingContentSpacer' class='divSectionEntireWrapper'>

            <div id='divSection1Wrapper' style='display:none;' class='divSectionWidthThin divSection1 divSectionSpacer'>
               <div id='divSection1' class='divSectionAll'>
                  <h1 class='h1LandingPage' >
                     Latest Articles
                  </h1>
                  <div id='divLoading' class='divLoading'>
                     <img id='imgLoading' src='/images/loading.gif' class='imgLoading' />
                  </div>

                  ".$strLatestArticles."

               </div>
            </div>

            <div id='divSection2and3Wrapper' style='width:100%' class='divSectionWidthThin divSection2n3'>
               <div id='divSection2Spacer' class='divSectionSpacer'>
                  <div id='divSection2' class='divSectionAll'>
                 
                     <h1 class='h1LandingPage' style='margin: 0;font-size:21px!important;'>
                        Welcome Back ".($_SESSION['CoachName'] ? $_SESSION['CoachName'] : $_SESSION[LEARNER]->DISPLAYNAME)."!
                       </h1>
                        <span style=\"float: right; color:black; font-size: 12px;font-family: 'museo1','Arial',Sans-Serif; font-size: 12px; padding: 0; margin-bottom: 10px;\">
                           $zstrLastLogin
                        </span>"
                     // <p class='test' style='clear:both;'>
                     //    What would you like to do today?
                     //    Use the menu tabs at the top to guide you.
                     // </p>
                     ."
                     <div style='border:3px solid #50b848;margin-top:12px;padding:12px;'>
                     <br>
                        <p style='clear:both;font-size:14px!important;'>
                           Thank you for accessing Old Mutual Wealth’s online learning platform. 
                        </p>
                        <p style='clear:both;font-size:14px!important;'>
                        
                       Our range of <span style='color:#50b848;'><a href='home.tools.php?System=Business_Tools'>Business Tools</a>, <a href='home.courses.php?System=Courses'>Courses</a>, <a href='home.workshops.php?System=Workshops'>Workshops</a> and <a href='home.wi.php?System=Wealth_Intelligence'>Publications</a></span> are designed to empower and enhance the skills of Financial Planning Business Owners, Financial Planners and Support Staff. Most of our learning activities offers either verifiable or non-verifiable CPD points. Our CPD process is aligned to the guidelines as set out by the FPI and whilst these can only be earned once off, you are able to complete the activity as many times as you like to improve your learning. 
                        <br/><br/>
                        We hope you find our content practical and relevant to your learning requirements. Any suggestions you would like to make, can be sent to <a href='mailto:info@knowmore.co.za'>info@knowmore.co.za</a>. 
                     </p>
                     <p style='font-size:14px!important;'>
                     <br/>
                        All the best on your learning journey!
                        <br><br/>
                        The Knowmore Team
                     </p>

                  </div>

                     <br><br/>
                     <div style='border:3px solid #50b848;padding:9px;padding-left: 0px;padding-right: 0px;'>
                        ".$strOutput."
                     </div>
                  </div>

               </div>
               <div id='divSection3Spacer' class='divSectionSpacer'>
                  <div id='divSection3' class='divSectionAll' style='$strHideUserCategory'>
                     <h1 class='h1LandingPage'>$rowUser->strUserCategory</h1>"
                     //<p>You are currently registered in the following categories: $rowUser->strUserCategory - $rowUser->strUserType.</p>
                     ."<p style='font-size:14px!important;'>".mynl2br($rowUser->txtWelcomeMessage)."</p>
                     <p style='font-size:14px!important;'>
                        If you cannot find something you are looking for, please contact us at info@knowmore.co.za.
                     </p>
                  </div>
               </div>
            </div>
         </div>
         <div id='divSection4Spacer' class='divSection4 divSectionSpacer divSectionWidthWide' style='$strHideWPS'>
            <div id='divSection4' class='divSectionAll'>
               <h1 class='h1LandingPage'>Your WPS Coordinator</h1>

               <img src='".$SystemSettings["ProfileImageDirLearner"].$rowWPS->{"Profile".":PicturePath"}."' style='width:200px; float: left; margin-right: 12px;'>
               <p style='padding: 8px;font-size:14px!important;'>
                  Name: $rowWPS->strUser <br/>
                  Email: $rowWPS->strEmail <br/>
                  Telephone: $rowWPS->strTel
               </p>
               <p style='padding: 8px;font-size:14px!important;'>
                  ".mynl2br($rowWPS->txtWPSTeamBio)."
               </p>
            </div>

      </div>
   </div>
   <script type='text/javascript' src='https://www.gstatic.com/charts/loader.js'></script>

   ".js("

      google.charts.load('current', {'packages':['gauge']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Label', 'Value'],
          ['CPD', $CPDPointsObtained]
        ]);

        var options = {
          width: 1500, height: 300,
          redFrom: 0, redTo: $CPDRed,
          yellowFrom:$CPDRed, yellowTo: $CPDAmber,
          greenFrom:$CPDAmber, greenTo: $CPDGreen,
          redColor: '#cc0000',
          greenColor: '#8dc63f',
          yellowColor: '#ffbf00',
          minorTicks: 5,
          majorTicks: ['0',''+($CPDRed).toFixed(0), ''+($CPDAmber).toFixed(0), ''+$maxCPDPoints],
          max: $maxCPDPoints,
        };

        var chart = new google.visualization.Gauge(document.getElementById('speedometer'));
        chart.draw(data, options);
      }





                        function drawBATResultsPie(pieChartID, chartTitle, intOverallRed, intOverallAmber, intOverallGreen){

                           //Default Width + Height
                           var width = 330;
                           var height = 300;

                           //Diplay all the charts side by side except Overall chart
                           if(pieChartID == 'execSummary')
                           {
                              width = 670;
                              height = 300;
                           }
                           
                           google.charts.load('current', {'packages':['corechart']});
                           google.charts.setOnLoadCallback(drawChart);

                           // Draw the chart and set the chart values
                           function drawChart() {
                             var data = google.visualization.arrayToDataTable([
                             ['Weighing', 'Percentage'],
                             ['Red', intOverallRed],
                             ['Amber', intOverallAmber],
                             ['Green', intOverallGreen],
                             ]);

                             //Display percentages on the legend for smaller slices
                             var RAGtotal = intOverallRed + intOverallAmber + intOverallGreen;
                             var redTotal = (intOverallRed/RAGtotal) * 100;
                             var amberTotal = (intOverallAmber/RAGtotal) * 100;
                             var greenTotal = (intOverallGreen/RAGtotal) * 100;

                              if(redTotal <= 8){
                                 data.setFormattedValue(0, 0, data.getValue(0, 0) + ' (' + ( redTotal).toFixed(1) + '%)');
                              }

                              if(amberTotal <= 8){
                                 data.setFormattedValue(1, 0, data.getValue(1, 0) + ' (' + ( amberTotal).toFixed(1) + '%)');
                              }

                              if(greenTotal <= 8){
                                 data.setFormattedValue(2, 0, data.getValue(2, 0) + ' (' + ( greenTotal).toFixed(1) + '%)');
                              }

                          //Add a title and set the width and height of the chart
                          var options = {
                           pieSliceBorderColor : 'transparent',
                           'width': width, 
                           'height': height,
                           backgroundColor: '#E4E4E4',
                           legend: {position: 'bottom', textStyle: {fontSize: 12, bold:true}},
                           tooltip: {textStyle: {fontSize: 12, bold:true}},
                           colors: ['#cc0000', '#ffbf00', '#8dc63f'],
                           pieHole: 0.4,
                           pieSliceTextStyle: {color: 'black', fontSize:12, bold:true},
                           pieStartAngle: 50,
                           };

                           // Display the chart inside the chart <div> element 
                           var chart_div = document.getElementById(pieChartID);
                           var chart = new google.visualization.PieChart(chart_div);

                           // google.visualization.events.addListener(chart, 'ready', function(){
                              
                           //   chart_div.innerHTML = '<img src=\"'+chart.getImageURI()+'\">';
                                 
            
                           //    });


                           //center align title

                           chart.draw(data, options);
                           // chart_div.innerHTML = '<img  src=\"'+chart.getImageURI()+'\">';
                           // alert(chart_div.innerHTML);

                           if(pieChartID == 'execSummary')
                           {
                              document.querySelector('#'+pieChartID+' > div > div:nth-child(1) > div > svg > g:nth-child(3) > text').setAttribute('x', 280);
                           }else{
                              $('text:contains(' + options.title + ')').attr({'x':'150', 'y':'20'})
                           }
                          



                           

                        }
                     }

     drawBATResultsPie('currentAssessment', 'Overrall Assessment', $intOverallRedCurrent, $intOverallAmberCurrent, $intOverallGreenCurrent );
     drawBATResultsPie('prevAssessment', 'Overrall Assessment', $intOverallRedPrev, $intOverallAmberPrev, $intOverallGreenPrev ); 
      ");



   $page->Display("layout.landing.page.incl.php");
?>