<?php
/*
* date last modified 28-11-2017
* Edited by PI-Digi Logical Solutions
* HTML Files - add_user.html.php
* Mysql Tables - tbl_designation, tbl_products
*/
include('includes/imgFunctions.php');
include('includes/functions.php'); # general functions

$isEdit = FALSE;

$categoryRs = mysqli_query($con, "SELECT * FROM tbl_product_categories WHERE parent_id = '0'");

if(isset($_REQUEST['id']) && $_REQUEST['id']!=''){	
	$isEdit = TRUE;
	$editId = mysqli_real_escape_string($con, trim($_REQUEST['id']));		
	$editRs = mysqli_query($con, "SELECT * FROM tbl_products WHERE id = '".$editId."'");
	if(mysqli_num_rows($editRs)>0){
		$resEdit = mysqli_fetch_array($editRs);
	} else {
		$error = 'Product does not exist!';
	}
} 

if(isset($_POST['add'])) {
		
	if(isset($_POST['description']) && strlen($_POST['description'])>0) {
		$description = trim($_POST['description']);
	} else {
		$description = '';
	}
	
	if(isset($_POST['name']) && strlen($_POST['name'])>0) {
		$name = trim($_POST['name']);
	} else {
		$error = 'Please enter product Name';
	}	
	
	if(isset($_POST['category']) && strlen($_POST['category'])>0) {
		$category = trim($_POST['category']);
	} else {
		$error = 'Please select category';
	}	
	
	if(empty($error)) {
						
		/* Adding New staff Details */		
		$insertQry = "INSERT INTO tbl_products(cat_id, name, description) VALUES (
		'".mysqli_real_escape_string($con, $category)."',
		 '".mysqli_real_escape_string($con, $name)."',
		 '".mysqli_real_escape_string($con, $description)."')";
		
		$execInsert = mysqli_query($con,$insertQry);
		$insert_id = mysqli_insert_id($con);				
		if($execInsert) {						
			$success = 'Product Added Successfully';
			header('Location:index.php?page=manage_product&success='.$success);
			exit();			
		}				
	} 
}

if(isset($_POST['update'])) {
	
	if(isset($_POST['description']) && strlen($_POST['description'])>0) {
		$description = trim($_POST['description']);
	} else {
		$description = '';
	}
	
	if(isset($_POST['name']) && strlen($_POST['name'])>0) {
		$name = trim($_POST['name']);
	} else {
		$error = 'Please enter product name';
	}	
	
	if(isset($_POST['category']) && strlen($_POST['category'])>0) {
		$category = trim($_POST['category']);
	} else {
		$error = 'Please select category';
	}			
		
	if(empty($error)) {					
			
		$updateQry = "UPDATE tbl_products SET name = '".$name."', cat_id = '".$category."', description = '".$description."' WHERE id = '".$editId."'";
		
		$execUpdate = mysqli_query($con,$updateQry);			
		
		if($execUpdate) {
			$success = 'Product Updated Successfully';
			header('Location:index.php?page=manage_product&success='.$success);
			exit();			
		}				
	} 
}

?>