<?php require_once('includes/check-login.php');
require_once('includes/config.php');
$tablename="users";
$viewurl="profile.php";
$user_id=$_SESSION['userid'];
if(isset($_POST['Add'])){
    
}
if(isset($_POST['Update'])){	
    $id=$_POST['id']; 
    if(isset($_FILES['image']["name"]) && $_FILES['image']["name"]!=null && $_FILES['image']["name"] !=""){
	    if(!file_exists(UPLOAD_PROFILE)) {
          mkdir(UPLOAD_PROFILE, 0777, true);
        }
		$file_name=$_FILES["image"]["name"];
		$file_tmp=$_FILES["image"]["tmp_name"];
		$actual_name = pathinfo($file_name,PATHINFO_FILENAME);
        $original_name = $actual_name;
        $extension = pathinfo($file_name, PATHINFO_EXTENSION);
        $j = 1;
        while(file_exists(UPLOAD_PROFILE.$actual_name.".".$extension)){           
        $actual_name =$original_name.$j;
        $file_name = $actual_name.".".$extension;
        $j++;
        }         		
	    $d =move_uploaded_file($file_tmp,UPLOAD_PROFILE.str_replace(' ','',$file_name));
		$image=str_replace(' ','',$file_name); 	
		$_SESSION['profile_image'] =  $image;
        $query = "update user_details SET image='".$image."' WHERE user_id='".$id."'";
		$exe = mysqli_query($con,$query);	
	}
	$modified=date("Y-m-d H:i:s");
    $update=mysqli_query($con,"update ".$tablename." SET updated_at='".$modified."' WHERE id='".$id."'");
    $query="update user_details SET name='".$_POST['name']."',email='".$_POST['email']."',phone='".$_POST['phone']."' WHERE user_id='".$id."'"; 
	$exe=mysqli_query( $con, $query );		
	if( $exe ) {				
			$_SESSION[$tablename.'succ_msg'] = 'Profile updated successfully';
	}else{				
			$_SESSION[$tablename.'err_msg'] = 'Error occured';
	}
    header("Location:".$base_url.$viewurl."");
}	  
$sql=$con->query("SELECT user_details.* from ".$tablename." INNER JOIN user_details ON users.user_id=user_details.user_id WHERE users.user_id='$user_id'");
if(mysqli_num_rows($sql)>0){
$display       = "Update";
$row=mysqli_fetch_array($sql);
$id            = $row['user_id']; 
$name  = $row['name']; 
$phone  = $row['phone'];
$email = $row['email'];  
$image = $row['image']; 
}else{
$id    = ""; 
$name  = "";
$phone ="";
$email = "";
$image ="";
$display = "Add";
}	  
require_once('includes/header.php');
require_once('includes/menu.php'); ?>
<!------ Include the above in your HEAD tag ---------->
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
      <!-- Content Header (Page header) -->
            <section class="content-header">                               
                    <ol class="breadcrumb">
                        <li><a href="<?php echo $base_url;?>"><i class="fa fa-dashboard"></i>Home</a></li>                    
                        <li class="active"><a href="#">Profile Settings</a></li>           
                    </ol>                
            </section>
<form id="serviceData" method="POST" enctype="multipart/form-data">
    <div class="row setup-content">
      <div class="col-xs-6 col-md-offset-3">
        <div class="col-md-12">
            <center><h3>Profile Settings</h3></center>
            <center><?php if(isset($_SESSION[$tablename."succ_msg"])) {?>
                 <div class="alert alert-success">
                 <a href="#" class="close" data-dismiss="alert" aria-label="close" title="close">×</a>
                 <?php echo $_SESSION[$tablename."succ_msg"];  unset($_SESSION[$tablename."succ_msg"]);?>
                 </div>
                <?php }?>   
                <?php if(isset($_SESSION[$tablename."err_msg"])) {?>
                <div class="alert alert-success">
                <a href="#" class="close" data-dismiss="alert" aria-label="close" title="close">×</a>
                <?php echo $_SESSION[$tablename."err_msg"]; unset($_SESSION[$tablename."err_msg"]);?>
                </div>
               <?php }?>			  </center>
              <div class="form-group">
                <label class="control-label">Name</label>
                <input type="hidden" name="id" value="<?php echo $id;?>">
                <input  id="name" name="name" value="<?php echo $name; ?>" type="text" class="form-control" placeholder="Name"/>
              </div>  
              <div class="form-group">
                <label class="control-label">Email</label>
                <input  id="email" name="email" value="<?php echo $email;?>" type="text" class="form-control" placeholder="Email"/>
              </div> 
              <div class="form-group">
                <label class="control-label">Mobile Number</label>
                <input  id="phone" name="phone" value="<?php echo $phone;?>" type="number" class="form-control" placeholder="Mobile Number"/>
              </div> 
              <div class="form-group">
                <label class="control-label">Image</label>
                <input  type="file" id="image" name="image" value="<?php echo $image; ?>" class="form-control"/>
				<?php if(@is_array(getimagesize(UPLOAD_PROFILE.$image))){?>
				<img id="imageshow" class="uploadimage" src="<?php echo $base_url.UPLOAD_PROFILE.$image;?>" alt="image" style="display:initial;"/>
				<?php } else {?>
			    <img src="dist/img/avatar5.png" id="imageshow" class="uploadimage" alt="image"/>
				<?php }?>
              </div> 
              <button class="btn btn-success btn-lg" type="submit" name="<?php echo $display;?>"><?php echo $display;?></button>
        </div>
      </div>
    </div>
  </form>
</div>
<script src="js/common.js"></script>  
<script src="<?php echo $base_url;?>js/jquery-3.4.1.min.js"></script>
<script src="<?php echo $base_url;?>js/jquery.validate.min.js"></script>
<script type="text/javascript">
$(function(){
       $("#serviceData").validate({
          rules: {
               name: 'required',
               email: 'required',
               phone: 'required',
           },
            messages: {
                                  
            },
            submitHandler: function(form) {
              form.submit();
           }
    });        
});
function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('#imageshow').attr('src', e.target.result);
	  $('#imageshow').css('display','initial');
    }
    reader.readAsDataURL(input.files[0]);
  }
}
$("#image").change(function() {
  readURL(this);
});
</script>
<?php require_once('includes/footer.php'); ?>