<?php 
// Include main file
include_once('../libs/main.php');
// Check admin Login
include_once('checkLogin.php');
// Logical section of page
$userObj =  new  user();
$adminlogObj = new admin_log();
$modulepagesObj = new module_pages();
$filename=basename($_SERVER['SCRIPT_FILENAME']);
 
if($filename == 'userlist.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['user_id'])){
    $userDetailLog = $userObj->fromId($_REQUEST['user_id']);
    if($userDetailLog->user_status == '1')
    {
        $user_status = 'Active';
    }else{
        $user_status = 'Inactive';
    }
    $user_detail = " <b>Id</b>:".$_REQUEST['user_id']." <br/>
                     <b>Name</b>:".$userDetailLog->user_fname." ".$userDetailLog->user_lname." <br/>
                     <b>Change Status Old data</b> ".$user_status;
    if(isset($_REQUEST['status'])){

        if($_REQUEST['status'] == '1')
        {
            $userstatusnew = 'Active';
        }else{
            $userstatusnew = 'Inactive';
        }
        $user_detail .= " <b>To</b> ".$userstatusnew;

        $userObj->changeStatus($_REQUEST['user_id']);
        echo RECORD_STATUS;

        $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,$user_detail);
    }
    return true;
}
if(isset($_REQUEST['act']) && $_REQUEST['act']=='delete' && isset($_REQUEST['user_id'])){

    $userData = $userObj->fromId($_REQUEST['user_id']);

    $user_detail = " <b>Delete record id</b>:  ".$_REQUEST['user_id']." and Name:- ".$userData->user_fname." ".$userData->user_lname." and <b>Email</b>: ".$userData->user_email_address;

    $data['user_isdeleted'] = '1';
    $rs=$userObj->updateRecords($data,$_REQUEST['user_id']);

    //$userObj->deleteFromId($_REQUEST['user_id']);
    $successMsg = base64_encode(RECORD_DELETE);

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

    if($rs)
    {
        header('Location:userlist.php');
        exit;
    }
}
if(isset($_REQUEST['action']) && $_REQUEST['action']!=''){
    if($_REQUEST['action']=="activate_all"){
        $data=array("user_status" => '1');
        $chk_data = $_POST['check'];
        foreach($chk_data as $akey => $val_actchk)
        {
            $old_data = $userObj->fromId($val_actchk);
            if($old_data->user_status == '1')
            {
                $old_status = 'Active';
            }else{
                $old_status = 'Inactive';
            }

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

            if($old_data->user_status != '0')
            {
                $new_status = 'Inactive';
                $userdata = " <b>Id</b>:".$val_actchk." <br/><b> Change Status</b>: "." ".$old_status." <b>To</b> ".$new_status." ";
                $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,$userdata);
            }
        }
        $rs = $userObj->updateManyRecords($data, $_POST['check']);
        $successMsg = base64_encode(RECORD_ALL_INACTIVE);
    }else if($_REQUEST['action']=="delete_all"){

        $chk_del = implode(",",$_POST['check']);
        
        $userdata = " <b>Delete Id</b>: "." ".$chk_del;
        $admin_log = $adminlogObj->addAdminLog($_SESSION['admin_id'],$module_id,$page_id,$pagename,$userdata);

        $rs = $userObj->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 AND user_isdeleted ='0' ";

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

        //$where .= " AND ('".$fullname."' LIKE Concat(Concat('',user_fname),'') 
                   // OR '".$fullname."' LIKE  Concat(Concat('',user_lname),''))";;

       $where .=" AND CONCAT(user_fname,'',user_lname) LIKE '%".$fullname."%' ";
    }*/

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

        $where .= " AND ((user_fname='".($firstname)."' and   user_lname='".($lastname)."') OR (user_fname='".(ucfirst($firstname))."' and   user_lname='".(ucfirst($lastname))."'))";
    }else if(isset($_REQUEST['firstname']) && $_REQUEST['firstname'] != '' && $_REQUEST['lastname'] == ''){

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

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

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

        $where .= " AND ((user_lname LIKE '%".($lastname)."%') OR ( user_lname LIKE '%".(ucfirst($lastname))."%'))";
    }
    
    if(isset($_REQUEST['user_unique_id']) && $_REQUEST['user_unique_id'] != '')
    {
        $where .= " AND user_unique_id = '".$_REQUEST['user_unique_id']."'";
    }
    
    if(isset($_REQUEST['user_email']) && $_REQUEST['user_email'] != '')
    {
        $where .= " AND  user_email_address = '".$_REQUEST['user_email']."' ";
    }
    
    if(isset($_REQUEST['user_status']) && $_REQUEST['user_status'] != '')
    {
        $where .= " AND  user_status = '".$_REQUEST['user_status']."' ";
    }

    if(isset($_REQUEST['user_customer_id']) && $_REQUEST['user_customer_id'] != '')
    {
        $data = '%"customerId"'.":".'"'.$_REQUEST['user_customer_id'].'"'."%".'';
        
        $where .="AND user_stripedata LIKE '".$data."'";
    }

    if(isset($_REQUEST['user_id']) && $_REQUEST['user_id'] != '')
    {
        $where .= " AND user_id = '".$_REQUEST['user_id']."'";
    }
    if(isset($_REQUEST['user_date']) && $_REQUEST['user_date'] != '')
    {
        $where .= " AND date(user_created_at) = '".$_REQUEST['user_date']."'";
    }
    if(isset($_REQUEST['user_clinic']) && $_REQUEST['user_clinic'] != '')
    {
        //$where .= " AND c.clinic_user_id = '".$_REQUEST['user_clinic']."'";
        $permissionObj = new permission();
        $pmwhere = array("permission_model_id="=>$_REQUEST['user_clinic'],'permission_model_type='=>'Clinic');
        $permissionArg = array('where'=>$pmwhere);
        $permissionExist = $permissionObj->getAllRecords($permissionArg);

        if(!empty($permissionExist))
        {
            foreach($permissionExist as $pkey => $pvalue)
            {
                $p_userId .= $pvalue->permission_user_id.",";
            }
            $all_puserId = rtrim($p_userId,",");
        }
        $puser_val = explode(",",$all_puserId);
        $data_puser =  "'".implode ( "','", $puser_val )."'";
        $where .= " AND user_id IN  (".$data_puser.") ";
    }


    
    if (isset($_REQUEST['search']['value']) && $_REQUEST['search']['value']!=""){
        $where = " user_unique_id LIKE '%".$_REQUEST['search']['value']."%' OR user_id LIKE '%".$_REQUEST['search']['value']."%' OR user_fname LIKE '%".$_REQUEST['search']['value']."%' OR user_lname LIKE '%".$_REQUEST['search']['value']."%' OR user_email_address LIKE '%".$_REQUEST['search']['value']."%' OR date(user_created_at) LIKE '%".$_REQUEST['search']['value']."%' ";
    }    
    //$orderFields = array('user_id', 'user_fname', 'user_email_address','user_created_at','user_status');

    $orderFields = array('','user_id','user_fname','','','user_created_at','user_status');    
    
    // 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(" user_id desc ");
    }
    //print_r($orderby);exit;
    
    $data    = array('where' => $where,'limit' => $limit, 'orderBy'=>$orderby);

    $userDetails = $userObj->getAllRecords($data);

    $recordsTotal   =   $userObj->getAllCount($data);

        
    if ($userDetails && count($userDetails)>0){
        foreach ($userDetails as $key => $user){

            $stripecardObj = new stripecard();
            $where = array("stripecard_user_id="=>$user->user_id,'stripecard_status='=>'Active');
            $stripeArg = array('where'=>$where);
            $cardExist = $stripecardObj->FromFields($stripeArg);
            $last4="";
            if($cardExist){
                $last4 = "*****".$cardExist->stripecard_last4;
            }

            if($user->user_status =='1'){
              $status = '<a href="javascript:void(0)" onclick="change_status('.$user->user_id.',0)" title="Inactivate"><span class="badge badge-success">Active</span></a>';
            }else{
              $status = '<a href="javascript:void(0)" onclick="change_status('.$user->user_id.',1)" title="Activate"><span class="badge badge-danger">Inactive</span></a>';
            }
            $customerdata = json_decode($user->user_stripedata,1);
            if($customerdata && $customerdata > 0 )
                { 
                    foreach ($customerdata as $key => $customer_value) 
                    {
                        if($key == 'customerId')
                        {
                            $customerId = $customer_value; 

                        }
                    }
                }

            if($user->user_owner == '1')
            {
               $userowner = 'Yes'; 
            }else{
                $userowner = 'No';
            }

            $action = '<a href="changepassword.php?user_id='.$user->user_id.'&user_type=user" class="btn btn-success white-btn"><i class="nav-icon i-Lock " title="Change Password"></i></a>
                 <a href="useradd.php?act=edit&user_id='.$user->user_id.'" class="btn btn-success white-btn"><i class="nav-icon i-Pen-2 "></i></a>
                 <a id="delete-confirm" onclick="delete_entry('.$user->user_id.');" class="btn btn-danger white-btn"><i class="nav-icon i-Close-Window "></i></a>';

            $response[] = array('<input type="checkbox" name="check[]" id="check[]" value="'.$user->user_id.'" class="check_class" />',
                    "<b>Xcare User Id: </b>".$user->user_id."<br/><b>External Id :</b>".$user->user_unique_id, 
                    "<b>First Name: </b>".$user->user_fname."<br><b>Last Name: </b>".$user->user_lname."<br/><b>Email: </b>".$user->user_email_address."<br/><b>Owner: </b>".$userowner,
                    "<b>Card: </b>".$last4."<br/><b>customerId: </b>".$customerId,
                    "<b>Fax Host </b> : ".$user->user_emailHost."<br/><b>Fax Email </b> : ".$user->user_faxEmail."<br/><b>Fax Password</b> : ".$user->user_faxPassword."<br/><b>Mango Call User: </b>".$user->user_mangoCallUser,
                    date('Y-m-d H:i:s',strtotime($user->user_created_at))."<br/><b>Login ip</b> :".$user->user_last_login_ip."<br><b>Last Login: </b>".$user->user_last_login_at,
                    "<div id='td_status_".$user->user_id."'>".$status."</div>",    
                    $action
             );
        }
        $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');
?>