<?php
include_once("../include/main.inc.php");
check_session('MyCpanel','index.php');

################ Paging Starts From Here ##################
@extract($_REQUEST);
$start = (intval($start)==0 or $start=="")?$start=0:$start;
$pagesize = intval($pagesize)==0?$pagesize=100:$pagesize;
if($parentID=="") {
	$parentID=1;
}
$heading="Manage Products";
$record_type="Products";
$script_name="manage_products.php";
$table_name="product_tbl";

if($id=="add_record") {

$file_name_array = [];
	if(count($_FILES['image']) > 0){
        if($_FILES['image']['name']!=''){
		foreach($_FILES["image"]["tmp_name"] as $key=>$tmp_name) {
		    $file_name=$_FILES["image"]["name"][$key];
		    $file_tmp=$_FILES["image"]["tmp_name"][$key];
		    $ext=pathinfo($file_name,PATHINFO_EXTENSION);   
		    $filename=basename($file_name,$ext);
			$filename=str_replace('.','-',$filename);
			$filename=str_replace(' ','-',$filename);
            $newFileName=$filename.time().".".$ext;
		    move_uploaded_file($file_tmp=$_FILES["image"]["tmp_name"][$key],"../uploaded-files/product-images/".$newFileName);
		    array_push($file_name_array, $newFileName);
		}
		$file_name1 = implode(',', $file_name_array);
        }
	}
	$prouct_cat = implode(',',$_POST['product_id']);
	echo 
		$sql=db_query("insert into $table_name set product_title='$product_title',product_name='$product_name', product_code='$product_code', product_image='$file_name1', product_specfi='$product_specfi', product_cat='$prouct_cat',  prodcut_subcat='$subcat', product_subsubcat='$subsubcat', product_video='$link'");
				
		$_SESSION['session_message']='<div class="btn btn-success">New '.$record_type.' has been added successfully</div>';
		header("Location: ".SITE_ADMIN_URL."/".$script_name."?start=".$start."&pagesize=".$pagesize);
		exit;
	}

	if(isset($_REQUEST['id']) && $_REQUEST['id']=='delete'){

	$name = $_REQUEST['name'];
	$cat_id = $_REQUEST['cat_id'];
	$delete_sql = mysqli_query($dbconn,"SELECT * FROM $table_name WHERE product_id='$cat_id'");
	$result = mysqli_fetch_array($delete_sql);
	if(count($result) > 0){
		$image_array = explode(',',$result['product_image']);
		if(in_array($name, $image_array)){
			$new_array = array_diff($image_array, [$name]);
			$file_name = implode(',',$new_array);
			$table = mysqli_query($dbconn,"UPDATE $table_name SET product_image='$file_name' WHERE product_id='$cat_id'");
		}	
	}
	
}
if($id=="update_record") {
		$prod_sql = mysqli_query($dbconn,"SELECT * FROM $table_name where product_id='$recordID'");
		$prod_res = mysqli_fetch_array($prod_sql);
		if(count($prod_res) > 0){
			$file_name_array = [];
$image = $_FILES['image'];
if($image['size'][0]!=0){
		foreach($_FILES["image"]["tmp_name"] as $key=>$tmp_name) {
		    $file_name=$_FILES["image"]["name"][$key];
		    $file_tmp=$_FILES["image"]["tmp_name"][$key];
		    $ext=pathinfo($file_name,PATHINFO_EXTENSION);   
		    $filename=basename($file_name,$ext);
			$filename=str_replace('.','-',$filename);
			$filename=str_replace(' ','-',$filename);
		    $newFileName=$filename.date('s').".".$ext;
		    move_uploaded_file($file_tmp=$_FILES["image"]["tmp_name"][$key],"../uploaded-files/product-images/".$newFileName);
		    array_push($file_name_array, $newFileName);
		}

		$file_name1 = implode(',', $file_name_array);
		$file_array = explode(',',$prod_res['product_image']);
			$new_array = array_merge($file_array, $file_name_array);
			$file_name1 = implode(',', $new_array);	
			mysqli_query($dbconn,"UPDATE $table_name SET product_image='$file_name1' WHERE product_id='$recordID'");
	}
	
		}
        $prouct_cat = implode(',',$_POST['product_id']);
		updateTable($table_name,"product_title='$product_title',product_name='$product_name', product_video='$link', product_code='$product_code', product_alt='$palt', product_desc='$cdesc', product_metatitle='$cmtitle', product_metadesc='$cmdesc', product_metakeyword='$cmkey', product_cat='$prouct_cat', prodcut_subcat='$subcat', product_subsubcat='$subsubcat', product_specfi='$product_specfi', product_finalcat='$finalcat', product_min_order='$pminorder', product_supply='$psupply', product_swearType='$pswearType', product_supplyType='$psupplyType', product_Gender='$pgenser', product_ageGroup='$pagegroup', product_size='$psize', product_origin='$porigin', product_pterms='$pterms', product_price='$pprice' where product_id='$recordID'");
		
		$_SESSION['session_message']='<div class="btn btn-success">'.$record_type.' has been updated successfully</div>';
		header("Location: ".SITE_ADMIN_URL."/".$script_name."?start=".$start."&pagesize=".$pagesize);
		exit;
	}
	
	else {
	
	}	
