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

// Logical section of page
$doctorObj =  new  doctor();
$cdoctorObj =  new  cdoctor();
$adminlogObj = new admin_log();
$modulepagesObj = new module_pages();

$filename=basename($_SERVER['SCRIPT_FILENAME']);

if($filename == 'doctorlist.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['doctor_id'])){
    if(isset($_REQUEST['status'])){
        //$doctorObj->changeStatus($_REQUEST['doctor_id']);
        $cdoctorObj =  new  cdoctor();
        $cddoctorDetail = $cdoctorObj->fromId($_REQUEST['doctor_id']);

        if($cddoctorDetail->cdoctor_appointment == '1')
        {
            $old_status = 'Active';
        }else{
            $old_status = 'Inactive';
        }

        if($_REQUEST['status'] == '1')
        {
            $new_status = 'Active';
        }else{
            $new_status = 'Inactive';
        }

        $doctor_id = $_REQUEST['doctor_id'];
        $doctor_status['cdoctor_appointment'] = $_REQUEST['status'];
        $rs=$cdoctorObj->updateRecords($doctor_status,$doctor_id);

        $doctor_detail = " <b>Provider Id</b>:".$cddoctorDetail->cdoctor_provider_id." <br/><b>Name</b>:".$cddoctorDetail->cdoctor_fullname." <br/><b>doctor status</b>: "." ".$old_status." <b>To</b> ".$new_status." ";
        $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,$doctor_detail);
        //echo RECORD_STATUS;
        echo json_encode(array("msg" => RECORD_STATUS, "dstatus" => $_REQUEST['status'], "doctor_id" => $_REQUEST['doctor_id']));
    }
    return true;
}
if(isset($_REQUEST['act']) && $_REQUEST['act']=='delete' && isset($_REQUEST['doctor_id']) && isset($_REQUEST['doctor_clinic'])){

    //$doctorObj->deleteFromId($_REQUEST['doctor_id']);
    $clinicIds = $_REQUEST['doctor_clinic'];
    $doctorIds = $_REQUEST['doctor_id'];
    //echo "<pre>";print_r($doctorIds);echo "</pre>";
    /*Fetch User*/
    $clinicObj = new clinic();
    $clinicDetail = $clinicObj->fromId($clinicIds);
    $userid = $clinicDetail->clinic_user_id;
    

    /*Fetch appointments of that provider*/
    
    $appointmentObj = new appointment();
    $where ='appointment_clinic_id ='.$clinicIds.' AND appointment_doctor_id='.$doctorIds.'';
    $arg =array('where'=>$where);
    $allAppt = $appointmentObj->getAllRecords($arg);
    
    if(!empty($allAppt)){
        echo 'There are appointments associated so you cannot delete this provider';
        exit();    
    }else{
        $cdoctorObj = new cdoctor();
        $where ='cdoctor_doctor_id='.$doctorIds.'';
        $arg =array('where'=>$where);
        $allProvider = $cdoctorObj->getAllRecords($arg);

        if(count($allProvider) == 1){
            $doctorObj = new doctor();
            $where ='doctor_id ='.$doctorIds.'';
            $arg =array('where'=>$where);
            $allProvider = $doctorObj->getAllRecords($arg);
            $doctorObj->deleteFromFields($arg);    
        }
        $cdocwhere ='cdoctor_clinic_id ='.$clinicIds.' AND cdoctor_doctor_id='.$doctorIds.'';
        $cdocarg =array('where'=>$cdocwhere);
        $cdoctorObj->deleteFromFields($cdocarg);
        

        // add doctor permission to user
        $permissonObj= new permission();
        $where ='permission_model_id ='.$doctorIds.' AND permission_model_type="Doctor" AND permission_user_id='.$userid.'';
        $arg =array('where'=>$where);
        //$allPermission = $permissonObj->getAllRecords($arg);
        //echo "<pre>";print_r($allPermission);echo "</pre>";
        
        $providerdelte = $permissonObj->deleteFromFields($arg);

        if($providerdelte)
            echo 'Provider Deleted Successfully';
        exit();
    }
}

