<?php 
include_once 'api/config.php';
if(!isset($_SESSION['SESS_UID'])){echo "Not allowed";exit();} 
$uid=$_SESSION['SESS_UID'];
if(isset($_POST['editId']))
{
	$editId=$_POST['editId'];
	$cust_name=$_POST['cust_name'];
	$cust_email=$_POST['cust_email'];
	$allowed_downloads=$_POST['allowed_downloads'];
	$current_downloads=$_POST['current_downloads'];
	$cust_status=$_POST['cust_status'];
	$cust_details=$_POST['cust_details'];
	$cust_address=$_POST['cust_address'];
	if($allowed_downloads<$current_downloads)
	{
		echo "<div class='alert alert-warning'><strong>Attention </strong> Allowed download must be greater than current downloads.</div>";
		exit();
	}
	if($editId==0)
	{
		$sql="SELECT * FROM customers WHERE cust_email='$cust_email'";
		$result = $link->query($sql);
		if ($result->num_rows > 0)
		{
			echo "<div class='alert alert-warning'><strong>Errors</strong> Customer Email  already exists.</div>";
			exit();
		}
		$sql="INSERT INTO customers (cust_name,cust_email,allowed_downloads,current_downloads,cust_status,cust_details,cust_address) VALUES ('$cust_name','$cust_email','$allowed_downloads','$current_downloads','$cust_status','$cust_details','$cust_address')";
		if($link->query($sql)===TRUE)
		{
			echo "<div class='alert alert-success'> <strong>Success ! </strong> New Customer Record Added Successfully...Redirecting...!</div>".
				"<script>setTimeout(function(){ window.location.reload(); }, 3000);</script>";		
			exit();
		}
		else
		{
			echo "<div class='alert alert-danger'> <strong>Error ! </strong> Error in inserting record.</div>";
		}
		
	}
	else
	{
		$sql="SELECT * FROM customers WHERE cust_email='$cust_email'  AND cust_id!='$editId'";
		$result = $link->query($sql);
		if ($result->num_rows > 0)
		{
			echo "<div class='alert alert-warning'><strong>Errors</strong> Email already exists for some other customer.</div>";
			exit();
		}
		$sql="UPDATE customers SET cust_details='$cust_details',cust_address='$cust_address', cust_status='$cust_status',cust_email='$cust_email',cust_name='$cust_name',allowed_downloads='$allowed_downloads',current_downloads='$current_downloads' WHERE cust_id='$editId'";
		if($link->query($sql)===TRUE)
		{
			echo "<div class='alert alert-success'> <strong>Success ! </strong> Customer Record Updated Successfully...Redirecting...!</div>".
				"<script>setTimeout(function(){ window.location.reload(); }, 3000);</script>";		
			exit();
		}
		else
		{
			echo "<div class='alert alert-danger'> <strong>Error ! </strong> Error in updating record.</div>";
		}
	}
}




?>