
<?php
session_start();
require_once __DIR__."/allfunctions.php";

if(empty($_SESSION["MEMBER_ID"]) && empty($_SESSION["TYPE"]) && empty($_SESSION["FIRST_NAME"]))
{
	 $itemarray = array();
	 $memberid = "";
	$type = "";
	$fname = "";
}
else
{
	$memberid = $_SESSION['MEMBER_ID'];
	$type = $_SESSION['TYPE'];
	$fname = $_SESSION['FIRST_NAME'];
}

	$con = mysqli_connect(get_dbserver(),get_dbuser(),get_dbpassword(),get_dbname());
	$echo="";

	$checklistdata = $_GET['checklistdata'];
	$commission = $_GET['commission'];
	$agent = $_GET['agent'];
	$saledate = $_GET['saledate'];
	//echo $historyname;
	//$checklistdata = explode(",",$historyname);
	//echo $checklistdata;
	//echo $commission;
	$array = explode(',', $checklistdata);
	$arraycommision = explode(',', $commission);
	$arrayagent = explode(',', $agent);
	$arraysaledate = explode(',', $saledate);
	$ctr = count($array);
	$dateToday = date('Y-m-d');
	//var_dump($arraycommision);
	for ($c=0;$c<$ctr;$c++)
	{
	//echo $checklistdata[$c];
	//echo $c;

	$strSQL = "UPDATE sales SET paymentstatus='Paid',paymentdate='".$dateToday."',approvedpaymentby='".$memberid."' WHERE id=".$array[$c];
	//echo $strSQL;
		if(mysqli_query($con, $strSQL) or die("database error: ". mysqli_error($con)))
		{
				$now =date("Y-m-d H:i:s");
				$status = "Paid";
				$paymentref= generateCode();
				//echo $arraycommision[$c];
				//$cleancommision = str_replace( ',', '', $arraycommision[$c] );
				//$cleanagent = str_replace( ',', '', $arrayagent[$c] );
				//$cleansalesdate = str_replace( ',', '', $arraysaledate[$c] );
				$soldby = getRecord('soldby','sales','id ='.$array[$c].'');
				$checkif = checkifpaymentexist($array[$c]);
				if(!$checkif)
				{
					$insert_sql3 = "INSERT INTO payments(id,paymentref,salesID,amountpaid,paymento,paymentstatus,paymentdate,approvedpaymentby,salesdate)
					VALUES(NULL,'".$paymentref."','".$array[$c]."','".$arraycommision[$c]."', '".$soldby."','".$status."','".$now."','".$memberid."', '".$arraysaledate[$c]."')";
					$rs = mysqli_query($con,$insert_sql3) or die(mysqli_error($con));
					if($rs)
					{
						echo 1;
					}
					else
					{
						echo 0;
					}

				}
				else {
					echo "Exist";
				}


		}
		else
		{
			echo 0;
		}
	}
//	echo $historyname;
?>
