<?php 
include('accesscheck2.php');
require_once('Connections/courier.php'); 
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_courier, $courier);

if ($action == 'save_new_schedule') {
    $doctors_name = mysql_real_escape_string($_POST['doctors_name']);
    $event_title = mysql_real_escape_string($_POST['event_title']);
    $start_date = mysql_real_escape_string($_POST['schedule_start_date']);
    $start_time = date('H:i', strtotime($_POST['start_time_picker']));
    $end_time = date('H:i', strtotime($_POST['end_time_picker']));
    $repeat_interval = mysql_real_escape_string($_POST['repeat_interval']);
    $repeat_every = mysql_real_escape_string($_POST['repeat_frequency']);
    $repeat_frequency_text = mysql_real_escape_string($_POST['repeat_frequency_text']);
    $ends_on_text = mysql_real_escape_string($_POST['ends_on_text']);
    $end_date = mysql_real_escape_string($_POST['ends_on_date']);
    $repeat_on = $_POST['repeat_on'];
    
    if(empty($start_date)){$start_date = date('Y-m-d');}
    if(empty($end_date)){$end_date = date('Y-m-d', strtotime('+ 1 WEEKS', $start_date));}

    if($repeat_interval=='0'){$text = 'D';}
    if($repeat_interval=='2'){$text = 'W';}
    if($repeat_interval=='3'){$text = 'M';}
    if($repeat_interval=='4'){$text = 'Y';}
    
    $week = array("Sunday" => 0,"Saturday" => 6,"Friday" => 5,"Thursday" => 4,"Wednesday" => 3,"Tuesday" => 2,"Monday" => 1);
    foreach ($repeat_on as $repeats) {
             $ron = $ron.$week[$repeats].',';
    }
    $ron = substr($ron, 0,-1);
    $ronS=explode(',', $ron);
    foreach($ronS as $ronS) {
    $res[]= $ronS;
    }
 
    if($repeat_interval == '2') {
       $curday= 7-date("N",strtotime($start_date));
       foreach ($res as $key=>$val) {
            $ncount= $res[$key]-7;
            $nc=$ncount+$curday;
            $cday= date('Y-m-d',strtotime('+'.$nc.' day',strtotime($start_date)));
            $datetime = new DateTime("$cday");
            if ( $datetime->format("w") >= 0 )
             {
              if(strtotime($start_date) <= strtotime($cday)){}
              else{$cday = date('Y-m-d',strtotime('+7 day',strtotime($cday)));}
              
            if (!empty($cday) && !empty($end_date)) {
                    $begin = new DateTime($cday);
                    $end = new DateTime($end_date);
                    $end = $end->modify('+' . $repeat_every . ' ' . $repeat_frequency_text);
                    $interval = new DateInterval('P' . $repeat_every . $text);
                    $daterange = new DatePeriod($begin, $interval, $end);
                    $max = mysql_fetch_assoc(mysql_query("SELECT MAX(parent_id)+1 as parent_id FROM scheduler", $courier));
                    foreach ($daterange as $date) {
                        $s = $date->format("Y-m-d");
                        mysql_query("INSERT INTO scheduler(doctor_id, parent_id, title, start_date, start_time, end_date, end_time) VALUES('$doctors_name','" . $max['parent_id'] . "','$event_title','$s','$start_time','$s','$end_time')", $courier);
                    }
                }
            }   
       }
    } else {     
    if (!empty($start_date) && !empty($end_date)) {
        $begin = new DateTime($start_date);
        $end = new DateTime($end_date);
        $end = $end->modify( '+'.$repeat_every.' '.$repeat_frequency_text );
        $interval = new DateInterval('P' . $repeat_every . $text);
        $daterange = new DatePeriod($begin, $interval, $end);
        $max = mysql_fetch_assoc(mysql_query("SELECT MAX(parent_id)+1 as parent_id FROM scheduler", $courier));
        foreach ($daterange as $date) {
            $s = $date->format("Y-m-d");
            mysql_query("INSERT INTO scheduler(doctor_id, parent_id, title, start_date, start_time, end_date, end_time) VALUES('$doctors_name','".$max['parent_id']."','$event_title','$s','$start_time','$s','$end_time')", $courier);
        }
    }
}
}