if($id=="delete_record") {
	db_query("delete from $table_name where product_id='$recordID'");
	$_SESSION['session_message']='<div class="alert alert-danger" role="alert">'.$record_type.' has been deleted successfully</div>';
	header("Location: ".SITE_ADMIN_URL."/".$script_name."?start=".$start."&pagesize=".$pagesize);
	exit;
}

if(isset($feature_pro)){
	foreach($pro_arr as $id){
		mysqli_query($dbconn,"UPDATE $table_name SET product_theme = '1' where product_id='$id'");
	}
	$_SESSION['session_message']='<div class="btn btn-warning">' . $record_type . ' has been set as Feature Product</div>';
		header("Location: ".SITE_ADMIN_URL."/".$script_name."?start=".$start."&parentID=".$parentID."&catID=".$catID."&pagesize=".$pagesize);
		exit;
}

admin_header();
?>
<form name="bannerFrm" method=post action="" enctype="multipart/form-data" onsubmit="return validate('bannerFrm') && chk_valid_date();">
   <?php
 if($_GET['recordID']=="" || $id!="edit_record") {
	 ?>
    <div class="form-group">
         <h3>Add New <?=$record_type;?></h3>
    </div>
     <?php
 }
 else {
	 ?>
    <div class="form-group">
         <h3>Edit <?=$record_type;?></h3>
    </div>
        <div class="form-group text-right">
         <a href="<?=$script_name;?>" class="btn btn-primary text-white"><b>Add New <?=$record_type;?></b></a>
    </div>
<?php
 }
 $res=getResult($table_name," where product_id='$_GET[recordID]'");
 ?>
    
<div class="form-group">
      <label for="cate">Product Title <font color="red">*</font></label>
       <?php
 if($_GET['recordID']=="" || $id!="edit_record") {
	 ?>
        <input type="text" name="product_title" class="form-control" value="" placeholder="Product Title ">
         <?php
 }
 else { ?>
      <input type="text" name="product_title" class="form-control" value="<?=$res['product_title']?>" placeholder="Product Title ">
    <?php } ?>
</div>   
<div class="form-group">
      <label for="cate">Product Name (For Url) <font color="red">*</font></label>
       <?php
 if($_GET['recordID']=="" || $id!="edit_record") {
	 ?>
        <input type="text" name="product_name" class="form-control" value="" placeholder="Product Name (Do not use special character">
         <?php
 }
 else { ?>
      <input type="text" name="product_name" class="form-control" value="<?=$res['product_name']?>" placeholder="Do not use special character ">
    <?php } ?>
