<?php 
// Include main file
include_once('../libs/main.php');
// Check admin Login
include_once('checkLogin.php');
// Logical section of page
$practiceObj =  new  practice();
$pmsAppointmentObj = new pmsAppointment();
if(isset($_REQUEST['office_id']) && $_REQUEST['office_id']!=""){
    $practiceObj = new practice();
    $where =array('practice_office_id='=>$_REQUEST['office_id']);
    $arg = array('where'=>$where);
    $practiceDetails = $practiceObj->FromFields($arg);
    if($practiceDetails){
            // $pmsAppointmentObj = new pmsAppointment();
            // $where =array('pmsAppointment_practice_id='=>$practiceDetails->practice_office_id);
            // $data =array('where'=>$where);
            // $exist = $pmsAppointmentObj->FromFields($data);
            // if($exist){
            //    header("Location:pmsAppointmentlist.php?failedMsg=Appointments already fetched from PMS for this practice.");
            //    exit;
            // }
 
        $pmsAppointmentObj = new pmsAppointment();
        $arg =array(
          "request_key"=>$practiceDetails->practice_request_key,
          "office_id"=>$practiceDetails->practice_office_id,
          "secret_key"=>$practiceDetails->practice_secret_key,
          "clinic_id"=>$practiceDetails->practice_xcare_id,
          "startdate"=>date("Y-m-d"),
          "endpoint"=>$practiceDetails->practice_endpoint
        );
        $status  = $pmsAppointmentObj->pullAppointments($arg);
        if($status){
            header("Location:pmsAppointmentlist.php?successMsg=Successfully pulled all appointment for ".$practiceDetails->practice_office_id);
            exit;
        }else{
             header("Location:pmsAppointmentlist.php?successMsg=Successfully pulled all appointment for ".$practiceDetails->practice_office_id);
            exit;
        }
    }else{
        header("Location:pmsAppointmentlist.php?failedMsg=Error Occur.");
        exit;
    }
}


if(isset($_REQUEST['action']) && $_REQUEST['action']!=''){
    
    if($_REQUEST['action']=="delete_all"){

        $chk_del = implode(",",$_POST['check']);
        
        /*$patientdata = " <b>Delete Id</b>: "." ".$chk_del;
        $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,$patientdata);*/
        
        $rs = $pmsAppointmentObj->deleteManyRecords($_POST['check']);
        $successMsg = base64_encode(RECORD_ALL_DELETE);
    }
}

/*if (isset($_REQUEST['act']) && $_REQUEST['act']=='load' && isset($_REQUEST['client_office_id']) 
    && $_REQUEST['client_office_id']!=''){*/