if ($action == 'search_patients_appointment') {
    $search_text = mysql_real_escape_string($_POST['search_text']);
    $search_by = mysql_real_escape_string($_POST['search_by']);
    if(!empty($search_text) && !empty($search_by)){
    if ($search_by == 'patient_id') {
        $qry = mysql_query("SELECT id, surname, othernames, card_number, old_card_no, picpath,tel,insurance_no1,insurance_company1 FROM patient_information WHERE (card_number='$search_text' OR old_card_no='$search_text') ORDER BY surname,othernames LIMIT 100", $courier);
    } else if ($search_by == 'surname') {
        $qry = mysql_query("SELECT id, surname, othernames, card_number, old_card_no, picpath,tel,insurance_no1,insurance_company1 FROM patient_information WHERE surname LIKE '$search_text%' ORDER BY surname,othernames LIMIT 100", $courier);
    } else if ($search_by == 'othername') {
        $qry = mysql_query("SELECT id, surname, othernames, card_number, old_card_no, picpath,tel,insurance_no1,insurance_company1 FROM patient_information WHERE othernames LIKE '%$search_text%' ORDER BY surname,othernames LIMIT 100", $courier);
    }

    if(mysql_num_rows($qry) > 0){
    $i=1;
    while ($row = mysql_fetch_assoc($qry)) {
        $picpath=$row['picpath']; 
        if(!$picpath){ 
                    if($row['insurance_no1']){
                    $inspicpath=getpicpath($row['insurance_company1']);
                    if($inspicpath){
                    $member_id=preg_replace("/[^0-9]/","",$row['insurance_no1']);
                    $picpath=$inspicpath."/".ltrim($member_id,0).".jpg";
                    }else{
                    $picpath="images/profile.gif";		
                    }
                    }else{
                    $picpath="images/profile.gif";	
                    }
										  }
        ?>
<div class="col-md-12" id="patient_details_<?php echo $i;?>" style="height: 61px;top:50px">
                                                <div class="todo-tasklist" onclick="selectPatientAppointment('<?php echo $row['id'];?>')">
                                                    <div id="tasklist_<?php echo $row['id'];?>" class="todo-tasklist-item todo-tasklist-item-border-green" id="<?php echo $row['id'];?>">
                                                        <i class="icon-ok todo-userpic pull-right" style="margin-top:10px;display: none;"></i>
                                                        <img class="todo-userpic pull-left" src="<?php echo $picpath;?>" width="30px" height="30px">
                                                        <div class="todo-tasklist-item-title" id="<?php echo $row['id'].'@@@'.$row['card_number'].'@@@'.$row['surname'].' '.$row['othernames'];?>">
                                                            <?php echo $row['surname'].' '.$row['othernames'];?> - (<?php echo $row['card_number'];?>)
                                                            <div class="todo-tasklist-controls pull-right">
                                                                <label for="urgency_Normal_<?php echo $i;?>" class="todo-tasklist-badge badge danger badge-roundless badge-danger">Appointment Booking</label>
                                                            </div>
                                                        </div>

                                                    </div>
                                                </div>
       </div>
    <?php $i++; }
    }else{ ?>
        <div class="col-md-12" style="height: 60px;">
                                                <div class="todo-tasklist">
                                                    <div class="todo-tasklist-item todo-tasklist-item">
                                                        <div class="todo-tasklist-item-title" style="text-align: center;">
                                                           Oops...No Results Found.
                                                        </div>

                                                    </div>
                                                </div>
       </div>
    <?php }
  }
}