</div>   
<div class="form-group">
      <label for="cate">Product Code <font color="red">*</font></label>
        
           <?php
 if($_GET['recordID']=="" || $id!="edit_record") {
	 ?>
        <input type="text" name="product_code" class="form-control" value="" placeholder="Product Code  ">
         <?php
 }
 else { ?>
      <input type="text" name="product_code" class="form-control" value="<?=$res['product_code']?>" placeholder="Product code ">
    <?php } ?>
</div>   
    <div class="form-group">
      <label for="cate">Product Video Link <font color="red">*</font></label>
        
           <?php
 if($_GET['recordID']=="" || $id!="edit_record") {
	 ?>
        <input type="text" name="link" class="form-control" value="" placeholder="Product Code  ">
         <?php
 }
 else { ?>
      <input type="text" name="link" class="form-control" value="<?=$res['product_video']?>" placeholder="Product video link ">
    <?php } ?>
</div> 
<div class="form-group">
		<label for="cate">Select Category<font color="red">*</font></label>
		<ul class="awardsChecks">
			<?php
			$sql_cat = mysqli_query($dbconn, "select * from category_tbl where parentID='0'");
			while ($res_cat = mysqli_fetch_assoc($sql_cat)) {
				$catids = explode(',', $res['product_cat']);
				$checked =  in_array($res_cat['catID'], $catids) ? 'checked' : '';
			?>
				<li class="first"><label><input type="checkbox" name="product_id[]" value="<?php echo $res_cat['catID']; ?>" <?= $checked; ?>><?php echo $res_cat['catName']; ?></label>
					<ul>
						<?php
						$sql_cat_sub = mysqli_query($dbconn, "select * from category_tbl where parentID='$res_cat[catID]'");
						while ($res_cat_sub = mysqli_fetch_assoc($sql_cat_sub)) {
							$checked =  in_array($res_cat_sub['catID'], $catids) ? 'checked' : '';
						?>
							<li><label><input type="checkbox" name="product_id[]" value="<?php echo $res_cat_sub['catID']; ?>" <?= $checked; ?>> <?php echo $res_cat_sub['catName']; ?></label>
							<ul>
						<?php
						$sql_cat_subsub = mysqli_query($dbconn, "select * from category_tbl where parentID='$res_cat_sub[catID]'");
						while ($res_cat_subsub = mysqli_fetch_assoc($sql_cat_subsub)) {
							$checked =  in_array($res_cat_subsub['catID'], $catids) ? 'checked' : '';
						?>
							<li><label><input type="checkbox" name="product_id[]" value="<?php echo $res_cat_subsub['catID']; ?>" <?= $checked; ?>> <?php echo $res_cat_subsub['catName']; ?></label>
							<ul>
						<?php
						$sql_cat_subsubsub = mysqli_query($dbconn, "select * from category_tbl where parentID='$res_cat_subsub[catID]'");
						while ($res_cat_subsubsub = mysqli_fetch_assoc($sql_cat_subsubsub)) {
							$checked =  in_array($res_cat_subsubsub['catID'], $catids) ? 'checked' : '';
						?>
							<li><label><input type="checkbox" name="product_id[]" value="<?php echo $res_cat_subsubsub['catID']; ?>" <?= $checked; ?>> <?php echo $res_cat_subsubsub['catName']; ?></label></li>
						<?php } ?>
					</ul>
						</li>
						<?php } ?>
					</ul>
						
						</li>
						<?php } ?>
					</ul>
				</li>
			<?php } ?>
		</ul>
    
<!-- <div class="form-group">
      <label for="cate">Select Category<font color="red">*</font></label>
        <select class="form-control" name="cat" id="quickCity">
            <option>Select Category</option>
            <?php
$sql_cat=mysqli_query($dbconn,"select * from category_tbl where parentID='0'");
while ($res_cat=mysqli_fetch_array($sql_cat))
{
?>
<option value="<?php echo $res_cat['catID']; ?>" <? if ($res['product_cat']==$res_cat['catID']) { echo "selected"; }?>><?php echo $res_cat['catName']; ?></option>
<?php
}
?>
    </select>
    </div>
    <div class="form-group">
      <label for="cate">Select Sub Category<font color="red">*</font></label>
        <select class="form-control" name="subcat" id="locatity">
            <option>Select Category</option>
            <?php
