<?php

  include ('include_fns.php');
  session_start();

  function displaydate($date, $hide)
  {
    if ($hide == 'I')
    {
      $dd   = substr($date, 0, 2);
      $mm   = substr($date, 3, 2);
      $yyyy = substr($date, 6, 4);

      if ($mm == '01')
        $newmm = 'JAN';
      else
      if ($mm == '02')
        $newmm = 'FEB';
      else
      if ($mm == '03')
        $newmm = 'MAR';
      else
      if ($mm == '04')
        $newmm = 'APR';
      else
      if ($mm == '05')
        $newmm = 'MAY';
      else
      if ($mm == '06')
        $newmm = 'JUN';
      else
      if ($mm == '07')
        $newmm = 'JUL';
      else
      if ($mm == '08')
        $newmm = 'AUG';
      else
      if ($mm == '09')
        $newmm = 'SEP';
      else
      if ($mm == '10')
        $newmm = 'OCT';
      else
      if ($mm == '11')
        $newmm = 'NOV';
      else
      if ($mm == '12')
        $newmm = 'DEC';

      return $dd.'-'.$newmm.'-'.$yyyy;


    }
    else
    {
      $dd   = substr($date, 8, 2);
      $mm   = substr($date, 5, 2);
      $yyyy = substr($date, 0, 4);


      if ($hide == 'T')
      {
        $newdate = $mm.'/'.$dd.'/'.$yyyy;
        return date('d-M-Y', strtotime($newdate));
      }
      else
        return $dd.'/'.$mm.'/'.$yyyy;;
    }
  }
  
  function get_practitioner_name($practitioner)
  {
    $result = ExecuteQuery("SELECT FIRSTNAME, SURNAME FROM PRACTITIONER WHERE PRACTITIONER_KEY = $practitioner;");
    
    return $result[0][0].' '.$result[0][1];
  }

  function get_patient_name($account_key, $patient_key)
  {
    $result = ExecuteQuery("SELECT FIRSTNAME, SURNAME FROM PATIENT WHERE ACCOUNT_KEY = '$account_key' 
                                          AND PATIENT_KEY = $patient_key;");
    
    return $result[0][0].' '.$result[0][1];
  }

  function get_status($status_key)
  {
    $result = ExecuteQuery("SELECT DIARYSTATUS_DESC FROM DIARYSTATUS WHERE DIARYSTATUS_KEY = $status_key");
    
    return $result[0][0].' '.$result[0][1];
  }

  function get_driver($driver_key)
  {
    if ($driver_key > 0)
    {
      $result = ExecuteQuery("SELECT FIRSTNAME, SURNAME FROM DRIVER WHERE DRIVER_KEY = $driver_key");

      return $result[0][0].' '.$result[0][1];
    }
    else
      return '';
  }

  function get_courthouse($courthouse_key)
  {
    if ($courthouse_key > 0)
    {
      $result = ExecuteQuery("SELECT COURTHOUSE_NAME FROM COURTHOUSE WHERE COURTHOUSE_KEY = $courthouse_key");

      return $result[0][0];
    }
    else
      return '';
  }

  function get_region($region_key)
  {
    $result = ExecuteQuery("SELECT REGION_NAME FROM REGION WHERE REGION_KEY = $region_key");

    return $result[0][0];
  }

  function display_appointment_form($status, $appointmentvalues = '', $region_key, $diarydate, $trialdate)
  {
    if(!check_admin_user())
    {
     echo "You do not seem to be logged in.";
     exit;
    }

    $_SESSION['AppointmentURL'] = selfURL();

    $values = $appointmentvalues;
    $savedtime = substr($values[APP_FROMTIME], 11, 5);

    ?>

    <script src="patientdialog.js"></script>
    
    <script>
    

      $('#cobxApptRegion').change(function () {

        $('#cobxPractitioner').empty();
        $('#cobxApptTime').empty();
        $('#cobxDriver').empty();

        var Region = $('#cobxApptRegion').val();

           $.ajax({
                   url     : 'loadcombo.php?stopcache='+ new Date().getTime(),
                   type    : 'GET',
                   cache   : false,
                   context : $(this),
                   data    : {'Type':'Practitioner', 'Region_Key': Region, 'showblank':'T'},
                   success : function(resp){
                                var optionstext = resp;
                                $('#cobxPractitioner').append(optionstext);
                                GetTimeslots();
                             }
           });
           
           $.ajax({
                   url     : 'loadcombo.php?stopcache='+ new Date().getTime(),
                   type    : 'GET',
                   cache   : false,
                   context : $(this),
                   data    : {'Type':'Driver', 'Region_Key': Region},
                   success : function(resp){
                                var optionstext = resp;
                                $('#cobxDriver').append(optionstext);
                             }
           });
           

      });


      $('#cobxPractitioner').change(function () {
        GetTimeslots();
      });

      $('#btnNewPatient').button({ icons: { primary: 'ui-icon-person'} }).click(function(event, ui){
        EditInsertPatient('new', event, ui, '', -1);

      });

      function GetTimeslots(){
        $('#cobxApptTime').empty();

        var Practitioner = $('#cobxPractitioner').val();
        var ApptDate     = $('#hideApptDate').val();

        var time         = '<?php echo $savedtime ?>';

           $.ajax({
                   url     : 'loadcombo.php?stopcache='+ new Date().getTime(),
                   type    : 'GET',
                   cache   : false,
                   context : $(this),
                   data    : {'Type':'Timeslots', 'Practitioner_Key': Practitioner, 'Date': ApptDate, 'Time':time},
                   success : function(resp){
                                var optionstext = resp;
                                $('#cobxApptTime').append(optionstext);
                             }
           });

      };

      $('#btnLookupPatient').button({ icons: { primary: 'ui-icon-search'} }).click(function(event, ui){
         $('#DIARYPATIENTsearchscreen').load("searchscreen.php?action=diarypatient", function (){


                    $( "#DIARYPATIENTsearchscreen" ).dialog({

                       stack : true,
                       modal: true,
                       height : 430,
                       width  : 700,
                       resizable : false,
                       context : $(this),
                       title : 'Patient Lookup',

                       open: function(event) {
                              $(event.target).dialog('widget').css({ position: 'fixed', top:200 });

                              $(".ui-widget-overlay").css({
                               position: 'fixed',
                               top: '0'
                              });
                        },

                       close : function(event, ui) {
                                  var selectedkey  = $('#selectedkey').val();
                                  var selectedkey2 = $('#selectedkey2').val();
                                  var selecteddesc = decodeURIComponent($('#selecteddesc').val());

                                  if (selectedkey != null)
                                  {
                                    $('#edtPatientName').val(selecteddesc);
                                    $('#edtAccount_Key').val(selectedkey);
                                    $('#Patient_Key').val(selectedkey2);

                                    $('#edtTempPatient').val('');
                                  }

                                  $('#DIARYPATIENTsearchscreen').html('');
                                  $(this).dialog('destroy');
                               }

                    });
         });
         return false;
      });
      
      $('#newpatient').on('custom_event', function ()
      {
     //   alert('new' +  $('#newpatient').val());

        var account = $('#newpatient').val();
        var patient = 0;
        
        $('#edtAccount_Key').val(account);
        $('#Patient_Key').val(patient);
        
        $.ajax({
                url     : 'loadpatientcombo.php?stopcache='+ new Date().getTime(),
                type    : 'GET',
                cache   : false,
                context : $(this),
                data    : {'Account_Key': account, 'Patient_Key': patient, 'DiaryName': 'T'},
                success : function(resp){
                             $('#edtPatientName').val(resp);
                          }
        });
      });

      $( '#dpApptDate' ).datepicker
       ({
        dateFormat : 'dd/mm/yy',
        altField   : '#hideApptDate',
        altFormat  : 'dd-MM-yy',
        onClose :function(dateText)
                 { 
                   try 
                   {
                     $.datepicker.parseDate('dd/mm/yy', dateText);
                     GetTimeslots();
                   } 
                   catch (e) 
                   {
                     alert(e);
                   };
                 }  
       });

      GetTimeslots();

    </script>
    
    <?php


    if ($status == 'I') 
      $diarykey = '-1';
    else
      $diarykey = $values[APP_DIARY_KEY];
       

    ?>
      <div id="DIARYPATIENTsearchscreen"></div>
      <div id="newpatient"></div>
      <div id="patientform"></div>

      <center>
      <table bgcolor='#cccccc'  border = 0 cellpadding = 6 cellspacing = 0 width="493" height="229" class='shadetable'>

       <tr>
         <td width="137" height="28">Region</td>
         <td width="290" height="28">

           <?php
            if ($status == 'D')
              echo '<b>'.get_region($values[APP_REGION_KEY]).'</b></td>';
            else
            {
              echo '<select size="1" name="cobxApptRegion" id="cobxApptRegion" class="roundedit" tabindex="2">';

              if ($status == 'I')
                fillcombo("SELECT REGION_KEY, REGION_NAME FROM REGION WHERE REGION_KEY <> 1 ORDER BY REGION_NAME",
                 $region_key, 30);
              else
              if ($status == 'U')
                fillcombo("SELECT REGION_KEY, REGION_NAME FROM REGION WHERE REGION_KEY <> 1 ORDER BY REGION_NAME",
                 $values[APP_REGION_KEY], 30);


              echo '</select></td>';
            }
           ?>
         </tr>

       <?php
       
       if ($trialdate == 'F')
       {
         echo '<tr>';
         echo '  <td width="137" height="28">Practitioner</td>';
         echo '  <td width="290" height="28">';


            if ($status == 'D')
              echo '<b>'.get_practitioner_name($values[APP_PRACTITIONER]).'</b></td>';
            else
            {
              echo '<select size="1" name="cobxPractitioner" id="cobxPractitioner" class="roundedit" tabindex="2">';

              fillcombo("SELECT PRACTITIONER_KEY, FIRSTNAME ||' '|| SURNAME FROM PRACTITIONER WHERE (HIDE = 'F' AND REGION_KEY = ".$region_key.")  ORDER BY SURNAME",
                $values[APP_PRACTITIONER], 30, 'T');

              echo '</select></td>';
            }

         echo ' </tr>';
       }
       else
       if ($trialdate == 'T')
       {
         echo '<input type="hidden" id="cobxPractitioner" name="cobxPractitioner" value =-1 >';
         echo '<input type="hidden" id="cobxDiaryStatus" name="cobxDiaryStatus" value =-1 >';
       }
       
       ?>

       <tr>
          <?php

           if ($trialdate == 'F')
             echo '<td width="137" height="1">Date</td>';
           else
           if ($trialdate == 'T')
             echo '<td width="137" height="1">Court Date</td>';

           echo '<td width="290" height="1">';

            if ($status == 'U')
            {
              echo "<input type='text' id='dpApptDate' name='dpApptDate' class='roundedit' value = '".displaydate($values[APP_DATE], 'F')."'>";
              echo "<input type='text' id='hideApptDate' name='hideApptDate' hidden='True' value = '".displaydate($values[APP_DATE], 'T')."'>";
            }
            else
            if ($status == 'D')
            {
              echo "<b>".displaydate($values[APP_DATE], 'F')."</b>";
            }
            else
            {
              echo "<input type='text' id='dpApptDate' name='dpApptDate' class='roundedit' value = '". $diarydate."'>";
              echo "<input type='text' id='hideApptDate' name='hideApptDate' hidden='True' value = '". displaydate($diarydate, 'I')."'>";
            }
          ?>

         </td>
         </tr>
         
         

       <?php

       if ($trialdate == 'T')
       {

         echo '<tr>';
         echo '  <td width="137" height="1">Court House</td>';
         echo '  <td width="290" height="1">';

            if ($status == 'D')
            {
              echo get_courthouse($values[APP_COURTHOUSE]).'</td>';
              echo '<input type="hidden" id="cobxCourtHouse" name="cobxCourtHouse" value ='.$values[APP_COURTHOUSE].'>';
            }
            else
            {
              echo '<select size="1" name="cobxCourtHouse" id="cobxCourtHouse" class="roundedit" tabindex="2">';

              if ($status == 'I')
                fillcombo("SELECT COURTHOUSE_KEY, COURTHOUSE_NAME FROM COURTHOUSE ORDER BY COURTHOUSE_NAME",
                 -1, 30, 'T');
              else
              if ($status == 'U')
                fillcombo("SELECT COURTHOUSE_KEY, COURTHOUSE_NAME FROM COURTHOUSE ORDER BY COURTHOUSE_NAME",
                 $values[APP_COURTHOUSE], 30, 'T');

              echo '</select></td>';
            }

         echo '  </td>';
         echo '  </tr>';
       }


       if ($trialdate == 'F')
       {

         echo '<tr>';
         echo '  <td width="137" height="1">Available Times</td>';
         echo '  <td width="290" height="1">';

            if ($status == 'D')
              echo '</td>';
            else
            {
              echo '<select size="1" name="cobxApptTime" id="cobxApptTime" class="roundedit" tabindex="2">';
              echo '</select></td>';
            }

         echo '  </td>';
         echo '  </tr>';
       }
       ?>

       <tr>
         <?php
           echo '<td width="137" height="1">Patient</td>';
           echo '<td width="290" height="1">';
         
            if ($status == 'D') 
            {
              if ($values[APP_ACCOUNT] <> '') 
                echo '<input type="text" id="edtPatientName" name="edtPatientName" class="roundedit" size = "43" readonly value = "'.get_patient_name($values[APP_ACCOUNT],$values[APP_PATIENT]) .'"</td>';

            }
            else
            if ($status =='U') 
            {
              if ($_SESSION['diaryaccount'] <> '')
                echo '<input type="text" id="edtPatientName" name="edtPatientName" class="roundedit" style="background-color:#EFEFEF" size = "43" readonly value = "'.get_patient_name($_SESSION['diaryaccount'], $_SESSION['diarypatient']).'"</td>';
              else
              if ($values[APP_ACCOUNT] <> '') 
                echo '<input type="text" id="edtPatientName" name="edtPatientName" class="roundedit" style="background-color:#EFEFEF" size = "43" readonly value = "'.get_patient_name($values[APP_ACCOUNT],$values[APP_PATIENT]) .'"</td>';
              else
                echo '<input type="text" id="edtPatientName" name="edtPatientName" class="roundedit" style="background-color:#EFEFEF" size = "43" readonly </td>';

            }
            else 
            if ($status == 'I') 
            { 
              if ($_SESSION['diaryaccount'] <> '')
                echo '<input type="text" id="edtPatientName" name="edtPatientName" class="roundedit" style="background-color:#EFEFEF" size = "43" readonly value = "'.get_patient_name($_SESSION['diaryaccount'], $_SESSION['diarypatient']).'"</td>';
              else
                echo '<input type="text" id="edtPatientName" name="edtPatientName" class="roundedit" style="background-color:#EFEFEF" size = "43" readonly </td>';

            }
         ?> 
       </tr>
       

       <?php

         if (($status == 'I')||($status == 'U'))
         {
           echo '<tr>';
           echo ' <td width="137" height="1"></td>';
           echo ' <td width="290" height="1">';

           echo " <button type ='button' id='btnLookupPatient'>Lookup Patient</button>
                  <button type ='button' id='btnNewPatient'>Insert Patient</button></td> ";

           echo '</tr>';
         }
       ?>
       
       <tr>
         <td width="137" height="28">Driver</td>
         <td width="290" height="28">

           <?php
            if ($status == 'D')
              echo '<b>'.get_driver($values[APP_DRIVER]).'</b></td>';
            else
            {
              echo '<select size="1" name="cobxDriver" id="cobxDriver" class="roundedit" tabindex="2">';

               fillcombo("SELECT DRIVER_KEY, FIRSTNAME ||' '|| SURNAME
                          FROM DRIVER WHERE REGION_KEY =".$region_key." ORDER BY SURNAME",
                $values[APP_DRIVER], 30, 'T');

              echo '</select></td>';
            }
           ?>
         </tr>


       <?php
       
       if ($trialdate == 'F')
       {
         echo '<tr>';
         echo '<td width="137" height="28">Status</td>';
         echo '<td width="290" height="28">';
         
            if ($status == 'D')
              echo '<b>'.get_status($values[APP_STATUS]).'</b></td>';
            else
            {     
              echo '<select size="1" name="cobxDiaryStatus" id="cobxDiaryStatus" class="roundedit" tabindex="2">';
            
               fillcombo("SELECT DIARYSTATUS_KEY, DIARYSTATUS_DESC FROM DIARYSTATUS ORDER BY DIARYSTATUS_DESC",
                $values[APP_STATUS], 30);

              echo '</select></td>';
            }
         echo '</tr>';
       }
       ?>

       <tr>
         <td width="137" height="37" valign="top">Notes</td>
         <td width="290" height="37">
           <?php 
            if ($status == 'D') 
              echo '<b>'.$values[APP_NOTE].'</b></td>';
            else
              echo '<textarea rows="4" name="mmoDiaryNotes" id="mmoDiaryNotes" cols="36"  maxlength="80">'.$values[APP_NOTE].'</textarea>';
           ?>  

         </td>
         </tr>

     </table>
     
       <input type="hidden" name="appointmentstatus" id="appointmentstatus" value = '<?php echo $status ?>'>
       <input type="hidden" name="diary_key" id="diary_key" value = '<?php echo $diarykey?>'>
       <input type="hidden" id="edtTempPatient" name="edtTempPatient"  ></td>
       <input type="hidden" name="edtTempPatientCell" id="edtTempPatientCell" ></td>
       <input type="hidden" name="trialdateTF" id="trialdateTF" value = '<?php echo $trialdate ?>'>

       <?php 
          if ($status == 'D') 
          {
            echo '<input type="hidden" id="edtAccount_Key" name="edtAccount_Key" value ='.$values[APP_ACCOUNT].'>';
            echo '<input type="hidden" id="Patient_Key" name="Patient_Key" value ='.$values[APP_PATIENT].'>';
            echo '<input type="hidden" id="cobxDiaryStatus" name="cobxDiaryStatus" value ='.$values[APP_STATUS].'>';
            echo '<input type="hidden" id="edtTempPatient" name="edtTempPatient" value ='.$values[APP_TEMPPAT].'>';
            echo '<input type="hidden" id="edtTempPatientCell" name="edtTempPatientCell" value ='.$values[APP_TEMPPATCELL].'>';
            echo '<input type="hidden" id="mmoDiaryNotes" name="mmoDiaryNotes" value = '.$values[APP_NOTE].'>';
            echo '<input type="hidden" id="cobxApptRegion" name="cobxApptRegion" value ='.$values[APP_REGION_KEY].'>';
            echo '<input type="hidden" id="cobxPractitioner" name="cobxPractitioner" value ='.$values[APP_PRACTITIONER].'>';
            echo '<input type="hidden" id="cobxDriver" name="cobxDriver" value = -1>';
            echo '<input type="hidden" id="hideApptDate" name="hideApptDate" value = "1899-12-30"';
            echo '<input type="hidden" id="cobxApptTime" name="cobxApptTime" value = "04:00"';
            echo '<input type="hidden" id="cobxCourtHouse" name="cobxCourtHouse" value ='.$values[APP_COURTHOUSE].'>';
            echo '<input type="hidden" id="trialdateTF" name="trialdateTF" value ='.$values[APP_TRIALDATE].'>';
          }
          else
          if ($status == 'U') 
          {
            if ($_SESSION['diaryaccount'] <> '') 
            {
              echo '<input type="hidden" id="edtAccount_Key" name="edtAccount_Key" value ='.$_SESSION['diaryaccount'].'>';
              echo '<input type="hidden" id="Patient_Key" name="Patient_Key" value ='.$_SESSION['diarypatient'].'>';
            }
            else  
            if ($values[APP_ACCOUNT] <> '')
            {
              echo '<input type="hidden" id="edtAccount_Key" name="edtAccount_Key" value ='.$values[APP_ACCOUNT].'>';
              echo '<input type="hidden" id="Patient_Key" name="Patient_Key" value ='.$values[APP_PATIENT].'>';
            } 
          }  
          else
          if ($status == 'I') 
          {
            echo '<input type="hidden" id="edtAccount_Key" name="edtAccount_Key" value ='.$_SESSION['diaryaccount'].'>';
            echo '<input type="hidden" id="Patient_Key" name="Patient_Key" value ='.$_SESSION['diarypatient'].'>';
          }  

       ?>
       

       </center>
    <?php
   
  }



  
  function editdelete_appointment($action, $key)
  {
        if($conn=db_connect())
        {
          $query = "SELECT D.DIARY_KEY, D.REGION_KEY, D.ACCOUNT_KEY, D.PATIENT_KEY, D.PRACTITIONER_KEY,
                         D.DIARYSTATUS_KEY, D.DIARY_NOTE, D.DIARY_DATE, D.DIARY_FROMTIME, D.DIARY_TOTIME,
                         P.FIRSTNAME, P.SURNAME, D.TEMPPATIENT, D.TEMPPATIENTCELLNUMBER, D.DRIVER_KEY, D.COURTHOUSE_KEY, D.TRIALDATE
                         FROM DIARY D
                         LEFT OUTER JOIN PATIENT P ON P.ACCOUNT_KEY = D.ACCOUNT_KEY
                           AND P.PATIENT_KEY = D.PATIENT_KEY
                         WHERE D.DIARY_key = $key; ";
                            
          
          $result = ibase_query($conn, $query); 

          if (!$result) 
          {
            echo "Patient could not be found."; 
            echo $query;
            exit; 
          }
          else
          {
            $patientvalues = array();
            $numcol = ibase_num_fields($result);
         
            while ($row=ibase_fetch_row ($result))
            {
              for($i=0; $i <$numcol; $i++)
                 $patientvalues[$i] = $row[$i];
            } 
  
            if ($action == 'delete')
               display_appointment_form('D', $patientvalues, $patientvalues[APP_REGION_KEY], '', $patientvalues[APP_TRIALDATE]);
            else
               display_appointment_form('U', $patientvalues, $patientvalues[APP_REGION_KEY], '', $patientvalues[APP_TRIALDATE]);
             
          }  
          
 //         ibase_close($conn);
        }  
  }
    

    if(!check_admin_user())
    {
     echo "You do not seem to be logged in.";
     exit;
    }

    $action       = $_GET['action'];
    $key          = $_GET['id1'];
    $region_key   = $_GET['id2'];
    $diarydate    = $_GET['id3'];
    $trialdate    = $_GET['id4'];

    switch ( $action )
    {
    case 'delete':
    {
      editdelete_appointment($action, $key);
      break;
    }
    case 'edit' :
    {
      editdelete_appointment($action, $key);
      break;
    }
    case 'new' :
    {
      display_appointment_form('I','', $region_key, $diarydate, $trialdate);
      break;
    }
  }


?>
