<?php 
define('DOCUMENT_ROOT_CLASS','../');
define('DOCUMENT_ROOT_INC_FOLDER','');
$filepath = realpath(dirname(__FILE__));
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call_1"){
    require "../inc/ajax_header.php";
    /*echo "<pre>";
    print_r($_POST);*/
    $commonFunctions->updateData('sys_users'," WHERE id = '".$_POST['user_id']."' ", ' first_name = "'.$_POST['first_name'].'",father_name = "'.$_POST['father_name'].'" ,last_name = "'.$_POST['last_name'].'",roleid = "'.$_POST['roleid'].'",contact = "'.$_POST['contact'].'",email = "'.$_POST['email'].'"','');
    echo 'users-card.php?user_id='.$_POST['user_id'];
    exit();
}
require "../inc/header.php";
Session::CheckSession(); 
$msg = Session::get('msg');
Session::set("msg", NULL); 
if(!empty($_POST['action']) and @$_POST['action'] == "profile"){
    $column = $fileName = "";
    if($_FILES["logo"]){
        $target_dir = "../uploads/admin-setting/users/";
        $target_file = $target_dir . basename($_FILES["logo"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
        @getimagesize($_FILES["logo"]["tmp_name"]);
        if(move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)){
            $column = " logo";
            $fileName = " logo = '".$_FILES["logo"]["name"]."' ";
            $commonFunctions->updateData('sys_users'," WHERE id = '".$_POST['user_id']."' ", $fileName ,'users-card.php?user_id='.$_POST['user_id']);
        }
    }else{
        Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error !</strong> User profile picture not saved!</div>');
        echo "<script>location.href='users-card.php?user_id=".$_POST['user_id']."';</script>";
    }
    exit();
}
if(!empty($_POST['action']) and @$_POST['action'] == "reset_password"){
    if(!empty($_POST["password"])){
        $commonFunctions->updateData('sys_users'," WHERE id = '".$_POST['user_id']."' ", ' password = "'.SHA1($_POST['password']).'" ','users-card.php?user_id='.$_POST['user_id']);
    }else{
        Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error !</strong> Please enter password and confirm password!</div>');
        echo "<script>location.href='users-card.php?user_id=".$_POST['user_id']."';</script>";
    }
    exit();
}
if(!empty($_POST)){
    $error_ = 0;
    if(empty($_POST['username'])){
        Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error !</strong> Please enter code !</div>');
    }else{
        $id = !empty($_POST['user_id'])?$_POST['user_id']:0;
        $cntA = $commonFunctions->getRowData('sys_users',' WHERE id NOT IN('.$id.') AND username = "'.$_POST['username'].'" ');
        if(@count($cntA) > 1){
           $error_ = 1;
           Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error !</strong> Username already exists !</div>');
        }
    }

    if(!empty($_POST['username']) and $error_ == 0){
        if($_POST['action'] == "add"){
            $column = $fileName = "";
            if($_FILES["logo"]){
                $target_dir = "../uploads/admin-setting/users/";
                $target_file = $target_dir . basename($_FILES["logo"]["name"]);
                $uploadOk = 1;
                $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
                @getimagesize($_FILES["logo"]["tmp_name"]);
                if(move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)){
                    $column = " ,logo";
                    $fileName = " , '".$_FILES["logo"]["name"]."'";
                }
            }
            
            $commonFunctions->addData('sys_users'," (first_name,father_name,last_name,username,email,contact,roleid,isActive".$column.") VALUES ('".$_POST['first_name']."','".$_POST['father_name']."','".$_POST['last_name']."','".$_POST['username']."','".$_POST['email']."','".$_POST['contact']."','".$_POST['roleid']."','".$_POST['isActive']."' ".$fileName." ) ",'users-form.php?state=form');
        }
        if($_POST['action'] == "edit"){
            $column = $fileName = "";
            if($_FILES["logo"]){
                $target_dir = "../uploads/admin-setting/users/";
                $target_file = $target_dir . basename($_FILES["logo"]["name"]);
                $uploadOk = 1;
                $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
                @getimagesize($_FILES["logo"]["tmp_name"]);
                if(move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)){
                    $column = " ,logo";
                    $fileName = " ,logo = '".$_FILES["logo"]["name"]."' ";
                }
            }

            $commonFunctions->updateData('sys_users'," WHERE id = '".$_POST['user_id']."' ", " first_name = '".$_POST['first_name']."', father_name='".$_POST['father_name']."', last_name='".$_POST['last_name']."' , username='".$_POST['username']."' , email='".$_POST['email']."' , contact='".$_POST['contact']."', email='".$_POST['email']."', roleid ='".$_POST['roleid']."', isActive='".$_POST['isActive']."'".$fileName ,'users.php?state=list');
        }
    }else{
        echo "<script>location.href='users-form.php?state=form';</script>";
    }
}
?>    
<style type="text/css"> td.text-primary { cursor: pointer; } </style>
        
    <!-- Page-Title -->
    <div class="row">
        <div class="col-sm-12">
            <div class="page-title-box">
                <div class="row">
                    <div class="col">
                        <h4 class="page-title">Users</h4>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="javascript:void(0);">Settings</a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);">User Management</a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);">Users<?php echo (!empty($_GET['state']) and $_GET['state'] == "form")?" Form ":" List "; ?></a></li>
                        </ol>
                    </div><!--end col-->
                    <?php if($_GET['state'] != "list"){ ?>
                        <a href="users.php?state=list"><button type="button" class="btn btn-sm btn-outline-secondary clear_form">Back to Users List</button></a> 
                    <?php } ?>
                </div><!--end row-->                                                              
            </div><!--end page-title-box-->
        </div><!--end col-->
    </div><!--end row-->
    <!-- end page title end breadcrumb -->
    <div class="row">
        <div class="col-md-12">
            <?php echo !empty($msg)?$msg:''; ?>        
            <?php echo !empty($msg1)?$msg1:''; ?>
            
            <?php if(empty($_GET['state']) OR (!empty($_GET['state']) and $_GET['state'] == "list")): ?>
                <div class="row justify-content-center">
                    <div class="col-md-6 col-lg-3">
                        <div class="card report-card">
                            <div class="card-body">
                                <div class="row d-flex justify-content-center">
                                    <div class="col">
                                        <p class="text-dark mb-0 font-weight-semibold">Total Users</p>
                                        <h3 class="m-0"><?php echo $commonFunctions->getRowDataCount('sys_users',''); ?></h3>
                                    </div>
                                    <div class="col-auto align-self-center">
                                        <div class="report-main-icon bg-light-alt">
                                            <i data-feather="users" class="align-self-center text-muted icon-sm"></i>  
                                        </div>
                                    </div>
                                </div>
                            </div><!--end card-body--> 
                        </div><!--end card--> 
                    </div> <!--end col--> 
                    <div class="col-md-6 col-lg-3">
                        <div class="card report-card">
                            <div class="card-body">
                                <div class="row d-flex justify-content-center">                                                
                                    <div class="col">
                                        <p class="text-dark mb-0 font-weight-semibold">Active Users</p>                
                                        <h3 class="m-0"><?php echo $commonFunctions->getRowDataCount('sys_users',' WHERE isActive = 0 '); ?></h3>
                                    </div>
                                    <div class="col-auto align-self-center">
                                        <div class="report-main-icon bg-light-alt">
                                            <i data-feather="clock" class="align-self-center text-muted icon-sm"></i>  
                                        </div>
                                    </div> 
                                </div>
                            </div><!--end card-body--> 
                        </div><!--end card--> 
                    </div> <!--end col--> 
                    <div class="col-md-6 col-lg-3">
                        <div class="card report-card">
                            <div class="card-body">
                                <div class="row d-flex justify-content-center">                                                
                                    <div class="col">
                                        <p class="text-dark mb-0 font-weight-semibold">In-Active Users</p>
                                        <h3 class="m-0"><?php echo $commonFunctions->getRowDataCount('sys_users',' WHERE isActive = 1 '); ?></h3>
                                    </div>
                                    <div class="col-auto align-self-center">
                                        <div class="report-main-icon bg-light-alt">
                                            <i data-feather="clock" class="align-self-center text-muted icon-sm"></i>  
                                        </div>
                                    </div> 
                                </div>
                            </div><!--end card-body--> 
                        </div><!--end card--> 
                    </div> <!--end col--> 
                    <div class="col-md-6 col-lg-3">
                        <div class="card report-card">
                            <div class="card-body">
                                <div class="row d-flex justify-content-center">                                                
                                    <div class="col">
                                        <p class="text-dark mb-0 font-weight-semibold">Branches</p>
                                        <h3 class="m-0">0</h3>
                                    </div>
                                    <div class="col-auto align-self-center">
                                        <div class="report-main-icon bg-light-alt">
                                            <i data-feather="clock" class="align-self-center text-muted icon-sm"></i>  
                                        </div>
                                    </div> 
                                </div>
                            </div><!--end card-body--> 
                        </div><!--end card--> 
                    </div> <!--end col-->                        
                </div><!--end row-->
            <?php endif; ?>
            <?php if(!empty($_GET['state']) and $_GET['state'] != "edit" ){ ?>
                <form enctype="multipart/form-data" action="users-form.php?state=form&action=add" method="post" name="formsoc" autocomplete="off">      
                    <div class="tab-content" id="pills-tabContent">
                        <!-- User Profile - Start --->
                        <div class="tab-pane fade show active">
                            <div class="row">
                                <div class="col-lg-6 col-xl-6">
                                    <div class="card">
                                        <div class="card-header">
                                            <div class="row align-items-center">
                                                <div class="col-11">                      
                                                    <h4 class="card-title text-left">User Details ( Personal )</h4>                      
                                                </div><!--end col-->                                                     
                                            </div>  <!--end row-->                                  
                                        </div><!--end card-header-->
                                        <div class="card-body">                              
                                            <input type="hidden" name="action" value="<?php echo !empty($_GET['user_id'])?'edit':'add';?>">
                                            <input type="hidden" name="user_id" value="<?php echo @$_GET['user_id'];?>">
                                            <!-- <input type="hidden" name="isActive" value="1"> -->
                                            <div class="form-group row">
                                                <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">First Name</label>
                                                <div class="col-lg-9 col-xl-8">
                                                    <input type="text" maxlength="128" name="first_name" id="first_name" value="<?php echo @$editData['first_name'];?>" autofocus="autofocus" class="form-control" placeholder="First Name">
                                                </div>
                                            </div>
                                            <div class="form-group row">
                                                <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Middle Name</label>
                                                <div class="col-lg-9 col-xl-8">
                                                    <input type="text" maxlength="128" name="father_name" id="father_name" value="<?php echo @$editData['father_name'];?>" autofocus="autofocus" class="form-control" placeholder="Middle Name">
                                                </div>
                                            </div>
                                            <div class="form-group row">
                                                <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Last Name</label>
                                                <div class="col-lg-9 col-xl-8">
                                                    <input type="text" maxlength="128" name="last_name" id="last_name" value="<?php echo @$editData['last_name'];?>" autofocus="autofocus" class="form-control" placeholder="Last Name">
                                                </div>
                                            </div>
                                            <div class="form-group row">
                                                <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Mobile Number</label>
                                                <div class="col-lg-9 col-xl-8">
                                                    <div class="input-group">
                                                        <div class="input-group-prepend"><span class="input-group-text"><i class="las la-phone"></i></span></div>
                                                        <input type="text" maxlength="128" name="contact" id="contact" value="<?php echo @$editData['contact'];?>" autofocus="autofocus" class="form-control" placeholder="Mobile Number">
                                                    </div>
                                                </div>
                                            </div>
                                             
                                            <div class="form-group row">
                                                <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Email ( Personal ) <span class="error">*</span></label>
                                                <div class="col-lg-9 col-xl-8">
                                                    <div class="input-group">
                                                        <div class="input-group-prepend"><span class="input-group-text"><i class="las la-at"></i></span></div>
                                                        <input type="text" maxlength="128" name="email" id="email" value="<?php echo @$editData['email'];?>" autofocus="autofocus" class="form-control" placeholder="Personal eMail" required="">
                                                    </div>
                                                </div>
                                            </div>
                                                                                        
                                        </div>                                            
                                    </div>
                                </div>  

                                <div class="col-lg-6 col-xl-6">
                                    
                                    <div class="card">
                                        <div class="card-header">
                                            <h4 class="card-title">User Credentials</h4>
                                        </div> 
                                        <div class="card-body"> 
                                            <div class="form-group row">
                                                <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">UserName <span class="error">*</span></label>
                                                <div class="col-lg-9 col-xl-8">
                                                    <input type="text" maxlength="128" name="username" id="username" value="<?php echo @$editData['username'];?>" autofocus="autofocus" class="form-control" placeholder="UserName" required="">
                                                </div>
                                            </div>  
                                            <!-- <div class="form-group row">
                                                <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">New Password</label>
                                                <div class="col-lg-9 col-xl-8">
                                                    <input type="password" maxlength="128" name="password" id="password" value="" autofocus="autofocus" class="form-control" placeholder="Password">
                                                </div>
                                            </div>
                                            <div class="form-group row">
                                                <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Confirm Password</label>
                                                <div class="col-lg-9 col-xl-8">
                                                    <input type="text" maxlength="128" name="cnf_password" id="cnf_password" value="" autofocus="autofocus" class="form-control" placeholder="Confirm Password">
                                                </div>
                                            </div>  -->
                                            <div class="form-group row">
                                                <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Staff Type</label>
                                                <div class="col-lg-9 col-xl-8">
                                                    <?php $optionData = $commonFunctions->getData('sys_roles',' WHERE id != 1 AND isActive = 0 '); ?>
                                                    <select class="form-control" name="roleid" id="roleid">
                                                      <?php foreach ($optionData as $key) { ?>
                                                        <option value="<?php echo $key['id'];?>" <?php echo (!empty(@$editData['roleid']) and $key['id'] == $editData['roleid'])?"selected":""; ?> ><?php echo $key['role'];?></option>
                                                      <?php } ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="form-group row">
                                                <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Status</label>
                                                <div class="col-lg-9 col-xl-8">
                                                    <select class="form-control" name="isActive">
                                                        <option value="0">Active</option>
                                                        <option value="1">Inactive</option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="form-group row">
                                                <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">User Photo (Avatar)</label>
                                                <div class="col-lg-9 col-xl-8">
                                                    <input type="file" name="logo" >
                                                </div>
                                            </div>  

                                        </div> 
                                    </div>
                                </div> <!-- end col -->                                                                              
                            </div><!--end row-->
                        </div>
                        <!-- User Profile - End --->
                    </div>
                    <div class="page-title-box">
                        <div class="row">
                            <div class="col-auto align-self-center">
                                <button type="submit" class="btn btn-sm btn-success waves-effect waves-light"><i class="fas fa-times-circle align-self-center icon-xs"></i> Save</button>
                                <a href="users.php?state=list" class="btn btn-sm btn-danger waves-effect waves-light">
                                    <i class="fas fa-times-circle align-self-center icon-xs"></i> Cancel
                                </a>
                            </div><!--end col-->  
                        </div><!--end row-->                                                              
                    </div><!--end page-title-box-->                      
                </form>
            <?php } ?>
        </div> <!-- end col -->
    </div> <!-- end row -->
    
<?php require "../inc/footer.php"; ?>
<script type="text/javascript">
$("#clearbtn").click(function(){
    $("#search").val('');
    $("#searchForm").submit();
});
function redirect_(uri){
    window.location.href = uri;
}
$(".dastone-profile_main-pic-change").click(function(){
    $("#fileUpload").click();
});
$("#fileUpload").change(function(){
    if(confirm("Please make sure do you want to change your profile picture?")){
        $("#fileUploadForm").submit();
    }else{
        return false;
    }
});
$(".FormBtn").click(function(){
    $.ajax({
        type: 'POST',
        url: "",
        data: $('.personalInfoForm').serialize()+"&"+$('.contactInfoForm').serialize()+"&action=ajax_call_1",
        success: function(response) { 
          window.location.href = response;
        }
    });
});
</script>