$sql_tl=mysqli_query($dbconn,"select * from category_tbl where parentID='$res[product_cat]' and parentID!=''");
 if(mysqli_num_rows($sql_tl) > 0)
 {
 while($qq_res=mysqli_fetch_array($sql_tl))
 {
?>
<option value="<?php echo $qq_res['catID']; ?>" <? if ($res['prodcut_subcat']==$qq_res['catID']) { echo "selected"; }?>><?php echo $qq_res['catName']; ?></option>
<?php
}
 }
?>
    </select>
</div> 
<div class="form-group">
	<label for="cate">Select Sub Sub-Category<font color="red">*</font></label>
	<select class="form-control" name="subsubcat" id="asd">
		<option>Select Category</option>
		<?php
		$sub_sql_tl=mysqli_query($dbconn,"select * from category_tbl where parentID='$res[prodcut_subcat]' and parentID!=''");
		if(mysqli_num_rows($sub_sql_tl) > 0)
		{
		while($sub_res=mysqli_fetch_array($sub_sql_tl))
		{
		?>
		<option value="<?php echo $sub_res['catID']; ?>" <? if ($res['product_subsubcat']==$sub_res['catID']) { echo "selected"; }?>><?php echo $sub_res['catName']; ?></option>
		<?php
		}
		}
		?>
	</select>
</div>
<div class="form-group">
	<label for="cate">Select sub Sub Sub-Category<font color="red">*</font></label>
	<select class="form-control" name="subsubcat" id="asd">
		<option>Select Category</option>
		<?php
		$subsub_sql_tl=mysqli_query($dbconn,"select * from category_tbl where parentID='$sub_res[prodcut_subcat]' and parentID!=''");
		if(mysqli_num_rows($sub_sql_tl) > 0)
		{
		while($sub_res=mysqli_fetch_array($sub_sql_tl))
		{
		?>
		<option value="<?php echo $sub_res['catID']; ?>" <? if ($res['product_subsubcat']==$sub_res['catID']) { echo "selected"; }?>><?php echo $sub_res['catName']; ?></option>
		<?php
		}
		}
		?>
	</select>
</div> -->
<div class="form-group">
      <label for="cate">Product Specification <font color="red">*</font></label>
        
           <?php
 if($_GET['recordID']=="" || $id!="edit_record") {
	 ?>
    <textarea type="text" name="product_specfi" id="catDesc1" class="form-control" value="" placeholder="Product Specification"></textarea>
         <?php
 }
 else { ?>
     <textarea type="text" name="product_specfi" id="catDesc1" class="form-control" value="" placeholder="Product Specification">
         <?=$res['product_specfi'];?></textarea>
    <?php } ?>
    <script type="text/javascript">
	var oFCKeditor=new FCKeditor('catDesc1');
	oFCKeditor.BasePath="fckeditor/";
	oFCKeditor.Width="600px";
	oFCKeditor.Height="400px";
	oFCKeditor.ReplaceTextarea();
	</script>
</div>  
  
        <div class="form-group">
      <label for="multimage">Multiple Image<font color="red">*</font></label>
        <input type="file" name="image[]" class="form-control" multiple size="60" value="" id="NOBLANK~Please enter Person Name.~DM~" />
    </div>
    <?php
if($res['product_image']!=""){
	$image_array = explode(',', $res['product_image']);?>




	
	<div class="display-img">
	<ul>
	<?php foreach($image_array as $image){?>
				<li>
					
						
<img src="<?=site_url;?>/uploaded-files/product-images/<?= $image ?>">
					
						<div class="card-footer">
							<a href="?id=delete&name=<?= $image ?>&cat_id=<?= $res['product_id'] ?>" onclick="confirm('Do you want to delete the image?')">Delete</a>
						</div>
				
				</li>
			<?php } ?>
	</ul>
</div>
<?php } ?>
    <div class="form-group">
           <?php
   if($recordID !="") {
	   ?>
	   <input type="submit" class="btn btn-primary" name="submit" value="Update <?=$record_type;?>" class="button">
	   <input type="hidden" name="recordID" value="<?=$res['product_id'];?>">
	   <input type="hidden" name="id" value="update_record">
	   <?php	   
   }
   else{
	   ?>
	   <input type="submit" class="btn btn-primary" name="submit" value="Add New <?=$record_type;?>" class="button">
	   <input type="hidden" name="id" value="add_record">
	   <?php
   }
   ?>
   <input type="hidden" name="start" value="<?=$start;?>">
   <input type="hidden" name="pagesize" value="<?=$pagesize;?>">
    </div>