if(isset($_REQUEST['action']) && $_REQUEST['action']!=''){
    
    if($_REQUEST['action']=="activate_all"){
        //$data=array("doctor_status" => '1');
        $data=array("cdoctor_appointment" => '1');
        $rs = $cdoctorObj->updateManyRecords($data, $_POST['check']);
        $successMsg = base64_encode(RECORD_ALL_ACTIVE);
    }else if($_REQUEST['action']=="inactivate_all"){
        //$data=array("doctor_status" => '0');
        $data=array("cdoctor_appointment" => '0');
        $rs = $cdoctorObj->updateManyRecords($data, $_POST['check']);
        $successMsg = base64_encode(RECORD_ALL_INACTIVE);
    }else if($_REQUEST['action']=="delete_all"){
        $rs = $doctorObj->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['fullname']) && $_REQUEST['fullname'] != '')
    {
        $where .= " AND cdoctor_fullname LIKE  '%".$_REQUEST['fullname']."%'";
    }
    if(isset($_REQUEST['doctor_unique_id']) && $_REQUEST['doctor_unique_id'] != '')
    {
        $where .= " AND  (cdoctor_provider_id = '".$_REQUEST['doctor_unique_id']."' OR doctor_unique_id = '".$_REQUEST['doctor_unique_id']."') ";
    }
    if(isset($_REQUEST['docotr_email']) && $_REQUEST['docotr_email'] != '')
    {
        $where .= " AND  (cdoctor_email = '".$_REQUEST['docotr_email']."' OR clinic_email = '".$_REQUEST['docotr_email']."' )";
    }
    if(isset($_REQUEST['doctor_phone']) && $_REQUEST['doctor_phone'] != '')
    {
        $where .= " AND  (cdoctor_phone = '".$_REQUEST['doctor_phone']."' OR clinic_phone = '".$_REQUEST['doctor_phone']."' ) ";
    }
    if(isset($_REQUEST['doctor_specality']) && $_REQUEST['doctor_specality'] != '')
    {
        $where .= " AND FIND_IN_SET('".$_REQUEST['doctor_specality']."', cdoctor_speciality)";
    }
    if(isset($_REQUEST['doctor_licenceno']) && $_REQUEST['doctor_licenceno'] != '')
    {
        $where .= " AND  doctor_licence = '".$_REQUEST['doctor_licenceno']."' ";
    }
    if(isset($_REQUEST['doctor_gender']) && $_REQUEST['doctor_gender'] != '')
    {
        $where .= " AND  doctor_gender = '".$_REQUEST['doctor_gender']."' ";
    }
    if(isset($_REQUEST['doctor_language']) && $_REQUEST['doctor_language'] != '')
    {
        $where .= " AND FIND_IN_SET('".$_REQUEST['doctor_language']."', doctor_languages)";
    }
    if(isset($_REQUEST['doctor_clinic']) && $_REQUEST['doctor_clinic'] != '')
    {
        $where .= " AND  cdoctor_clinic_id = '".$_REQUEST['doctor_clinic']."' ";
    }
    if(isset($_REQUEST['doctor_id']) && $_REQUEST['doctor_id'] != '')
    {
        $where .= " AND doctor_id = '".$_REQUEST['doctor_id']."'";
    }
    if(isset($_REQUEST['doctor_date']) && $_REQUEST['doctor_date'] != '')
    {
        $where .= " AND doctor_date = '".$_REQUEST['doctor_date']."'";
    }
    if(isset($_REQUEST['doctor_website']) && $_REQUEST['doctor_website'] != '')
    {
        $where .= " AND clinic_website = '".$_REQUEST['doctor_website']."'";
    }
    if(isset($_REQUEST['doctor_status']) && $_REQUEST['doctor_status'] != '')
    {
        $where .= " AND cdoctor_appointment = '".$_REQUEST['doctor_status']."'";
    }    

    /*if (isset($_REQUEST['search']['value']) && $_REQUEST['search']['value']!=""){
        $where = "doctor_unique_id LIKE '%".$_REQUEST['search']['value']."%' OR  doctor_id LIKE '%".$_REQUEST['search']['value']."%' OR doctor_fullname LIKE '%".$_REQUEST['search']['value']."%' OR doctor_email LIKE '%".$_REQUEST['search']['value']."%' OR doctor_phone LIKE '%".$_REQUEST['search']['value']."%' OR doctor_website LIKE '%".$_REQUEST['search']['value']."%' ";
    }*/

    if (isset($_REQUEST['search']['value']) && $_REQUEST['search']['value']!=""){
        $where = "doctor_unique_id LIKE '%".$_REQUEST['search']['value']."%' OR  doctor_id LIKE '%".$_REQUEST['search']['value']."%' OR clinic_unique_id LIKE '%".$_REQUEST['search']['value']."%' OR clinic_name LIKE '%".$_REQUEST['search']['value']."%' OR clinic_phone LIKE '%".$_REQUEST['search']['value']."%' OR clinic_email LIKE '%".$_REQUEST['search']['value']."%' OR clinic_website LIKE '%".$_REQUEST['search']['value']."%' OR cdoctor_fullname LIKE '%".$_REQUEST['search']['value']."%' OR cdoctor_email LIKE '%".$_REQUEST['search']['value']."%' OR cdoctor_phone LIKE '%".$_REQUEST['search']['value']."%' OR doctor_licence LIKE '%".$_REQUEST['search']['value']."%' OR doctor_gender LIKE '".$_REQUEST['search']['value']."' OR cdoctor_provider_id LIKE '".$_REQUEST['search']['value']."' OR cdoctor_sikka_code LIKE '%".$_REQUEST['search']['value']."%' OR cdoctor_created_at LIKE '%".$_REQUEST['search']['value']."%' OR clinic_id LIKE '%".$_REQUEST['search']['value']."%' ";
    }    
        
    //$orderFields = array('doctor_id','doctor_fullname', 'doctor_email', 'doctor_created_at');
    $orderFields = array('','doctor_id','doctor_unique_id','clinic_name','cdoctor_fullname','cdoctor_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(" doctor_id desc ");
    }

    //print_r($orderby);exit;
    //$data   = array('limit' => $limit);
    //,'tbl_speciality s'
    //,'cd.cdoctor_speciality = s.speciality_id'
    //,"LEFT"
    $tables = array('tbl_cdoctor cd','tbl_clinic c');
    $jfields = array('cd.cdoctor_doctor_id = d.doctor_id','c.clinic_id = cd.cdoctor_clinic_id');
    $jtype   = array("INNER","INNER");
    $data   = array('where' => $where,  'joinTables' =>$tables, 'joinFields' =>$jfields, 'joinTypes' => $jtype,'orderBy'=>$orderby,'limit' => $limit);

    $doctorDetails = $doctorObj->getAllRecords($data);
    //echo "<pre>";print_r($doctorDetails);echo "</pre>";
    //print_r($doctorDetails);exit;
    $recordsTotal   =   $doctorObj->getAllCount($data);
        
    if ($doctorDetails && count($doctorDetails)>0){
        foreach ($doctorDetails as $key => $doctor){

            if($doctor->cdoctor_appointment =='1'){
              $status = '<a href="javascript:void(0)" onclick="change_status('.$doctor->cdoctor_id.',0)" title="Inactivate"><span class="badge badge-success">Active</span></a>';
            }else{
              $status = '<a href="javascript:void(0)" onclick="change_status('.$doctor->cdoctor_id.',1)" title="Activate"><span class="badge badge-danger">Inactive</span></a>';
            }

            if($doctor->cdoctor_shareCalender == '1')
            {
                $dshare_clender = 'true';
            }else{
                $dshare_clender = 'false';
            }

            if($doctor->cdoctor_newPatient == '1')
            {
                $dnewPatient = 'true';
            }else{
                $dnewPatient = 'false';
            }
            
            $SpecalityName = "";
            $specalityObj =  new  speciality();
            $where = "speciality_id IN (".$doctor->cdoctor_speciality.")";
            $specalityArg = array('where'=>$where);
            $specalitydata = $specalityObj->getAllRecords($specalityArg);
            
            foreach ($specalitydata as $skey => $sp_data) {
                $SpecalityName .= $sp_data->speciality_name.",";    
            }

            $LanguageName1 = "";
            $languageObj =  new  language();
            $where = "language_id IN (".$doctor->doctor_languages.")";
            $languageArg = array('where'=>$where);
            $languagedata = $languageObj->getAllRecords($languageArg);
            
            foreach ($languagedata as $lkey => $lang_data) {
                $LanguageName1 .= $lang_data->language_name.",";    
            }
            $LanguageName = wordwrap($LanguageName1, 25, '<br />', true);
            if($doctor->cdoctor_sikkaMap != '')
            {
                $sikkaMap = json_encode(json_decode($doctor->cdoctor_sikkaMap), JSON_PRETTY_PRINT);
            }else{
                $sikkaMap = '';
            }

            $notificationObj = new notification();
            $fields = array('count(notification_id) as notification');
            $where = array("notification_doctor_id="=>$doctor->doctor_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='providerfcmtokendetail.php?fcm_id=".$doctor->doctor_id."'>".$notification_count."</a>";    
            }else{
                $notificationdata = $notification_count;
            }

            $response[] = array('<input type="checkbox" name="check[]" id="check[]" value="'.$doctor->cdoctor_id.'" class="check_class" />', 
                    "<b>Xcare Provider Primary Id: </b>".$doctor->doctor_id."<br/><b>Global Provider Id: </b>".$doctor->doctor_unique_id."<br/><b>Clinic Provider Id: </b>".$doctor->cdoctor_provider_id,
                    "<b> Name: </b>".$doctor->clinic_name."</b></br><b>External Id: </b>".$doctor->clinic_unique_id."<br/><b>Phone: </b>".$doctor->clinic_phone."<br/><b>email: </b>".$doctor->clinic_email."<br/><b>Website: </b>".$doctor->clinic_website,
                    "<b>Name: </b>".$doctor->cdoctor_fullname."<br/><b>Gender: </b>".$doctor->doctor_gender."<br/><b>Email: </b>".$doctor->cdoctor_email."<br/><b>Phone: </b>".$doctor->cdoctor_phone."<br/><b>Licence No: </b>".$doctor->doctor_licence."<br/><b>Sikka code: </b>".$doctor->cdoctor_sikka_code."<br/><b>Sikka Mapping: </b>".$sikkaMap."<br/><b>Language Name: </b>".rtrim($LanguageName,",")."<br/><b>New Patient: </b>".$dnewPatient."<br><b>ShareCalender: </b>".$dshare_clender."<br/><b>Date: </b>".date('Y-m-d',strtotime($doctor->cdoctor_created_at))."<br><b>Specality</b>: ".rtrim($SpecalityName,",")."<br/><b>FCM Token Count</b> : ".$notificationdata,
                    /*"<b>Email : </b>".$doctor->cdoctor_email."<br/><b>New Patient : </b>".$dnewPatient."<br><b>ShareCalender : </b>".$dshare_clender."<br/><b>Date : </b>".date('Y-m-d',strtotime($doctor->cdoctor_created_at))."<br><b>Specality</b> : ".rtrim($SpecalityName,","),*/

                    "<b>Name: </b>".$doctor->doctor_login_fullname."<br/><b>Email: </b>".$doctor->doctor_login_email."<br/><b>Phone: </b>".$doctor->doctor_login_phone."<br><b>Phone Verified: </b>".$doctor->doctor_login_phone_verified."<br><b>Phone Vcode</b>: ".$doctor->doctor_login_pcode."<br><b>Email Verified</b>: ".$doctor->doctor_login_email_verified."<br><b>Email Vcode</b>: ".$doctor->doctor_login_ecode,

                    "<div id='td_status_".$doctor->cdoctor_id."'>".$status."</div>"."<br/><b>
                    <a href='doctordetail.php?doc_id=".$doctor->cdoctor_id."'>View</a></b>", 

                    //"<a href='doctoradd.php?act=edit&doctor_id=".$doctor->doctor_id."' class='btn btn-success white-btn'><i class='nav-icon i-Pen-2 '></i></a>
                    "<a id='delete-confirm' onclick='delete_entry(".$doctor->doctor_id.",".$doctor->clinic_id.");' class='btn btn-danger white-btn'><i class='nav-icon i-Close-Window '></i></a>"

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