<?php
include_once('common.php');
?>
<?php
            // Create an instance of MyOpticianWsdlService
            $opticianService = new MyOpticianWsdlService('http://87.127.13.154:899/DiaryWebService.svc', $optician_id);
            
            // Get site info
            $siteInfo = $opticianService->getSiteInfo($optician_id, $password);
            
            // Get optician details
            $opticianDetails = $opticianService->getOpticianDetails($optician_id);
            
            $optician_name = $opticianDetails->getName();
            $optician_address = $opticianDetails->getAddress();
            $optician_phone = $opticianDetails->getPhone();
            $optician_logo = $opticianDetails->getLogo();
            
            // Get appointments
            $appointments = $opticianService->getAppointments($optician_id);
            

?>
<!DOCTYPE html>
<html lang="en-US" class="scheme_original" style="margin-top:0px !important;">
   <head>
      <title> Book Appointment Form </title>
      </style>
      <meta name='robots' content='max-image-preview:large' />
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
      <meta name="format-detection" content="telephone=no">
      <link rel="profile" href="//gmpg.org/xfn/11" />
      <link rel='dns-prefetch' href='//fonts.googleapis.com' />
      <link rel='dns-prefetch' href='//s.w.org' />
      <link rel='stylesheet' id='optometry-main-style-css'  href='style.css' type='text/css' media='all' />
      

   </head>
   <body class="page-template-default page page-id-1836 logged-in admin-bar no-customize-support theme-optometry woocommerce-no-js optometry_body body_style_wide body_filled theme_skin_optometry article_style_stretch layout_single-standard template_single-standard scheme_original top_panel_show top_panel_above sidebar_hide sidebar_outer_hide preloader wpb-js-composer js-comp-ver-6.4.1 vc_responsive">
      <div class="body_wrap">
         <div class="page_wrap">
            </div>
            <div class="top_panel_title top_panel_style_3  title_present breadcrumbs_present scheme_original">
               <div class="top_panel_title_inner top_panel_inner_style_3  title_present_inner breadcrumbs_present_inner">
                  <div class="content_wrap">
                     <h1 class="page_title">Appointment Booking</h1>
                     
                  </div>
               </div>
            </div>



            <div class="page_content_wrap page_paddings_no">
               <div class="content_wrap">
                  <div class="content">
                     <article class="itemscope post_item post_item_single post_featured_default post_format_standard post-1836 page type-page status-publish hentry" itemscope itemtype="//schema.org/Article">
                        <section class="post_content" itemprop="articleBody">
                           <form action="book-appointment.php" id="addAppointmentFrom" method="post">
                              <div class="vc_row wpb_row vc_row-fluid vc_custom_1615448114233" id="step1">
                                 <?php if(isset($_GET['status']) && $_GET['status']=='success'){ ?>
                                    <div class="alert alert-success alert-dismissible fade in show" role="alert">
                                      Your appointment book successfull
                                      <!-- <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                      </button> -->
                                    </div>
                                 <?php } ?>
                                 <?php if(isset($_GET['status']) && $_GET['status']=='failed'){ ?>
                                    <div class="alert alert-danger alert-dismissible fade in show" role="alert">
                                      Something Went Wrong...
                                      <!-- <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                      </button> -->
                                    </div>
                                 <?php } ?>
                                 <div class="wpb_column vc_column_container vc_col-sm-12">
                                    <div class="vc_column-inner">
                                       <div class="wpb_wrapper">
                                          <div class="wpb_text_column wpb_content_element">
                                             <div class="wpb_wrapper">
                                                <div class="appointinfo">
                                                   <div class="personal-info">
                                                      <h4 style="margin-top:0; margin-bottom: 8px;">Select a date and time</h4>
                                                   </div>
                                                   <div style="overflow:hidden;">
                                                      <div class="form-group">
                                                         <div class="row">
                                                            <div class="col-md-6">
                                                               <div class="row">
                                                                  <?php $appointments = $app_fun->getAppointments(); 
                                                                  if($appointments == ""){
                                                                     
                                                                     echo "Error, no DB connection";
                                                                     exit();
                                                                  }

                                                                     if($appointments){
                                                                        $slot = explode('|', $appointments);
                                                                     }else{
                                                                        $slot = array();
                                                                     }
                                                                     $timeslot = array();
                                                                     $start_date = '';
                                                                     $available_date = array();
                                                                     $cdate = date('d/m/Y',strtotime('+1 days'));
                                                                     if($slot){
                                                                        foreach ($slot as $key => $value) {
                                                                           if($value!=''){
                                                                              $date = explode(' ', $value);
                                                                              if($start_date==''){
                                                                              	$cdate = $date[0];
                                                                                $start_date = str_replace('/', '-', $date[0]);
                                                                              }
                                                                              if(!in_array($date[0], $available_date)){
                                                                                 array_push($available_date, $date[0]);
                                                                              }
                                                                              if(!in_array($date[1], $timeslot) && $date[0]==$cdate){
                                                                                 array_push($timeslot, $date[1]);
                                                                              }
                                                                           }
                                                                        }
                                                                     }
                                                                     if($available_date){
                                                                        $available = implode(',', $available_date);
                                                                     }else{
                                                                        $available = '';
                                                                     }
                                                                  ?>
                                                                  <!-- <div id="datetimepicker1"></div> -->
                                                                  <div class="col-md-12">
                                                                     <div id="calendar"></div>
                                                                  </div>
                                                                  <div class="col-md-12">
                                                                     <ul class="legend">
                                                                        <li><strong></strong> Available</li>
                                                                        <li><strong></strong> Fully Booked / Not yet released</li>
                                                                     </ul>
                                                                  </div>
                                                               </div>
                                                            </div>
                                                            <div class="col-md-1"></div>
                                                            <div class="col-md-5">
                                                               <h4 style="margin-top:0; margin-bottom: 20px;" id="selectdate"><?php echo date('D d F Y',strtotime($start_date)); ?></h4>
                                                               <div class="row" id="timeslots">
                                                                  <?php if($timeslot){ foreach ($timeslot as $key => $value){
                                                                     $formattime = date("h:i A", strtotime($value));
                                                                  ?>
                                                                     <div class="col-md-4 text-center">
                                                                        <ul class="time_select">
                                                                             <li>
                                                                                 <input type="radio" <?php echo ($key==0)?'checked':''; ?> id="radio<?php echo $key; ?>" name="appointment_time" value="<?php echo $value; ?>">
                                                                                 <label for="radio<?php echo $key; ?>"><?php echo $formattime; ?></label>
                                                                             </li>
                                                                        </ul>
                                                                     </div>
                                                                  <?php } } ?>
                                                               </div>
                                                            </div>
                                                         </div>
                                                         <div class="row">
                                                            <div class="col-md-12" style="margin-top:10px;">
                                                               <a href="javascript:void(0);" class="btn btn-default pull-left" disabled>Back</a>
                                                               <a href="javascript:void(0);" class="btn btn-success nextAction pull-right" style="color:#fff;" data-step="1">Next</a>
                                                            </div>
                                                         </div>
                                                      </div>
                                                   </div>
                                                </div>
                                             </div>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                              <div class="vc_row wpb_row vc_row-fluid vc_custom_1615448114233" id="step2" style="display:none;">
                                 <div class="wpb_column vc_column_container vc_col-sm-7 col-md-7">
                                    <div class="vc_column-inner">
                                       <div class="wpb_wrapper">
                                          <div class="wpb_text_column wpb_content_element">
                                             <div class="wpb_wrapper">
                                                <div class="appointinfo">
                                                   <div class="personal-info">
                                                      <h4 style="margin-top:0; margin-bottom: 8px;">Personal Information</h4>
                                                   </div>
                                                   <input type="hidden" id="appointment_date" name="appointment_date">
                                                   <!-- <div class="form-group">
                                                   <label>Appointment Type (Select all that apply)</label>
                                                      <div class="form-check" id="appointmentTypes">
                                                         
                                                      </div>
                                                   </div>
                                                   -->
                                                   <div class="form-group">
                                                      <select id="appointmentTypes" name="appointmentTypes">
                                                         <option disabled selected value> -- Select an Appointment Type -- </option>
                                                      </select>
                                                   </div>
                                                   <div class="form-group">
                                                      <label for="fname">First Name*</label>
                                                      <input type="text" id="fname" name="firstname">
                                                   </div>
                                                   <div class="form-group">
                                                      <label for="lname">Last Name*</label>
                                                      <input type="text" id="lname" name="lastname">
                                                   </div>
                                                   <div class="form-group">
                                                      <label for="Email">Email Address*</label>
                                                      <input type="email" id="email" name="email">
                                                   </div>
                                                   <div class="form-group">
                                                      <label for="mobile">Mobile Number</label>
                                                      <input type="text" id="mobile" name="mobile">
                                                   </div>
                                                   <div class="form-group">
                                                      <label for="dob">Date Of Birth </label>
                                                      <input type="date" id="dob" name="dob" class="form-control">
                                                   </div>
                                                   <div class="form-group">
                                                      <label for="postcode">Post Code</label>
                                                      <input type="text" id="postcode" name="postcode">
                                                   </div>
                                                   <div class="form-group"> 
                                                      <label for="existing_patient">Existing Patient</label>
                                                      <input type="checkbox" name="existing_patient" value="1">
                                                   </div>
                                                   <div class="form-group">
                                                      <label for="comment">Comment</label>
                                                      <textarea id="comment" name="comment" rows="3" cols="3"></textarea>
                                                   </div>
                                                </div>
                                             </div>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="wpb_column vc_column_container vc_col-sm-5 col-md-5">
                                    <div class="vc_column-inner">
                                       <div class="wpb_wrapper">
                                          <div class="wpb_text_column wpb_content_element">
                                             <div class="wpb_wrapper">
                                                <div class="confirms">
                                                   <div style="width:460px;">
                                                      <img id="OpticianLogo" src="https://www.centenaryopticians.co.uk/wp-content/uploads/2021/03/logo.jpg" style="display:block;margin-left:auto;margin-right:auto;width:90%;">
                                                   </div>

                                                   <div class="bookdetail">
                                                      <h4>Your Appointment Details</h4>
                                                      <p id="adate"></p>
                                                      <p id="atime"></p>
                                                      <p>&nbsp;</p>
                                                      <h4 id="OpticianName"></h4>
                                                      <p id="OpticianAddress"></p>
                                                      <p id="OpticianPhone"></p>
                                                      <p>&nbsp;</p>

                                                      <script>
                                                      // Set booking details to parameters in sql database
                                                      let optician_name = <?php echo json_encode($optician_name); ?>;
                                                      let optician_address = <?php echo json_encode($optician_address); ?>;
                                                      let optician_phone = <?php echo json_encode($optician_phone); ?>;
                                                      let optician_logo = <?php echo json_encode($optician_logo); ?>;
                                                      
                                                      
                                                      //set all elements on the page to the correct setting based on sql table
                                                      document.getElementById("OpticianName").innerText = optician_name;
                                                      document.getElementById("OpticianAddress").innerText = optician_address;
                                                      document.getElementById("OpticianPhone").innerText = optician_phone;
                                                      document.getElementById("OpticianLogo").src = optician_logo;

                                                      // Create dropdown depending on sql parameters
                                                      const AppointmentTypes = document.getElementById("appointmentTypes");

                                                      //Find all combinations of an array
                                                      let AppointmentNamesArray = <?php echo json_encode($AppointmentNamesArray); ?>;
                                                      let AppointmentNamesArrayAllCombos = FindAllCombinations(AppointmentNamesArray);
                                                      console.log(AppointmentNamesArrayAllCombos);

                                                      //Function that finds all combinations of an array for you
                                                      //Function that finds all combinations of an array for you
                                                      
                                                      function FindAllCombinations(arr) {
                                                         var res = [[]];
                                                         for (var i=0; i<arr.length; i++)
                                                            for (var j=i+1; j<=arr.length; j++)
                                                                  res.push(arr.slice(i, j));
                                                         let AllCombos = [];
                                                         res.forEach(element => {
                                                            if (element.length > 0) {
                                                               var appointment = element.join(' + ');
                                                               AllCombos.push(appointment)
                                                            }
                                                         })
                                                         return AllCombos;
                                                      };

                                                      //Create Dropdown option for each appointment type in the array passed from php
                                                      let AppointmentNamesArray1 = AppointmentNamesArrayAllCombos;
                                                      AppointmentNamesArray1.forEach(element => {
                                                         if (element.length > 0) {
                                                            var Appointment0 = document.createElement("option");
                                                            Appointment0.innerText = element;
                                                            Appointment0.setAttribute("value", element);
                                                            AppointmentTypes.appendChild(Appointment0);
                                                         };
                                                      });
                                                      

                                                      </script>

                                                   </div>
                                                </div>
                                             </div>
                                          </div>
                                          <div class="row">
                                             <div class="col-md-12" style="margin-top:10px;">
                                                <input type="submit" value="Confirm Booking" name="confirm_booking" class="btn btn-block">
                                             </div>
                                          </div>
                                          
                                          <div class="row">
                                             <div class="col-md-12" style="margin-top:10px;">
                                                <a href="javascript:void(0);" class="btn btn-default nextAction pull-left"  data-step="2">Back</a>
                                             </div>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                           </form>
                           <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css">
                           <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
                           <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
                           <script type="text/javascript" src="js/moment-with-locales.min.js"></script>
                           <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
                           <script src="js/bootstrap-datepicker.js"></script>
                           <link href="js/icon_fonts/css/all_icons_min.css" rel="stylesheet">
                           <link rel="stylesheet" type="text/css" href="js/date_picker.css">
                           <script>
                              var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
                              var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

                              var day_disabled = [];                              
                              var availableDates = ["<?php echo str_replace(',', '","',$available); ?>"];
                              
                              function available(date) {
                                 
                                 $mon = "0"+(date.getMonth()+1);
                                 
                                dmy = date.getDate() + "/" + ($mon).slice(-2) + "/" + date.getFullYear();

                                firstChar = dmy.split("/");
                                if(firstChar[0].length == 1){
                                    dmy = "0"+dmy;
                                }

                                if ($.inArray(dmy, availableDates) !== -1) {
                                    return true;
                                } else {
                                    return false;
                                }
                              }
                              
                              $('#calendar').datepicker({
                                 todayHighlight: true,
                                 daysOfWeekDisabled: day_disabled,
                                 //startDate: new Date(Date.parse("2021-03-17")),
                                 weekStart: 0,
                                 format: "yyyy-mm-dd",
                                 // datesDisabled: ["2019/07/20", "2017/11/21","2017/12/21", "2018/01/21","2018/02/21","2018/03/21"],
                                 beforeShowDay: available
                              }).on('changeDate', showTestDate);
                              var start_date = '<?php echo date('Y-m-d',strtotime($start_date)); ?>';
                              $('#calendar').datepicker('update', new Date(Date.parse(start_date)));

                              function showTestDate(){
                                 // Single line below changes if before date timeslots retrieved it displays old timeslots or none
                                 $('#timeslots').html("Loading...");

                                var dvalue = $('#calendar').datepicker('getFormattedDate');
                                var value = new Date($('#calendar').datepicker('getFormattedDate'));
                                var selectdate = days[value.getDay()]+" "+value.getDate()+" "+monthNames[value.getMonth()]+" "+value.getFullYear();
                                 $('#selectdate').html(selectdate);
                                // alert(selectdate);
                                 // var w = myDate(value);
                                 $.ajax({
                                     url: "available-slot.php",
                                     type: "POST",
                                     data: "date="+dvalue,
                                     success: function(result){
                                         if(result)
                                         {
                                             $('#timeslots').html(result);
                                             // console.log("Times updated")
                                         }else {
                                            console.log("Error updating timeslots");
                                         }
                                     }
                                 });
                              }

                              
                              function formatAMPM(date) {
                                var str = date.split(':');
                                var hours = str[0];
                                var minutes = str[1];
                                var ampm = hours >= 12 ? 'pm' : 'am';
                                hours = hours % 12;
                                hours = hours ? hours : 12; // the hour '0' should be '12'
                                minutes = minutes = ('0'+minutes).slice(-2); 
                                var strTime = hours + ':' + minutes + ' ' + ampm;
                                return strTime;
                              }

                              $('.nextAction').on('click', function () {
                                 var date = new Date($('#calendar').datepicker('getFormattedDate'));
                                 var adate = days[date.getDay()]+" "+date.getDate()+" "+monthNames[date.getMonth()]+" "+date.getFullYear();
                                 // alert(adate);
                                 $radiotime = $("input[type='radio'][name='appointment_time']:checked").val();
                                 var atime = formatAMPM($radiotime);
                                 //formatted = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                                 // alert(formatted);
                                 var appointment_date = date.getDate()+"/"+(date.getMonth() + 1)+"/"+date.getFullYear();
                                 $('#adate').html(adate);
                                 $('#atime').html(atime);
                                 $('#appointment_date').val(appointment_date);
                                 var step = $(this).attr('data-step');
                                 if(step==1){
                                    $('#step1').css('display','none');
                                    $('#step2').css('display','block');
                                 }else{
                                    $('#step2').css('display','none');
                                    $('#step1').css('display','block');
                                 }
                              });
                           </script>
                           <script src="formvalidation/js/formValidation.min.js"></script>
                           <script src="formvalidation/js/framework/bootstrap.min.js"></script>
                           <script>
                              $('#addAppointmentFrom').formValidation({
                                   framework: 'bootstrap',
                                   icon: {
                                       valid: 'glyphicon glyphicon-ok',
                                       invalid: 'glyphicon glyphicon-remove',
                                       validating: 'glyphicon glyphicon-refresh'
                                   },
                                   fields: {
                                       firstname: {
                                           validators: {
                                               notEmpty: {
                                                   message: 'First Name is required'
                                               },
                                               // regexp: {
                                               //     regexp: /^[^*|\":<>[\]{}`\\()';@&$]+$/,
                                               //     message: 'The First Name can only consist of alphabetical charecters'
                                               // },
                                           }
                                       },
                                       lastname: {
                                           validators: {
                                               notEmpty: {
                                                   message: 'Last Name is required'
                                               },
                                               // regexp: {
                                               //     regexp: /^[^*|\":<>[\]{}`\\()';@&$]+$/,
                                               //     message: 'The Last Name can only consist of alphabetical charecters'
                                               // },
                                           }
                                       },
                                       comment: {
                                           validators: {
                                               // notEmpty: {
                                               //     message: 'Comment is required'
                                               // },
                                               regexp: {
                                                   regexp: /^[^*|\":<>[\]{}`\\()';@&$,]+$/,
                                                   message: 'Comment can only consist of alphabetical charecters'
                                               },
                                           }
                                       },
                                       email: {
                                           validators: {
                                               notEmpty: {
                                                   message: 'Email is required'
                                               },
                                           }
                                       },
                                       mobile: {
                                           validators: {
                                               notEmpty: {
                                                   message: 'Mobile No. is required'
                                               },
                                               numeric: {
                                                   message: 'Mobile No. is a Number'
                                               },
                                               stringLength: {
                                                   min: 11,
                                                   max: 11,
                                                   message: 'The Mobile number length should 11 characters'
                                               }
                                           }
                                       },
                                       dob: {
                                           validators: {
                                               notEmpty: {
                                                   message: 'dob is required'
                                               }
                                           }
                                       },
                                       postcode: {
                                           validators: {
                                               notEmpty: {
                                                   message: 'Post Code is required'
                                               }
                                           }
                                       },
                                       'appointmentType[]': {
                                           validators: {
                                               notEmpty: {
                                                   message: 'Appointment Type is required'
                                               }
                                           }
                                       },
                                   }
                               });
                               
                           </script>
                        </section>
                        <!-- </section> class="post_content" itemprop="articleBody"> -->
                     </article>
                     <!-- </article> class="itemscope post_item post_item_single post_featured_default post_format_standard post-1836 page type-page status-publish hentry" itemscope itemtype="//schema.org/Article"> -->  
                     <section class="related_wrap related_wrap_empty"></section>
                  </div>
                  <!-- </div> class="content"> -->
               </div>
               <!-- </div> class="content_wrap"> -->      
            </div>
      </div>
      <!-- /.body_wrap -->
      <div class="custom_html_section"></div>
      <a href="#" class="scroll_to_top icon-up" title="Scroll to top"></a>
   </body>
</html>