<?php  
// Include main file
include_once('../libs/main.php');
// Check dependant Login
include_once('checkLogin.php');

// Logical section of page
$dependantObj =  new  dependant();
$patientObj =  new patient();

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['loyalty_member']) && $_REQUEST['loyalty_member'] == 'Yes'){
        $where .= " AND dependant_member_id IS NOT NULL AND dependant_member_id != '' AND dependant_member_id != 0 ";
    }

    if(isset($_REQUEST['firstname']) && $_REQUEST['firstname'] != '' && $_REQUEST['lastname'] != '')
    {
        $firstname = trim($_REQUEST['firstname']);
        $lastname = trim($_REQUEST['lastname']);

        $where .= " AND ((d.dependant_fname='".w::e($firstname)."' and   d.dependant_lname='".w::e($lastname)."') OR (d.dependant_fname='".w::e(ucfirst($firstname))."' and   d.dependant_lname='".w::e(ucfirst($lastname))."'))";
    }else if(isset($_REQUEST['firstname']) && $_REQUEST['firstname'] != '' && $_REQUEST['lastname'] == ''){

        $firstname = trim($_REQUEST['firstname']);

        $where .= " AND ((d.dependant_fname LIKE '%".w::e($firstname)."%') OR (d.dependant_fname LIKE '%".w::e(ucfirst($firstname))."%' ))";
    }else if(isset($_REQUEST['lastname']) && $_REQUEST['lastname'] != '' && $_REQUEST['firstname'] == ''){

        $lastname = trim($_REQUEST['lastname']);

        $where .= " AND ((d.dependant_lname LIKE '%".w::e($lastname)."%') OR ( d.dependant_lname LIKE '%".w::e(ucfirst($lastname))."%'))";
    }

    /*if(isset($_REQUEST['fullname']) && $_REQUEST['fullname'] != '')
    {

        $patientname = preg_replace('/\s\s+/', ' ', $_REQUEST['fullname']);
        $fullname = explode(" ", $patientname);
        if(count($fullname)==2){
            $where .=" AND ((d.dependant_fname='".w::e($fullname['0'])."' AND  d.dependant_lname='".w::e($fullname['1'])."' ) OR (d.dependant_lname='".w::e($fullname['0'])."' AND  d.dependant_fname='".w::e($fullname['1'])."' ) OR (d.dependant_fname='".w::e(ucfirst($fullname['0']))."' AND  d.dependant_lname='".w::e(ucfirst($fullname['1']))."' ) OR (d.dependant_lname='".w::e(ucfirst($fullname['0']))."' AND  d.dependant_fname='".w::e(ucfirst($fullname['1']))."' ) )";
        }else{
            foreach ($fullname as $key => $f) {
                if($key==0){
                    $where .=" AND ( ";
                }
                $where .=" d.dependant_fname LIKE '%".w::e($f)."%' OR d.dependant_fname LIKE '%".w::e(ucfirst($f))."%'  OR d.dependant_lname LIKE '%".w::e($f)."%' OR dependant_lname LIKE '%".w::e(ucfirst($f))."%' OR d.dependant_email_address ='".w::e($f)."' OR d.dependant_phone = '".w::e($f)."' ";
                if( ($key+1) != count($fullname) ){
                        $where .=" OR ";
                }
                if( ($key+1) == count($fullname) ){
                    $where .=" )";
                }
            }
        }
    }*/
    /*if(isset($_REQUEST['dependant_patientname']) && $_REQUEST['dependant_patientname'] != '')
    {
        $patientfullname = str_replace(' ', '', $_REQUEST['dependant_patientname']);

        $where .=" AND ( patient_fname LIKE '%".($_REQUEST['dependant_patientname'])."%' OR CONCAT(patient_fname,'',patient_lname) LIKE '%".($fullname)."%' OR patient_lname LIKE '%".($_REQUEST['dependant_patientname'])."%') ";
    }*/
    if(isset($_REQUEST['dependant_unique_id']) && $_REQUEST['dependant_unique_id'] != '')
    {
        $where .= " AND  (dependant_unique_id = '".$_REQUEST['dependant_unique_id']."' OR patient_unique_id = '".$_REQUEST['dependant_unique_id']."') ";
    }
    /*if(isset($_REQUEST['dependant_gender']) && $_REQUEST['dependant_gender'] != '')
    {
        $where .= " AND  dependant_gender = '".$_REQUEST['dependant_gender']."' ";
    }*/
    if(isset($_REQUEST['dependant_email']) && $_REQUEST['dependant_email'] != '')
    {
        $where .= " AND  (dependant_email_address = '".w::e($_REQUEST['dependant_email'])."' OR patient_email_address = '".w::e($_REQUEST['dependant_email'])."') ";
    }
    if(isset($_REQUEST['dependant_phone']) && $_REQUEST['dependant_phone'] != '')
    {
        $where .= " AND  (dependant_phone = '".w::e($_REQUEST['dependant_phone'])."' OR  patient_phone = '".w::e($_REQUEST['dependant_phone'])."' )";
    }
    if(isset($_REQUEST['dependant_dob']) && $_REQUEST['dependant_dob'] != '')
    {
        $where .= " AND  dependant_dob = '".w::e($_REQUEST['dependant_dob'])."' ";
    }
    /*if(isset($_REQUEST['dependant_contact_method']) && $_REQUEST['dependant_contact_method'] != '')
    {
        $where .= " AND FIND_IN_SET('".$_REQUEST['dependant_contact_method']."', dependant_contact_method)";
    }*/
    if(isset($_REQUEST['dependant_id']) && $_REQUEST['dependant_id'] != '')
    {
        $where .= " AND  dependant_id = '".$_REQUEST['dependant_id']."' ";
    }
    if(isset($_REQUEST['guarantor_id']) && $_REQUEST['guarantor_id'] != '')
    {   
        $where_parg = array("patient_unique_id="=>$_REQUEST['guarantor_id']);
        $patientArg    = array('where' => $where_parg);
        $patientDetailsId = $patientObj->FromFields($patientArg);
        
        $where .= " AND patient_id = '".$patientDetailsId->patient_id."'";
    }
    if(isset($_REQUEST['login_id']) && $_REQUEST['login_id']!= '')
    {
        $where_arg = array("patient_unique_id="=>$_REQUEST['login_id']);
        $patientArg    = array('where' => $where_arg);
        $patientdependantId = $patientObj->FromFields($patientArg);
        $where .= " AND dependant_login_id = '".$patientdependantId->patient_id."'";
    }
    
    //OR i.insurance_name LIKE '%".$_REQUEST['search']['value']."%' OR inp.insurancePlan_name LIKE '%".$_REQUEST['search']['value']."%' 
    if (isset($_REQUEST['search']['value']) && $_REQUEST['search']['value']!=""){
        $where = "d.dependant_unique_id LIKE '%".$_REQUEST['search']['value']."%' OR  d.dependant_id LIKE '%".$_REQUEST['search']['value']."%' OR dependant_fname LIKE '%".w::e($_REQUEST['search']['value'])."%' OR dependant_lname LIKE '%".w::e($_REQUEST['search']['value'])."%' OR dependant_email_address LIKE '%".w::e($_REQUEST['search']['value'])."%' OR dependant_phone LIKE '%".w::e($_REQUEST['search']['value'])."%' OR dependant_contact_method LIKE '%".$_REQUEST['search']['value']."%' OR d.dependant_gender LIKE '%".$_REQUEST['search']['value']."%' OR p.patient_id LIKE '%".$_REQUEST['search']['value']."%' OR p.patient_fname LIKE '%".w::e($_REQUEST['search']['value'])."%' OR p.patient_lname LIKE '%".w::e($_REQUEST['search']['value'])."%' OR p.patient_email_address LIKE '%".w::e($_REQUEST['search']['value'])."%' OR p.patient_phone LIKE '%".w::e($_REQUEST['search']['value'])."%' OR p.patient_unique_id LIKE '%".$_REQUEST['search']['value']."%' OR d.dependant_fname LIKE '%".w::e(ucfirst($_REQUEST['search']['value']))."%' OR d.dependant_lname LIKE '%".w::e(ucfirst($_REQUEST['search']['value']))."%' OR d.dependant_fname LIKE '%".w::e(ucwords($_REQUEST['search']['value']))."%' OR d.dependant_lname LIKE '%".w::e(ucwords($_REQUEST['search']['value']))."%' OR p.patient_fname LIKE '%".w::e(ucfirst($_REQUEST['search']['value']))."%' OR p.patient_lname LIKE '%".w::e(ucfirst($_REQUEST['search']['value']))."%' OR p.patient_fname LIKE '%".w::e(ucwords($_REQUEST['search']['value']))."%' OR p.patient_lname LIKE '%".w::e(ucwords($_REQUEST['search']['value']))."%' OR dependant_dob LIKE '".w::e($_REQUEST['search']['value'])."'";
    }    
        
    $orderFields = array('dependant_id','dependant_dob','','patient_fname');
    
    // 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(" dependant_id desc ");
    }
   // $t = '378';
    $tables = array('tbl_patient p');
    $jfields = array('p.patient_id = d.dependant_guarantor_id');
    $jtype   = array("INNER");
    //$where = array("dependant_id="=>$t); 
    $data   = array('where' => $where,  'joinTables' =>$tables, 'joinFields' =>$jfields, 'joinTypes' => $jtype,'orderBy'=>$orderby,'limit' => $limit);

    $dependantDetails = $dependantObj->getAllRecords($data);
    //print_r($dependantDetails);exit;
    $recordsTotal   =   $dependantObj->getAllCount($data);
     
    if ($dependantDetails && count($dependantDetails)>0){
        foreach ($dependantDetails as $key => $dependant){

            $login_detail = '';
            if(!is_null($dependant->dependant_login_id))
            {
                $where = array("patient_id="=>$dependant->dependant_login_id);
                $patientArg    = array('where' => $where);
                $patientDetails = $patientObj->FromFields($patientArg);
                if($patientDetails)
                {
                    $notificationObj = new notification();
                    $fields = array('count(notification_id) as notification');
                    $where = array("notification_patient_id="=>$patientDetails->patient_id);
                    $notificationArg = array("fields"=>$fields,"where"=>$where);
                    $notificationDetail = $notificationObj->fromFields($notificationArg);
                    $notification_count = 0;
                    $notification_count = $notificationDetail->notification;
                    if($notification_count != '0'){
                        $notificationdata = "<a href='fcmtokendetail.php?fcm_id=".$patientDetails->patient_id."'>".$notification_count."</a>";    
                    }else{
                        $notificationdata = $notification_count;
                    }
                    
                    //<b>First Name :</b>".w::d($patientDetails->patient_fname)."<br/><b>Last Name : </b>".w::d($patientDetails->patient_lname)."<br/>
                    $login_detail = "<b>Xcare SignIn Patient ID : </b>".$patientDetails->patient_id."<br/><b>Xcare SignIn External Id : </b>".$patientDetails->patient_unique_id."<br/><b>Email : </b>".w::d($patientDetails->patient_email_address)."<br/><b>Phone : </b>".w::d($patientDetails->patient_phone)."<br/><b>FCM Token Count</b> : ".$notificationdata;
                }
            }
            if(!is_null($dependant->dependant_login_id) && $dependant->dependant_login_id != '')
            {
                $patientappointmentdetail = "<a href='patientappointmentdetail.php?patient_id=".$dependant->dependant_login_id."'>Appointment Details</a>";
            }else{
                $patientappointmentdetail = '';
            }

            $pmspatientObj = new pmsPatient();
            $pmsfields = array("pmsPatient_patient_id");
            $pmswhere = array("pmsPatient_xcare_id="=>$dependant->dependant_id);
            $pmspatientObj->resultAs = 'array';
            $pmspatientdata = array('fields'=>$pmsfields,'where' => $pmswhere);
            $pmspatientDetails = $pmspatientObj->getAllRecords($pmspatientdata);
            $pmsallpatient = array_column($pmspatientDetails, 'pmsPatient_patient_id');
            $pmsdataval = implode(",",$pmsallpatient);
            
            //<b>ID : </b>".$dependant->dependant_id."<br/>
            //."<br/><br/>".$patientappointmentdetail

            $membershipInfo = '';
            if (!empty($dependant->dependant_member_id)) {
                $membershipInfo .= "<b>MemberId: </b>".($dependant->dependant_member_id)."<br/>";
            }
            if (!empty($dependant->dependant_memberSince)) {
                $membershipInfo .= "<b>MemberSince: </b>".($dependant->dependant_memberSince)."<br/>";
            }
            if (!empty($dependant->dependant_member_email)) {
                $membershipInfo .= "<b>MemberEmail: </b>".($dependant->dependant_member_email)."<br/>";
            }
            if (!empty($dependant->dependant_currentRewardTier)) {
                $membershipInfo .= "<b>CurrentTier: </b>".($dependant->dependant_currentRewardTier)."<br/>";
            }

            $response[] = array( 
                    "<b>Xcare Patient ID : </b>".$dependant->dependant_id."<br/>
                    <b>Patient External Id: </b>".$dependant->dependant_unique_id."<br/>
                    <b>First Name: </b>".w::d($dependant->dependant_fname)."<br/>
                    <b>Last Name: </b>".w::d($dependant->dependant_lname)."<br/>
                    <b>Communication Email: </b>".w::d($dependant->dependant_email_address)."<br/>
                    <b>Communication Phone: </b>".w::d($dependant->dependant_phone)."<br/>
                    <b>PMS ID: </b>".$pmsdataval."<br/>
                    <b>Created At: </b>".$dependant->dependant_created_at."<br/>"
                    .$membershipInfo,
                    
                
                    "<b>DOB: </b>".w::d($dependant->dependant_dob)."<br/>
                    <b>Gender: </b>".$dependant->dependant_gender."<br/>
                    <b>Relation with Guarantor: </b><br/>".$dependant->dependant_relation,
                    
                    "<b>Method: </b>".$dependant->dependant_contact_method."<br/>
                    <b>Reminder: </b>".$dependant->dependant_reminder,
                    $login_detail,

                    "<b>Xcare Guarantor ID: </b>".$dependant->patient_id."<br/>
                    <b>Guarantor External Id: </b>".$dependant->patient_unique_id."<br/>
                    <b>First Name: </b>".w::d($dependant->patient_fname)."<br/>
                    <b>Last Name: </b>".w::d($dependant->patient_lname)."<br/>
                    <b>Email: </b>".w::d($dependant->patient_email_address)."<br/>
                    <b>Phone: </b>".w::d($dependant->patient_phone),
                    "<a href='dependantdetail.php?dependant_id=".$dependant->dependant_id."'>PMS Details</a>"."<br/><br/>
                    <a href='all_app_data.php?type=dependantdata&dependants_id=".$dependant->dependant_id."'>Appointment Details</a>"."<br/><br/><a href='clinicpatientlist.php?type=dependantdata&dependants_id=".$dependant->dependant_id."' target='_blank'>Clinic Details</a>"."<br/><br/>
                    <a href='dependantmoredetail.php?type=dependantmoredata&dependants_id=".$dependant->dependant_id."' target='_blank'>More Details</a>",


                    //"<b>Insurance Name : </b>".$dependant->insurance_name."<br/><b>Insurance Plan : </b>".$dependant->insurancePlan_name,
                   // date('Y-m-d',strtotime($dependant->dependant_created_at))


            );
        }
        $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');
?>