</form>
<div class="table-responsive">

<table width="99%" border="0" align="center" cellpadding="0" cellspacing="0" valign="top">
    <tr>
	<td align="left" width="50%" class="myTitle"><?=$heading;?></td>
	<td align="right">
	 <form name="pgimg_form" action="<?=$PHP_SELF?>" method="post" style="margin:0px;padding:0px;">
	 <table width="98%" border="0" align="center" cellpadding="0" cellspacing="0" valign="top">
	  <tr>
	   <td align="right">Records Per Page:
	    <select name="pagesize" onchange="this.form.submit();">
	     <option value="0">--Select--</option>
	     <?php
	     foreach($_GLOBALS['pgsize_arr'] as $val) {
		     if(trim($pagesize)==trim($val)) {
			     echo '<option value="'.$val.'" selected>'.$val.'</option>';
		     }
		     else{
			     echo '<option value="'.$val.'">'.$val.'</option>';
		     }
	     }
	     ?>
	    </select>	    
		 </td>
		</tr>
	 </table>
	 </form>
	</td>
 </tr>
</table>
</div>
<hr size="2" width="99%" color="#DA251C">

<?php
$qry1= mysqli_query($dbconn,"select * from $table_name");
$reccnt = mysqli_num_rows($qry1);
$qry= mysqli_query($dbconn,"select * from $table_name order by product_id desc");
// echo pageNavigation($reccnt,$pagesize,$start);
print_message();
?>
<form name="formn" method="post" action="" enctype="multipart/form-data">
<div class="table-responsive">
<table class="lightBorder table table-bordered table-hover">
       <?php
 if($reccnt>0) {
     ?>
    <thead>
	 <tr height="25" bgcolor="#EAEAEA">
    <td width="3%"></td>
	 <td width="5%" align="center"><strong style="
    color: #3331ca;">S.No.</strong></td>
	 <td width="10%" align="left"><strong style="
    color: #3331ca;">Product Title</strong></td>
	 <td width="8%" align="left"><strong style="
    color: #3331ca;">Product Code</strong></td>
	 <td width="19%" align="center"><strong style="
    color: #3331ca;">Product Image</strong></td>
         <td width="5%" align="center"><strong style="
    color: #3331ca;">Product Feature</strong></td>
	 <td width="8%" align="left"><strong style="
    color: #3331ca;">Category</strong></td>
	 <td width="10%" align="left"><strong style="
    color: #3331ca;">Options</strong></td>
	 </tr>
  </thead>
  <tbody>
       <?php
	 $sl=$start+1;
      while($arr=mysqli_fetch_array($qry)) { 
      ?>
    <tr>
        <td><label class="container1"><input type="checkbox" name="pro_arr[]" value="<?= $arr['product_id'] ?>" />  <span class="checkmark"></span></label></td>
        <td><?=$sl;?></td>
        <td><?=$arr['product_title'];?></td>
        <td><?=$arr['product_code'];?></td>
        <td>	
            <?php
	   if($arr['product_image']) {
		   $file1=SITE_DIR_PATH."/uploaded_files/product-images/".$arr['product_image'];
			   $dimens=getImageSize($file1);
			   if($dimens[0]>130) {
				   $dimens[0]=$dimens[0]+30;
				   $dimens[1]=$dimens[1]+80;
			   }
			   else{
				   $dimens[0]=200;
				   $dimens[1]=200;
			   }
			   ?>
            <a href="javascript:void(0);" onClick="openwin('<?=SITE_ADMIN_URL;?>/popup.php?img=product-images/<?=$arr['product_image'];?>', '<?=$dimens[0];?>', '<?=$dimens[1];?>')" class="linkgray fontbold"><strong>View Image</strong></a>
			   <?php
	   }

	   ?>
        </td>
        <td><?if($arr['product_theme']==0){ echo "No";}else{ echo "Yes";}?></td>
        <td>
           <?php
		 $cct=$arr['product_cat'];
		 $sql_cat=mysqli_query($dbconn,"select * from category_tbl where catID='$cct'");
         $res_cat=mysqli_fetch_array($sql_cat);
		 echo $res_cat['catName'];
         ?>
        </td>
        <td>&nbsp;<a href="<?=$script_name;?>?id=edit_record&start=<?=$start;?>&pagesize=<?=$pagesize?>&recordID=<?=$arr['product_id'];?>#bot"><i class="fa fa-edit"></i></a>&nbsp;<a href="<?=$script_name;?>?id=delete_record&start=<?=$start;?>&pagesize=<?=$pagesize?>&recordID=<?=$arr['product_id'];?>" onClick="return confirm('Are you sure to delete this record...');"><i class="fa fa-trash"></i></a>
        </td>
    </tr> 
      <?php $sl++; }  ?>
</tbody>
     <?php } else { ?> <tr><td><h5>Not Record Found ... </h5></td></tr><?php } ?>
