<?php
session_start();
require_once 'db_connection.php'; 
$agency = $_POST['agency'];
$product = $_POST['product'];
$qty = $_POST['qty'];
$price = $_POST['price'];

$proname = $_POST['proname'];
$prcode = $_POST['prcode'];
$brandname = $_POST['brandname'];
$category = $_POST['category'];
$discount = $_POST['discount'];
$sellprice = $_POST['sellprice'];
$price = $_POST['price'];


$user_id = $_SESSION['emid'];
$today = date('Y-m-d H:i:s');

$sql = "INSERT INTO mobileagency_stock (agency_id, product_id, agency_price,agency_quantity, transfer_by, transfer_at)
VALUES ('$agency', '$product', '$price','$qty', '$user_id', '$today')";

if ($conn->query($sql) === TRUE) {
	$last_id = $conn->insert_id;
	echo $last_id;
	if($last_id>0){
		$sql2 = "UPDATE mobileproducts SET qty=qty-'$qty' WHERE prid='$product'";
		if ($conn->query($sql2) === TRUE) { }

		//check product have in agency product table
			$sql3 = "SELECT * FROM mobileproducts_agency WHERE agency_id='$agency' AND prid='$product' ";
		$result3 = $conn->query($sql3);
		if ($result3->num_rows > 0) {
			//update table
			$sql4 = "UPDATE mobileproducts_agency SET qty=qty+'$qty', sellprice='$price' WHERE prid='$product' AND agency_id='$agency'";
			if ($conn->query($sql4) === TRUE) { }
		}else{

			//insert record
			$sql5 = "INSERT INTO mobileproducts_agency(agency_id, prid, prcode, proname, brandname, category, qty, discount, wsprice, sellprice) VALUES	('$agency', '$product', '$prcode','$proname', '$brandname', '$category','$qty', '$discount' ,'$price', '$sellprice')";
			if ($conn->query($sql5) === TRUE) { }else{
				echo "Error: " . $sql5 . "<br>" . $conn->error;
			}

		}


	
}

} else {
	echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>