<?php

	$cmd = '';
	$p_barcode_last = '';
	//echo "Manage Patrons(new/edit/del)";
	$p_barcode =  $_POST['h_txt_barcode'];
	$s_name = $_POST['txt_s_name'];
	$f_name = $_POST['txt_f_name'];
	$l_name = $_POST['txt_l_name'];
	
	

	$conn = new mysqli('localhost', 'root', 'tester123','book_store');
	if ($conn->connect_error) {
		die("Connection failed: " . $conn->connect_error);
	}else{
		//echo "ok";
	}
	
	
	if($p_barcode == ""){		
		$sql = "select p_barcode from patrons";			
		$result = $conn->query($sql);		
		if ($result->num_rows > 0) {
			while($row = $result->fetch_assoc()) {
				$p_barcode_last = $row['p_barcode'];
			}		
		}
		//echo $p_barcode_last."<br/>";
			
		$p_barcode_last = substr($p_barcode_last,1);
		$p_barcode_last = (int)$p_barcode_last;	
		$p_barcode_new = $p_barcode_last+ 1;
		
		$p_barcode_new = "B".str_pad($p_barcode_new, 7, "0", STR_PAD_LEFT);
		//echo $p_barcode_new;
		$sql_manage = 	"INSERT INTO patrons (p_barcode, s_name, f_name,l_name)
				VALUES ('".$p_barcode_new."', '".$s_name."', '".$f_name."','".$l_name."')";	
	
		
		if ($conn->query($sql_manage) === TRUE) {
			echo "New record created successfully";
		} else {
			echo "Error: " . $sql_manage . "<br>" . $conn->error;
		}
	}else{
		
		$sql_update = 	"update patrons set
			
			s_name= '".$s_name."',
			f_name='".$f_name."',
			l_name='".$l_name."'
			where p_barcode='".$p_barcode."'
		
		";	
	
		
		if ($conn->query($sql_update) === TRUE) {
			echo "Update successfully";
		} else {
			echo "Error: " . $sql_update . "<br>" . $conn->error;
		}
	}
	
	 header( "location: http://127.0.0.1/booking/patrons.php" );
	exit(0);
	$conn->close();
?>