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

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

$adminlogObj = new admin_log();
$modulepagesObj = new module_pages();

$filename=basename($_SERVER['SCRIPT_FILENAME']);
if($filename == 'patientlist.php')
{
    $module_id = $adminlogObj->getModuleId($filename);
    $page_id = $adminlogObj->getPageId($filename);
    $allpages = $modulepagesObj->fromId($page_id);
    $pagename = $allpages->page;

}

if(isset($_REQUEST['act']) && $_REQUEST['act']=='change_status' && isset($_REQUEST['patient_id'])){
    if(isset($_REQUEST['status'])){

        $patientDetail = $patientObj->fromId($_REQUEST['patient_id']);
        if($patientDetail->patient_status == '1')
        {
            $old_status = 'Active';
        }else{
            $old_status = 'Inactive';
        }

        if($_REQUEST['status'] == '1')
        {
            $new_status = 'Active';
        }else{
            $new_status = 'Inactive';
        }
        $patient_detail = " <b>Id</b>:".$_REQUEST['patient_id']." <br/><b>Name</b>:".w::d($patientDetail->patient_fname)." ".w::d($patientDetail->patient_lname)." <br/><b>Status</b>: "." ".$old_status." <b>To</b> ".$new_status." ";

        $patientObj->changeStatus($_REQUEST['patient_id']);

         $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,$patient_detail);

        //echo RECORD_STATUS;
        echo json_encode(array("msg" => RECORD_STATUS, "pstatus" => $_REQUEST['status'], "patient_id" => $_REQUEST['patient_id']));
    }
    return true;
}
if(isset($_REQUEST['act']) && $_REQUEST['act']=='delete' && isset($_REQUEST['patient_id'])){
    $patientObj->deleteFromId($_REQUEST['patient_id']);
    $successMsg = base64_encode(RECORD_DELETE);
}