if (isset($_REQUEST['act']) && $_REQUEST['act']=='load'){
    //echo 'dfsdfa';exit; 
    //echo $_REQUEST['client_office_id'];exit;
    $records = $_REQUEST['length'];
    $start=0;
    if(isset($_GET['start']) && $_GET['start']!='0'){
        $page = $_GET['start'];
    }
    $start=($page-1)*$limit;
    $limit = array('start'=>$_GET['start'],'record'=>$records);
    
    $where = " 1=1 ";
    /*if(isset($_REQUEST['client_office_id']) && $_REQUEST['client_office_id']!=""){
         $client_office_id = $_REQUEST['client_office_id'];
         $where = " pp.pmsPatient_practice_id='".$client_office_id."' AND p.pmsAppointment_practice_id='".$client_office_id."' AND pd.pmsProvider_office_id='".$client_office_id."' "; 
    }*/
    
    if(isset($_REQUEST['serial_no']) && $_REQUEST['serial_no'] != "")
    {
        $where .= " AND  pmsAppointment_sr_no = '".$_REQUEST['serial_no']."' ";
    }
    if (isset($_REQUEST['practice_id']) && $_REQUEST['practice_id']!=""){
        $where .= " AND  pmsAppointment_practice_id = '".$_REQUEST['practice_id']."' ";
    }
    if (isset($_REQUEST['provider_id']) && $_REQUEST['provider_id']!=""){
        $where .= " AND  pmsAppointment_provider_id = '".$_REQUEST['provider_id']."' ";
    }
    if (isset($_REQUEST['start_date']) && $_REQUEST['start_date']!="" && isset($_REQUEST['end_date']) && $_REQUEST['end_date']!="" ){
        $where .= " AND  pmsAppointment_date BETWEEN '".$_REQUEST['start_date']."' AND '".$_REQUEST['end_date']."' ";
    }
    
    if (isset($_REQUEST['start_time']) && $_REQUEST['start_time']!="" && isset($_REQUEST['end_time']) && $_REQUEST['end_time']!="" )
    {
        $cstart_time = date("H:i",strtotime($_REQUEST['start_time']));
        $cend_time = date("H:i",strtotime($_REQUEST['end_time']));
        
        $where .= " AND  pmsAppointment_time BETWEEN '".$cstart_time."' AND '".$cend_time."' ";
    }
    
    if (isset($_REQUEST['status_data']) && $_REQUEST['status_data']!=""){
        $where .= " AND  pmsAppointment_status = '".$_REQUEST['status_data']."' ";
    }

    if(isset($_REQUEST['pmsappoinment_clinic']) && $_REQUEST['pmsappoinment_clinic'] != '')
    {
        $where .= " AND pmsAppointment_clinic_id = '".$_REQUEST['pmsappoinment_clinic']."'";
    }

    if(isset($_REQUEST['pmspatient_name']) && $_REQUEST['pmspatient_name'] != '')
    {
        $fullname = str_replace(' ', '', $_REQUEST['pmspatient_name']);

        //$where .=" AND CONCAT(pmsPatient_fname,'',pmsPatient_lname) LIKE '%".$fullname."%' ";
        $where .=" AND ( pmsPatient_fname LIKE '%".$_REQUEST['pmspatient_name']."%' OR CONCAT(pmsPatient_fname,'',pmsPatient_lname) LIKE '%".$fullname."%' OR pmsPatient_lname LIKE '%".$_REQUEST['pmspatient_name']."%') ";
    }
    if(isset($_REQUEST['appointmnet_operatory']) && $_REQUEST['appointmnet_operatory'] != '')
    {
        $where .= " AND pmsAppointment_operatory = '".$_REQUEST['appointmnet_operatory']."'";
    }
    if(isset($_REQUEST['pmspatient_id']) && $_REQUEST['pmspatient_id'] != '')
    {
        $where .= " AND pmsAppointment_patient_id = '".$_REQUEST['pmspatient_id']."'";
    }
    if (isset($_REQUEST['pmspatient_xcare_id']) && $_REQUEST['pmspatient_xcare_id']!=""){
        if(is_numeric($_REQUEST['pmspatient_xcare_id']))
        {
            $where .= " AND  pmsAppointment_xappointmentId = '".$_REQUEST['pmspatient_xcare_id']."' ";    
        }
        if($_REQUEST['pmspatient_xcare_id'] == 'IS NULL')
        {    
            $where .= " AND  (`pmsAppointment_xappointmentId` IS NULL OR `pmsAppointment_xappointmentId` = '') ";
        }
        
    }
    if(isset($_REQUEST['pmsappointment_id']) && $_REQUEST['pmsappointment_id'] != '')
    {
        $where .= " AND pmsAppointment_id = '".$_REQUEST['pmsappointment_id']."'";
    }
    if(isset($_REQUEST['pmsAppointment_verified']) && $_REQUEST['pmsAppointment_verified']!= '')
    {
        $where .= " AND pmsAppointment_verified = '".$_REQUEST['pmsAppointment_verified']."'";
    }

    if (isset($_REQUEST['search']['value']) && $_REQUEST['search']['value']!=""){
        $where .= " AND ( pmsPatient_fname LIKE '%".$_REQUEST['search']['value']."%' OR pmsPatient_lname LIKE '%".$_REQUEST['search']['value']."%'  OR pmsPatient_email LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_sr_no LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_patient_id LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_practice_id LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_patient_id LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_time LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_length LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_amount LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_operatory LIKE '%".$_REQUEST['search']['value']."%' OR pmsProvider_type LIKE '%".$_REQUEST['search']['value']."%' OR pmsProvider_office_id LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_id LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_provider_id LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_date LIKE '%".$_REQUEST['search']['value']."%' OR pmsAppointment_verified LIKE '%".ucfirst($_REQUEST['search']['value'])."%' )";
    }    
    $orderFields = array('pmsAppointment_id','pmsPatient_fname','pmsAppointment_provider_id','pmsAppointment_date');
    
    // Array of order by 
    $orderby=array();
    if (isset($_REQUEST['order']['0']['column']) && $_REQUEST['order']['0']['column']!=""){
        $orderby = array(" ".$orderFields[$_REQUEST['order']['0']['column']]." ".$_REQUEST['order']['0']['dir']);
    }else{
        $orderby = array(" pmsAppointment_date DESC ");
    }
    $fields  = array('c.*','p.*','pp.*','pd.*','ap.*');
    $tables = array('tbl_pmsPatient pp','tbl_clinic c','tbl_pmsProvider pd','tbl_appointment ap');
    /*$jfields = array('p.pmsAppointment_patient_id = pp.pmsPatient_patient_id','c.clinic_id = p.pmsAppointment_clinic_id','p.pmsAppointment_provider_id = pd.pmsProvider_sikka_id');*/
    $jfields = array('p.pmsAppointment_patient_id = pp.pmsPatient_patient_id AND p.pmsAppointment_clinic_id = pp.pmsPatient_clinic_id','c.clinic_id = p.pmsAppointment_clinic_id','p.pmsAppointment_provider_id = pd.pmsProvider_sikka_id AND p.pmsAppointment_clinic_id = pd.pmsProvider_clinic_id','ap.appointment_id=p.pmsAppointment_xappointmentId');
    $jtype   = array("INNER","INNER","LEFT","LEFT");
    $data    = array('fields' => $fields, 'where' => $where,  'joinTables' =>$tables, 'joinFields' =>$jfields, 'joinTypes' => $jtype, 'orderBy'=>$orderby, 'limit' => $limit);


    $pmsAppointmentDetails = $pmsAppointmentObj->getAllRecords($data);
    $recordsTotal   =   $pmsAppointmentObj->getAllCount($data);

        
    if ($pmsAppointmentDetails && count($pmsAppointmentDetails)>0){
        foreach ($pmsAppointmentDetails as $key => $pmsAppointment){

            /*$clinicObj = new clinic();
            $where =array('clinic_id='=>$pmsAppointment->pmsAppointment_clinic_id);
            $data =array('where'=>$where);
            $clinicexist = $clinicObj->FromFields($data);
            $clinicDetail = '';
            if($clinicexist)
            {
                $clinicDetail .= "<b>ClinicId :</b>".$clinicexist->clinic_id."<br/><b>UniqueId : </b>".$clinicexist->clinic_unique_id."<br/><b>ClinicName :</b>".$clinicexist->clinic_name."<br/><b>Phone</b>".$clinicexist->clinic_phone."<br/><b>Email</b>".$clinicexist->clinic_email;
            }*/

            if(is_null($pmsAppointment->pmsAppointment_xappointmentId) && $pmsAppointment->pmsAppointment_xappointmentId == '')
            {
                $all_checkbox = '<input type="checkbox" name="check[]" id="check[]" value="'.$pmsAppointment->pmsAppointment_id.'" class="check_class" />';
            }else{
                $all_checkbox = '';
            }
            $allapp_metdata = '';
            if($pmsAppointment->pmsAppointment_xappointmentId != '')
            {
                $metadata =json_decode($pmsAppointment->appointment_metadata,1);
                $appointmentStatus = $metadata['pms']['appointmentStatus'];
                $appointmentconfirmation = $metadata['appointment']['confirmation']['status'];
                $appointmentFloating =$metadata['appointment']['floating'];
                if($appointmentFloating == true)
                {
                    $allapp_metdata = ' (floating)';
                }else if($appointmentconfirmation != ''){
                    $allapp_metdata = "(".$appointmentconfirmation.")";
                }    
            }
            

            $response[] = array(
                    //.'<br/><b>SikkaId : </b>'.$pmsAppointment->pmsAppointment_patient_id
                    $all_checkbox,
                    "<b>PMS Appointment ID : </b>".$pmsAppointment->pmsAppointment_id."<br/><b>Sr No : </b>".$pmsAppointment->pmsAppointment_sr_no."<br/><b>Clinic : </b>".$pmsAppointment->clinic_name."<br/><b>OfficeId : </b>".$pmsAppointment->pmsAppointment_practice_id."<br/><b>PMS PatientId : </b>".$pmsAppointment->pmsAppointment_patient_id."<br/><b>Xcare Id : </b>".$pmsAppointment->pmsAppointment_xappointmentId."<br/><b>Xcare External Id : </b>".$pmsAppointment->appointment_unique_id,
                    $pmsAppointment->pmsPatient_fname." ".$pmsAppointment->pmsPatient_lname,
                    //$pmsAppointment->pmsPatient_email.'<br/>',
                    
                    //date("Y-m-d",strtotime($pmsAppointment->pmsAppointment_date))." ".$pmsAppointment->pmsAppointment_time,
                    "<b>ProviderId : </b>".$pmsAppointment->pmsAppointment_provider_id."<br/><b>Full Name : </b>".$pmsAppointment->pmsProvider_fname." ".$pmsAppointment->pmsProvider_lname."<br/><b>ProviderType : </b>".$pmsAppointment->pmsProvider_type."<br/><b>OfficeId : </b>".$pmsAppointment->pmsProvider_office_id, 

                    $pmsAppointment->pmsAppointment_date,

                    "<b>Date : </b>".$pmsAppointment->pmsAppointment_date."<br/><b>Time : </b>".$pmsAppointment->pmsAppointment_time."<br/><b>Length : </b>".$pmsAppointment->pmsAppointment_length."<br/><b>Amount : </b>".$pmsAppointment->pmsAppointment_amount."<br/><b>Operatory : </b>".$pmsAppointment->pmsAppointment_operatory,


                    "<b>Schedule : </b>".$pmsAppointment->pmsAppointment_schedule."<br/><b>Cancelled : </b>".$pmsAppointment->pmsAppointment_cancelled.'<br/><b>Verified : </b>'.$pmsAppointment->pmsAppointment_verified.'<br/><b>Changed : </b>'.$pmsAppointment->pmsAppointment_changed.'<br/><b>Amount : </b>'.$pmsAppointment->pmsAppointment_amount, 
                    "<b>PMS: </b>".$pmsAppointment->pmsAppointment_status."<br/><b>Xcare: </b>".$pmsAppointment->appointment_status.$allapp_metdata,
             );
        }
        $result=array('recordsFiltered'=>$recordsTotal,'recordsTotal'=>$recordsTotal,'data'=>$response);
    }else{
        $result=array('recordsFiltered'=>0,'recordsTotal'=>0,'data'=>array());
    }
    echo json_encode($result);
    exit;
}

/*$practiceObj = new practice();

$fields = array('p.*');
$practicArg    = array('fields'=>$fields);
$allClinic = $practiceObj->getAllRecords($practicArg);*/

// Include Template 
include_once('../libs/routs.php');
?>