<?php
// Include main file
include_once('../libs/main.php');
// Check admin Login
include_once('checkLogin.php');
// Logical section of page
$practiceObj =  new  practice();
$pmsPatientObj = new pmsPatient();
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){
            /*$pmsPatientObj = new pmsPatient();
            $where =array('pmsPatient_practice_id='=>$practiceDetails->practice_office_id);
            $data =array('where'=>$where);
            $exist = $pmsPatientObj->FromFields($data);
            if($exist){
               header("Location:pmsPatientlist.php?failedMsg=Patients already fetched from PMS for this practice.");
               exit;
            }*/

        $pmsPatientObj = new pmsPatient();
        $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,
          "endpoint"=>$practiceDetails->practice_endpoint
        );
        $status  = $pmsPatientObj->pullPatients($arg);
        if($status){
            header("Location:pmsPatientlist.php?successMsg=Successfully pulled all patients for ".$practiceDetails->practice_office_id);
            exit;
        }else{
             header("Location:pmsPatientlist.php?successMsg=Successfully pulled all patients for ".$practiceDetails->practice_office_id);
            exit;
        }
    }else{
        header("Location:pmsPatientlist.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 = $pmsPatientObj->deleteManyRecords($_POST['check']);
        $successMsg = base64_encode(RECORD_ALL_DELETE);
    }
}

