<?php require_once('includes/check-login.php');
require_once('includes/config.php');
$tablename="subservices";
$viewurl="subservices.php";
if(isset($_POST['Add'])){
	    if(!file_exists(UPLOAD_SERVICEIMG)) {
          mkdir(UPLOAD_SERVICEIMG, 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_SERVICEIMG.$actual_name.".".$extension)){           
        $actual_name =$original_name.$j;
        $file_name = $actual_name.".".$extension;
        $j++;
        }         		
	    $d =move_uploaded_file($file_tmp,UPLOAD_SERVICEIMG.str_replace(' ','',$file_name));
		$image=str_replace(' ','',$file_name); 	
        $created=date("Y-m-d H:i:s");
        $query = "insert into ".$tablename." SET  service_id='".$_POST['service_id']."',service_name='".$_POST['service_name']."',image='".$image."',status='".$_POST['status']."',commission='".$_POST['commission']."',created='".$created."'";
		$exe = mysqli_query( $con, $query );		
		if( $exe ) {				
			$_SESSION[$tablename.'succ_msg'] = 'Service added successfully';
		}else{				
			$_SESSION[$tablename.'err_msg'] = 'Error occured';
		}
        header("Location:".$base_url.$viewurl."");
}
if(isset($_POST['Update'])){	
        $id=$_POST['id']; 
		if(isset($_FILES['image']["name"]) && $_FILES['image']["name"]!=null && $_FILES['image']["name"] !=""){
	    if(!file_exists(UPLOAD_SERVICEIMG)) {
          mkdir(UPLOAD_SERVICEIMG, 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_SERVICEIMG.$actual_name.".".$extension)){           
        $actual_name =$original_name.$j;
        $file_name = $actual_name.".".$extension;
        $j++;
        }         		
	    $d =move_uploaded_file($file_tmp,UPLOAD_SERVICEIMG.str_replace(' ','',$file_name));
		$image=str_replace(' ','',$file_name); 	
        $modified=date("Y-m-d H:i:s");
        $query = "update ".$tablename." SET service_id='".$_POST['service_id']."',service_name='".$_POST['service_name']."',image='".$image."',status='".$_POST['status']."',commission='".$_POST['commission']."',modified='".$modified."' WHERE id='".$_POST['id']."'";
		$exe = mysqli_query( $con, $query );		
		if( $exe ) {				
			$_SESSION[$tablename.'succ_msg'] = 'Service updated successfully';
		}else{				
			$_SESSION[$tablename.'err_msg'] = 'Error occured';
		}
        header("Location:".$base_url.$viewurl."");
}else{
	$modified=date("Y-m-d H:i:s");
     $query = "update ".$tablename." SET service_id='".$_POST['service_id']."',service_name='".$_POST['service_name']."',commission='".$_POST['commission']."',status='".$_POST['status']."',modified='".$modified."' WHERE id='".$_POST['id']."'";
	$exe = mysqli_query( $con, $query );		
	if( $exe ) {				
			$_SESSION[$tablename.'succ_msg'] = 'Service updated successfully';
	}else{				
			$_SESSION[$tablename.'err_msg'] = 'Error occured';
	}
    header("Location:".$base_url.$viewurl."");
}	   
}	  
	  
if(isset($_GET['id'])){
$display       = "Update";
$sql = "SELECT id,service_name,service_id,image,status,commission from ".$tablename." WHERE id = '".$_GET['id']."'";
$result = $con->query($sql);
$row=mysqli_fetch_array($result);
$id            = $row['id']; 
$service_id    = $row['service_id'];
$service_name  = $row['service_name'];
$image         = $row['image'];
$status        = $row['status'];  
$commission    = $row['commission'];  
}else{
$id            = ""; 
$service_id    = "";
$service_name  = "";
$image         = "";
$status        = "";
$commission    = "";
$display = "Add";
}	  
$sql_rslt = "SELECT id,service_name from services WHERE status='1'";
$result_rslt = $con->query($sql_rslt);
?>
<?php require_once('includes/header.php'); ?>
<?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="services.php">Sub Services</a></li>           
                    </ol>                
            </section>
<form id="serviceData" method="POST" enctype="multipart/form-data">
  <center><div class="message"></div></center>
    <div class="row setup-content">
      <div class="col-xs-6 col-md-offset-3">
        <div class="col-md-12">
            <center><h3>Sub Services</h3></center>
              <div class="form-group">
                <label class="control-label">Choose Service</label>
                <input type="hidden" name="id" value="<?php echo $id;?>">
               	<select name="service_id" class="form-control select2" required autofocus>
				<option value="" disabled selected>Choose</option>
				<?php if ($result_rslt->num_rows > 0) {
                while($row = $result_rslt->fetch_assoc()) {?>
				<option value="<?php echo $row['id'];?>" <?php if($service_id==$row['id']){ echo "selected";}?>><?php echo $row['service_name'];?></option>
				<?php }}?>
				</select>
              </div> 
              <div class="form-group">
                <label class="control-label">Service Name</label>               
                <input id="service_name" name="service_name" value="<?php echo $service_name; ?>" type="text" class="form-control" placeholder="Service Name"  />
              </div>  
              <div class="form-group">
                <label class="control-label">Commission (%)</label>               
                <input id="commission" name="commission" value="<?php echo $commission; ?>" type="number" class="form-control" placeholder="Commission"/>
              </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(isset($_GET['id'])){if(@is_array(getimagesize(UPLOAD_SERVICEIMG.$image))){?>
				<img id="imageshow" class="uploadimage" src="<?php echo $base_url.UPLOAD_SERVICEIMG.$image;?>" alt="image" style="display:initial;"/>
				<?php }} else {?>
			    <img id="imageshow" class="uploadimage" alt="image"/>
				<?php }?>
              </div>
              <div class="form-group">
                <label class="control-label">Status</label>
                 <select name="status" class="form-control select2" required>
				 <option value="" disabled selected>Choose</option>
				 <option value="1" <?php if($status=='1'){ echo "selected";}?>>Active</option>
				 <option value="0" <?php if($status=='0'){ echo "selected";}?>>Inactive</option>
				 </select>
              </div>  
			   <a href="<?php echo $base_url.$viewurl;?>" class="btn btn-primary btn-lg pull-left" >Back</a>
            <button class="btn btn-success btn-lg pull-right" 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 src="<?php echo $base_url;?>js/additional-methods.min.js"></script>
<script type="text/javascript">
$(function(){
       $("#serviceData").validate({
          rules: {
               service_name: 'required',
			   service_id: 'required',
			   image: {extension: "jpg|jpeg|png"},
               status:'required',  
           },
            messages: {
              image: {extension: "Please enter a value with a valid extension(jpg,jpeg,png)"},                         
            },
            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'); ?>