<?php
	$username = $_POST['username'];
	
	if ($username == "<b>PLEASE LOGIN</b>") {
		echo "PLEASE LOGIN!";
	}
	else {
		$userPW = $_POST['userPW'];
		$userpurchase = 1;
		$price = 400000;
		$userhome = $_POST['userHome'];
		$userRequest = $_POST['userRequest'];
		
		$filename = "stock.txt";
		$file = fopen($filename,"r");
			$readed = fread($file,filesize($filename));
			fclose($file);
		$rearray = explode("\r\n",$readed);
		
		$filename1 = "../../userDB/" . $username . ".txt";
			$file1 = fopen($filename1,"r");
			$readed1 = fread($file1,filesize($filename1));
			fclose($file1);
			$rearray1 = explode("\r\n",$readed1);
			
		$money = $rearray1[1];

		$stock = $rearray[0];
		
		$pwver = password_verify($userPW,$rearray1[0]);
		
		if ((int)$stock > 0) {
			if ($pwver) {
				if ((int)$money >= (int)$price) {
					//subtract stock
					$nstock = (int)$stock-(int)$userpurchase;
				
					$filename = "stock.txt";
					$opn = fopen($filename,"w");
					$write = $nstock;
					fputs($opn,$write);
					fclose($opn);
					
					//subtract money		
					$newmoney = (int)$money-(int)$price;
					$content = $rearray1[0] . "\r\n" . $newmoney . "\r\n" . $_SERVER['REMOTE_ADDR'];
					
					$filename1 = "../../userDB/" . $username . ".txt";
					$opn1 = fopen($filename1,"w");
					$write1 = $content;
					fputs($opn1,$write1);
					fclose($opn1);
					
					//write log
					$logorder = $username . " -- is purchasing! for amount of: " . $userpurchase . ", their adress is: " . $userhome . ", Their request: " . $userRequest . "\r\n";
				
					$filename2 = "orderlog.txt";
					$opn2 = fopen($filename2,"a");
					$write2 = $logorder;
					fputs($opn2,$write2);
					fclose($opn2);
					
					echo "Purchase Complete!";
				}
				else {
					echo "Please refill your money before purchasing!";
				}
			}
			else {
				echo "Password incorrect!";
			}
		}
		else {
			echo "Purchase Failed, No Stock!";
		}
	}
?>