if (isset($_REQUEST['act']) && $_REQUEST['act']=='load'){
    $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['practice_id']) && $_REQUEST['practice_id'] != "")
    {
        $where .= " AND  pmsPatient_practice_id = '".$_REQUEST['practice_id']."' ";
    }
    if (isset($_REQUEST['sikka_id']) && $_REQUEST['sikka_id']!=""){
        $where .= " AND  pmsPatient_patient_id = '".$_REQUEST['sikka_id']."' ";
    }
    if (isset($_REQUEST['email']) && $_REQUEST['email']!=""){
        $where .= " AND  pmsPatient_email = '".$_REQUEST['email']."' ";
    }
    if (isset($_REQUEST['fullname']) && $_REQUEST['fullname']!="")
    {
        //$fullname = str_replace(' ', '', $_REQUEST['fullname']);

        $patientname = preg_replace('/\s\s+/', ' ', $_REQUEST['fullname']);
        $fullname = explode(" ", $patientname);
        if(count($fullname)==2){
            $where .=" AND ((pmsPatient_fname='".($fullname['0'])."' AND  pmsPatient_lname='".($fullname['1'])."' ) OR (pmsPatient_lname='".($fullname['0'])."' AND  pmsPatient_fname='".($fullname['1'])."' ) OR (pmsPatient_fname='".(ucfirst($fullname['0']))."' AND  pmsPatient_lname='".(ucfirst($fullname['1']))."' ) OR (pmsPatient_lname='".(ucfirst($fullname['0']))."' AND  pmsPatient_fname='".(ucfirst($fullname['1']))."' ) )";
        }else{
            foreach ($fullname as $key => $f) {
                if($key==0){
                    $where .=" AND ( ";
                }
                $where .=" pmsPatient_fname LIKE '%".($f)."%' OR pmsPatient_fname LIKE '%".(ucfirst($f))."%'  OR pmsPatient_lname LIKE '%".($f)."%' OR pmsPatient_lname LIKE '%".(ucfirst($f))."%' ";
                if( ($key+1) != count($fullname) ){
                        $where .=" OR ";
                }
                if( ($key+1) == count($fullname) ){
                    $where .=" )";
                }
            }
        }
        /*$where .=" AND ( pmsPatient_fname LIKE '%".$_REQUEST['fullname']."%' OR CONCAT(pmsPatient_fname,'',pmsPatient_lname) LIKE '%".$fullname."%' OR pmsPatient_lname LIKE '%".$_REQUEST['fullname']."%') ";*/

        //$where .= " AND ('%".$fullname."%' LIKE Concat(Concat('%',pmsPatient_fname),'%') 
                   // OR '%".$fullname."%' LIKE  Concat(Concat('%',pmsPatient_lname),'%'))";
    }
    if (isset($_REQUEST['clinic_id']) && $_REQUEST['clinic_id']!=""){
        $where .= " AND  pmsPatient_clinic_id = '".$_REQUEST['clinic_id']."' ";
    }
    if (isset($_REQUEST['guarantor_id']) && $_REQUEST['guarantor_id']!=""){
        $where .= " AND  pmsPatient_guarantor_id = '".$_REQUEST['guarantor_id']."' ";
    }
    if (isset($_REQUEST['patient_xcare_id']) && $_REQUEST['patient_xcare_id']!=""){
        if(is_numeric($_REQUEST['patient_xcare_id']))
        {
            $where .= " AND  pmsPatient_xcare_id = '".$_REQUEST['patient_xcare_id']."' ";    
        }
        if($_REQUEST['patient_xcare_id'] == 'IS NULL')
        {    
            $where .= " AND  (`pmsPatient_xcare_id` IS NULL OR `pmsPatient_xcare_id` = '') ";
        }
        
    }
    if(isset($_REQUEST['pmspatient_gender']) && $_REQUEST['pmspatient_gender'] != '')
    {
        $where .= " AND pmsPatient_gender = '".$_REQUEST['pmspatient_gender']."'";
    }
    if(isset($_REQUEST['pmspatient_phone']) && $_REQUEST['pmspatient_phone'] != '')
    {
        $where .= " AND (pmsPatient_cell = '".$_REQUEST['pmspatient_phone']."' OR pmsPatient_homephone = '".$_REQUEST['pmspatient_phone']."' OR pmsPatient_workphone = '".$_REQUEST['pmspatient_phone']."')";
    }
    if(isset($_REQUEST['pmspatient_dob']) && $_REQUEST['pmspatient_dob'] != '')
    {
        $where .= " AND pmsPatient_dob = '".$_REQUEST['pmspatient_dob']."'";
    }
    if(isset($_REQUEST['pmspatient_id']) && $_REQUEST['pmspatient_id'] != '')
    {
        $where .= " AND pmsPatient_id = '".$_REQUEST['pmspatient_id']."'";
    }


    if (isset($_REQUEST['search']['value']) && $_REQUEST['search']['value']!=""){
        $where = " pmsPatient_fname LIKE '%".$_REQUEST['search']['value']."%' OR pmsPatient_lname LIKE '%".$_REQUEST['search']['value']."%'  OR pmsPatient_email LIKE '%".$_REQUEST['search']['value']."%' OR pmsPatient_homephone LIKE '%".$_REQUEST['search']['value']."%'   OR pmsPatient_workphone LIKE '%".$_REQUEST['search']['value']."%'  OR pmsPatient_cell LIKE '%".$_REQUEST['search']['value']."%' OR pmsPatient_patient_id LIKE '%".$_REQUEST['search']['value']."%' OR pmsPatient_practice_id LIKE '%".$_REQUEST['search']['value']."%'
             OR pmsPatient_id LIKE '%".$_REQUEST['search']['value']."%' OR pmsPatient_guarantor_id LIKE '%".$_REQUEST['search']['value']."%' ";
    }    
    $orderFields = array('','pmsPatient_id','pmsPatient_fname','pmsPatient_patient_id','','pmsPatient_email');
    
    // 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(" pmsPatient_id desc ");
    }

    $data    = array('where' => $where,'limit' => $limit, 'orderBy'=>$orderby);

    $pmsPatientDetails = $pmsPatientObj->getAllRecords($data);
    $recordsTotal   =   $pmsPatientObj->getAllCount($data);

        
    if ($pmsPatientDetails && count($pmsPatientDetails)>0){
        foreach ($pmsPatientDetails as $key => $pmsPatient){
            $dob="NA";
            if(!is_null($pmsPatient->pmsPatient_dob)){
                $dob = date("Y-m-d",strtotime($pmsPatient->pmsPatient_dob));
            }
            $gender="NA";
            if(!is_null($pmsPatient->pmsPatient_gender)){
                $gender = $pmsPatient->pmsPatient_gender;
            }
            $relationship = "NA";
            if(isset($pmsPatient->pmsPatient_relationship) && $pmsPatient->pmsPatient_relationship != '')
            {
                $relationship = $pmsPatient->pmsPatient_relationship;
            }

            if(is_null($pmsPatient->pmsPatient_xcare_id) && $pmsPatient->pmsPatient_xcare_id == '')
            {
                $all_checkbox = '<input type="checkbox" name="check[]" id="check[]" value="'.$pmsPatient->pmsPatient_id.'" class="check_class" />';
            }else{
                $all_checkbox = '';
            } 

            $response[] = array($all_checkbox,
                    $pmsPatient->pmsPatient_id,
                    $pmsPatient->pmsPatient_fname." ".$pmsPatient->pmsPatient_lname,
                    "<b>SikkaId : </b>".$pmsPatient->pmsPatient_patient_id."<br/><b>OfficeId : </b>".$pmsPatient->pmsPatient_practice_id."<br/><b>GuarantorId : </b>".$pmsPatient->pmsPatient_guarantor_id,
                    "<b>DOB : </b>".$dob."<br/><b>Gender : </b>".$gender."<br/><b>Relationship :</b>".$relationship,
                    $pmsPatient->pmsPatient_email, 
                    "<b>Home :</b>".$pmsPatient->pmsPatient_homephone."<br/><b>Work : </b>".$pmsPatient->pmsPatient_workphone."<br/><b>Cell : </b>".$pmsPatient->pmsPatient_cell,
                    $pmsPatient->pmsPatient_primary_insurance."<br/><b>Created At : </b>".date("Y-m-d", strtotime($pmsPatient->pmsPatient_created_at))."<br/><b>PMS Created Date : </b>".date("Y-m-d", strtotime($pmsPatient->pmsPatient_made_date)),
                    "<b>Address : </b>".$pmsPatient->pmsPatient_address1."  ".$pmsPatient->pmsPatient_address2."<br/><b>City : </b>".$pmsPatient->pmsPatient_city."<br/><b>State : </b>".$pmsPatient->pmsPatient_state."<br/><b>Zipcode : </b>".$pmsPatient->pmsPatient_zipcode,
             );
        }
        $result=array('recordsFiltered'=>$recordsTotal,'recordsTotal'=>$recordsTotal,'data'=>$response);
    }else{
        $result=array('recordsFiltered'=>0,'recordsTotal'=>0,'data'=>array());
    }
    echo json_encode($result);
    exit;
}

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