if(isset($_REQUEST['action']) && $_REQUEST['action']!=''){
    
    if($_REQUEST['action']=="activate_all"){
        $data=array("patient_status" => '1');
        $chk_data = $_POST['check'];
        foreach($chk_data as $akey => $val_actchk)
        {
            $old_data = $patientObj->fromId($val_actchk);
            if($old_data->patient_status == '1')
            {
                $old_status = 'Active';
            }else{
                $old_status = 'Inactive';
            }

            if($old_data->patient_status != '1')
            {
                $new_status = 'Active';
                $patientdata = " <b>Id</b>:".$val_actchk." <br/><b>Status</b>: "." ".$old_status." <b>To</b> ".$new_status." ";
                $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,$patientdata);
            }
        }
        $rs = $patientObj->updateManyRecords($data, $_POST['check']);
        $successMsg = base64_encode(RECORD_ALL_ACTIVE);
    }else if($_REQUEST['action']=="inactivate_all"){
        $data=array("patient_status" => '0');
        $chk_data = $_POST['check'];
        foreach($chk_data as $akey => $val_actchk)
        {
            $old_data = $patientObj->fromId($val_actchk);
            if($old_data->patient_status == '1')
            {
                $old_status = 'Active';
            }else{
                $old_status = 'Inactive';
            }

            if($old_data->patient_status != '0')
            {
                $new_status = 'Inactive';
                $patientdata = " <b>Id</b>:".$val_actchk." <br/><b>Status</b>: "." ".$old_status." <b>To</b> ".$new_status." ";
                $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,$patientdata);
            }
        }
        $rs = $patientObj->updateManyRecords($data, $_POST['check']);
        $successMsg = base64_encode(RECORD_ALL_INACTIVE);
    }else 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 = $patientObj->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['firstname']) && $_REQUEST['firstname'] != '' && $_REQUEST['lastname'] != '')
    {
        $firstname = trim($_REQUEST['firstname']);
        $lastname = trim($_REQUEST['lastname']);

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

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

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

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

        $where .= " AND ((p.patient_lname LIKE '%".w::e($lastname)."%') OR ( p.patient_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 ((p.patient_fname='".w::e($fullname['0'])."' AND  p.patient_lname='".w::e($fullname['1'])."' ) OR (p.patient_lname='".w::e($fullname['0'])."' AND  p.patient_fname='".w::e($fullname['1'])."' ) OR (p.patient_fname='".w::e(ucfirst($fullname['0']))."' AND  p.patient_lname='".w::e(ucfirst($fullname['1']))."' ) OR (p.patient_lname='".w::e(ucfirst($fullname['0']))."' AND  p.patient_fname='".w::e(ucfirst($fullname['1']))."' ) )";
        }else{
            foreach ($fullname as $key => $f) {
                if($key==0){
                    $where .=" AND ( ";
                }
                $where .=" p.patient_fname LIKE '%".w::e($f)."%' OR p.patient_fname LIKE '%".w::e(ucfirst($f))."%'  OR p.patient_lname LIKE '%".w::e($f)."%' OR p.patient_lname LIKE '%".w::e(ucfirst($f))."%'  ";
                if( ($key+1) != count($fullname) ){
                        $where .=" OR ";
                }
                if( ($key+1) == count($fullname) ){
                    $where .=" )";
                }
            }
        }*/
        //echo $where;exit;
        //$fullname = str_replace(' ', '', $_REQUEST['fullname']);   
        //$where .= " AND CONCAT(patient_fname,'',patient_lname) LIKE '%".w::d($fullname)."%'";
       // $where .=" AND ( patient_fname LIKE '%".w::d($_REQUEST['fullname'])."%' OR CONCAT(patient_fname,'',patient_lname) LIKE '%".w::d($fullname)."%' OR patient_lname LIKE '%".w::d($_REQUEST['fullname'])."%') ";
    //}
    if(isset($_REQUEST['referral_code']) && $_REQUEST['referral_code'] != '')
    {   
        $where .= " AND  patient_referralCode = '".$_REQUEST['referral_code']."' ";
    }
    if(isset($_REQUEST['patient_uniqueid']) && $_REQUEST['patient_uniqueid'] != '')
    {
        $where .= " AND  patient_unique_id = '".$_REQUEST['patient_uniqueid']."' ";
    }
    if(isset($_REQUEST['patient_gender']) && $_REQUEST['patient_gender'] != '')
    {
        $where .= " AND  patient_gender = '".$_REQUEST['patient_gender']."' ";
    }
    if(isset($_REQUEST['patient_email']) && $_REQUEST['patient_email'] != '')
    {
        $where .= " AND  patient_email_address = '".w::e($_REQUEST['patient_email'])."' ";
    }
    if(isset($_REQUEST['patient_phone']) && $_REQUEST['patient_phone'] != '')
    {
        $where .= " AND  patient_phone = '".w::e($_REQUEST['patient_phone'])."' ";
    }
    if(isset($_REQUEST['patient_dob']) && $_REQUEST['patient_dob'] != '')
    {
        $where .= " AND  patient_dob = '".w::e($_REQUEST['patient_dob'])."' ";
    }
    if(isset($_REQUEST['patient_id']) && $_REQUEST['patient_id'] != '')
    {
        $where .= " AND patient_id = '".$_REQUEST['patient_id']."'";
    }



    if (isset($_REQUEST['search']['value']) && $_REQUEST['search']['value']!=""){
        $where = " patient_unique_id LIKE '%".$_REQUEST['search']['value']."%' OR patient_id LIKE '%".$_REQUEST['search']['value']."%' OR patient_fname LIKE '%".w::e($_REQUEST['search']['value'])."%' OR patient_lname LIKE '%".w::e($_REQUEST['search']['value'])."%' OR patient_email_address LIKE '%".w::e($_REQUEST['search']['value'])."%' OR patient_phone LIKE '%".w::e($_REQUEST['search']['value'])."%' OR patient_dob LIKE '%".w::e($_REQUEST['search']['value'])."%' OR patient_referralCode LIKE '%".$_REQUEST['search']['value']."%' OR patient_country LIKE '%".$_REQUEST['search']['value']."%' OR patient_state LIKE '%".$_REQUEST['search']['value']."%' OR patient_city LIKE '%".$_REQUEST['search']['value']."%' OR patient_postal_code LIKE '%".$_REQUEST['search']['value']."%' OR patient_gender LIKE '%".$_REQUEST['search']['value']."%' OR patient_loginas LIKE '%".$_REQUEST['search']['value']."%' OR patient_fname LIKE '%".w::e(ucfirst($_REQUEST['search']['value']))."%' OR patient_fname LIKE '%".w::e(ucwords($_REQUEST['search']['value']))."%' OR patient_lname LIKE '%".w::e(ucfirst($_REQUEST['search']['value']))."%' OR patient_lname LIKE '%".w::e(ucwords($_REQUEST['search']['value']))."%' OR  patient_email_address LIKE '%".w::e(ucfirst($_REQUEST['search']['value']))."%' OR patient_email_address LIKE '%".w::e(ucwords($_REQUEST['search']['value']))."%' OR patient_last_login_ip LIKE '%".$_REQUEST['search']['value']."%' OR patient_last_login_at LIKE '%".$_REQUEST['search']['value']."%' OR patient_phone_verified LIKE '%".$_REQUEST['search']['value']."%' OR patient_phone_vcode LIKE '%".$_REQUEST['search']['value']."%' OR patient_email_vcode LIKE '%".$_REQUEST['search']['value']."%' OR patient_email_verified LIKE '%".$_REQUEST['search']['value']."%' " ;

    }    
        
    $orderFields = array('','patient_id','patient_email_address','','');
    
    // 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(" patient_id desc ");
    }

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

    $patientDetails = $patientObj->getAllRecords($data);

    $recordsTotal   =   $patientObj->getAllCount($data);
        
    if ($patientDetails && count($patientDetails)>0){
        foreach ($patientDetails as $key => $patient){

            if($patient->patient_status =='1'){
              $status = '<a href="javascript:void(0)" onclick="change_status('.$patient->patient_id.',0)" title="Inactivate"><span class="badge badge-success">Active</span></a>';
            }else{
              $status = '<a href="javascript:void(0)" onclick="change_status('.$patient->patient_id.',1)" title="Activate"><span class="badge badge-danger">Inactive</span></a>';
            }
           
            /*$clinic_detail = '';
            if(!is_null($patient->patient_defaultClinic) && $patient->patient_defaultClinic != '')
            {
                $clinicObj = new clinic();
                $where = 'clinic_id IN ('.$patient->patient_defaultClinic.')';
                $data = array('where' => $where);
                $clinicDetails = $clinicObj->getAllRecords($data);
                
                foreach ($clinicDetails as $key => $clinicdata) {
                    
                    $clinic_detail .= "<b>Id : </b>".$clinicdata->clinic_id."<br/><b>UniqueId : </b>".$clinicdata->clinic_unique_id."<br/><b>Clinic Name : </b>".$clinicdata->clinic_name.
                    "<br/><b>Email : </b>".$clinicdata->clinic_email."<br/><b>Phone : </b>".$clinicdata->clinic_phone."<br/><br/>";
                }
            }*/


            $photo_image = '';
            if(!is_null($patient->patient_profilephoto) && $patient->patient_profilephoto != '')
            {
                $photo_detail = json_decode($patient->patient_profilephoto,1);
                if($photo_detail && $photo_detail > 0 )
                { 
                    foreach ($photo_detail as $key => $row_photo) 
                    {
                        if($key == 'name')
                        {
                            $photo_name = $row_photo; 

                        }
                        if($key == 'type')
                        {
                            $photo_type = $row_photo;    
                        }  
                        if($photo_name != '' && $photo_type != '')
                        {
                            $photo_src =  $photo_name.'-original.'.$photo_type;
                            $photo_src1 =  $photo_name.'-';
                            //echo DIR_UPLOAD_PATIENT_SHOW.$photo_name.'-'.'.jpeg';exit;
                            $photo_image = '<img style="width:120px;" src="'.DIR_UPLOAD_PATIENT_SHOW.$photo_src.'" />';
                        }
                    }
                }
            }

            //$insurance_detail = '';
            /*if(!is_null($patient->patient_insurance) && $patient->patient_insurance != '')
            {
                $insuranceObj = new insurance();
                $tables = array('tbl_insuranceplan inp');
                $jfields = array('inp.insurancePlan_id = i.insurance_id');
                $jtype   = array("LEFT");
                $where = 'insurance_id IN ('.$patient->patient_insurance.')';
                $data = array('where' => $where,'joinTables' =>$tables, 'joinFields' =>$jfields, 'joinTypes' => $jtype);
                $insuranceDetails = $insuranceObj->getAllRecords($data);
                
                foreach ($insuranceDetails as $ikey => $insurancedata) {
                    
                    $insurance_detail .= "<b>insurance_id : </b>".$insurancedata->insurance_id."<br/><b>Insurance Name : </b>".$insurancedata->insurance_name.
                    "<br/><b>Plan name : </b>".$insurancedata->insurancePlan_name;
                }
            }*/

            $response[] = array('<input type="checkbox" name="check[]" id="check[]" value="'.$patient->patient_id.'" class="check_class" />', 
                    //$patient->patient_unique_id,
                    "<b>Xcare Patient ID: </b>".$patient->patient_id."<br/><b>External Id: </b>".$patient->patient_unique_id."<br/><b>First Name: </b>".w::d($patient->patient_fname)."<br/><b>Last Name: </b>".w::d($patient->patient_lname)."<br/><b>Gender: </b>".$patient->patient_gender."<br/><b>DOB: </b>".w::d($patient->patient_dob)."<br/><b>Referral Code: </b>".$patient->patient_referralCode."<br/><b>Login: </b>".$patient->patient_loginas,
                    
                    //$clinic_detail,
                    
                    "<b>Email: </b>".w::d($patient->patient_email_address)."<br/><b>Phone: </b>".w::d($patient->patient_phone)."<br/><b>Login Ip: </b>".$patient->patient_last_login_ip."<br/><b>Last Login: </b>".$patient->patient_last_login_at."<br/><b>Phone Verified: </b>".$patient->patient_phone_verified."<br/><b>Phone Vcode: </b>".$patient->patient_phone_vcode."<br/><b>Email Verified: </b>".$patient->patient_email_verified."<br/><b>Email Vcode: </b>".$patient->patient_email_vcode,
                    
                    "<b>Address: </b>".$patient->patient_addressline1." ".$patient->patient_addressline2."<br/><b>City: </b>".$patient->patient_city."<br/><b>State: </b>".$patient->patient_state."<br/><b>Country: </b> ".$patient->patient_country."<br/><b>Postal Code: </b>".$patient->patient_postal_code,
                    //$photo_image,
                    //date('Y-m-d',strtotime($patient->patient_created_at)),
                    //$insurance_detail,
                    "<div id='td_status_".$patient->patient_id."'>".$status."</div>"."<br/><a href='patientdetail.php?patient_gurantor_id=".$patient->patient_guarantor_id."'>Details</a>",    
                    // '<a href="patientadd.php?act=edit&patient_id='.$patient->patient_id.'" class="btn btn-success white-btn"><i class="nav-icon i-Pen-2 "></i></a>
                    // <a id="delete-confirm" onclick="delete_entry('.$patient->patient_id.');" class="btn btn-danger white-btn"><i class="nav-icon i-Close-Window "></i></a>'

            );
        }
       //print_r($response);exit;
        $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');
?>