</table>
</div>
<div class="text-right">
    <input type="submit" name="feature_pro" value="feature Product" class="btn btn-primary">
</div>
</form>
<br>

<link rel='stylesheet' href='calendar.css' title='calendar'>
<script language="javascript" src="calendar.js"></script>
<script src="jquery.min.js"></script>
<script type="text/javascript">

                    $("#quickCity").change(function(){	

                            var cityid  =  $('#quickCity').val();

                           $.ajax({   

                                url: "ajax99.php", //The url where the server req would we made.

                                async: false,

                                type: "POST", //The type which you want to use: GET/POST

                                data: "cityid="+cityid, //The variables which are going.

                                dataType: "html", //Return data type (what we expect).

                                //This is the function which will be called if ajax call is successful.

                                success: function(data) {

                                    //data is the html of the page where the request is made.

                                    $('#locatity').html(data);

                                }

                            })

                });
				
				 

        </script>
		<script type="text/javascript">

		
		$("#locatity").change(function(){	

                            var locatityid  =  $('#locatity').val();

                           $.ajax({   

                                url: "ajax999.php", //The url where the server req would we made.

                                async: false,

                                type: "POST", //The type which you want to use: GET/POST

                                data: "locatityid="+locatityid, //The variables which are going.

                                dataType: "html", //Return data type (what we expect).

                                //This is the function which will be called if ajax call is successful.

                                success: function(data) {

                                    //data is the html of the page where the request is made.

                                    $('#asd').html(data);

                                }

                            })

                });

</script>
<script type="text/javascript">

		
		$("#asd").change(function(){	

                            var asdid  =  $('#asd').val();

                           $.ajax({   

                                url: "ajax9999.php", //The url where the server req would we made.

                                async: false,

                                type: "POST", //The type which you want to use: GET/POST

                                data: "asdid="+asdid, //The variables which are going.

                                dataType: "html", //Return data type (what we expect).

                                //This is the function which will be called if ajax call is successful.

                                success: function(data) {

                                    //data is the html of the page where the request is made.

                                    $('#asd1').html(data);

                                }

                            })

                });

</script>
<iframe width=174 height=189 name="gToday:normal:agenda.js" id="gToday:normal:agenda.js" src="<?=SITE_URL_PATH;?>/js/calendar/themes/Normal/ipopeng.htm" scrolling="no" frameborder="0" style="visibility:visible; z-index:999; position:absolute; top:-500px; left:-500px;">
</iframe>
<?php
admin_footer();
exit;
?>