<!DOCTYPE html>
<html lang="en">
<head>
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
	<meta charset="utf-8" />
	<title>Sudila Printers</title>
	<meta name="description" content="overview &amp; stats" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
	<!-- bootstrap & fontawesome -->
	<link rel="stylesheet" href="assets/css/bootstrap.min.css" />
	<link rel="stylesheet" href="assets/font-awesome/4.5.0/css/font-awesome.min.css" />
	<!-- page specific plugin styles -->
	<!-- text fonts -->
	<link rel="stylesheet" href="assets/css/fonts.googleapis.com.css" />
	<!-- ace styles -->
	<link rel="stylesheet" href="assets/css/chosen.min.css" />
	<link rel="stylesheet" href="assets/css/ace.min.css" class="ace-main-stylesheet" id="main-ace-style" />
<!--[if lte IE 9]>
    <link rel="stylesheet" href="assets/css/ace-part2.min.css" class="ace-main-stylesheet" />
<![endif]-->
<link rel="stylesheet" href="assets/css/ace-skins.min.css" />
<link rel="stylesheet" href="assets/css/ace-rtl.min.css" />
<!--[if lte IE 9]>
  <link rel="stylesheet" href="assets/css/ace-ie.min.css" />
<![endif]-->
<!-- inline styles related to this page -->
<!-- ace settings handler -->
<script src="assets/js/ace-extra.min.js"></script>
<!-- HTML5shiv and Respond.js for IE8 to support HTML5 elements and media queries -->
<!--[if lte IE 8]>
    <script src="assets/js/html5shiv.min.js"></script>
    <script src="assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body class="no-skin">
	<?php include 'common/navbar.php'; ?>
	<div class="main-container ace-save-state" id="main-container">
		<?php include 'common/sidebar.php'; ?>
		<div class="main-content">
			<div class="main-content-inner">
				<div class="breadcrumbs ace-save-state" id="breadcrumbs">
					<ul class="breadcrumb">
						<li> <i class="ace-icon fa fa-home home-icon"></i> <a href="home">Home</a> </li>
						<li> <a href="add-new-book">Add New Book</a> </li>
						<li class="active">Book List</li>
					</ul>
					<!-- /.breadcrumb --> 
				</div>
				<div class="page-content">
					<div class="page-header">
						<h1> Search Book </h1>
					</div>
					<?php if(isset($_GET['cat_id']) && !empty($_GET['cat_id'])) {
						$cat_id = htmlspecialchars(strip_tags(trim($_GET['cat_id'])), ENT_QUOTES, 'UTF-8');
						if($cat_id == 'all') {
							$txt = "";

						} else {
							$txt = " WHERE id IN (SELECT Book_ID FROM category_map WHERE Cat_ID='".$cat_id."')";
						}
					} else { $cat_id = ''; $txt = ''; } ?>
					<!-- /.page-header -->
					<div class="row">
						<div class="col-xs-12">
							<div class="widget-box">
								<div class="widget-body">
									<div class="widget-main"> <br>
										<!-- Content -->
										<form method="get">
											<div class="form-group">
												<label>Select Category:<sup class="red">*</sup></label>
												<select class="chosen-select form-control" data-placeholder="Select a Category.." name="cat_id">
													<option></option>
													<option value="all">All Books</option>
													<?php
													$sql = "SELECT * FROM category";
													$result = mysqli_query($conn, $sql);
													while ($row = mysqli_fetch_array($result)) { ?>
														<option value="<?php echo $row['id'] ?>" <?php if($row['id'] == $cat_id) { echo 'selected'; } ?>><?php echo $row['category'] ?></option> 
													<?php } ?>
												</select>
											</div>
											<br>
											<div class="form-group">
												<button class="btn btn-danger btn-sm"> SEARCH</button>
											</div>

										</form>
									</div>
								</div>
							</div>
							<?php if(!empty($cat_id)) { ?>
								<br>
								<div class="widget-box">
									<div class="widget-body">
										<div class="widget-main">
											<div class="table-header"> Edit/Remove Book </div>
											<!-- div.table-responsive --> 
											<!-- div.dataTables_borderWrap -->
											<div class="table-responsive">
												<table id="dynamic-table" class="table table-striped table-bordered table-hover">
													<thead>
														<tr>
															<th>ID</th>
															<th>Name</th>
															<th>Price</th>
															<th>ISBN</th>
															<th>Discount (%)</th>
															<th>Image</th>
															<th>Edit Category</th>
															<th>Edit Author</th>
															<th>Edit/Remove</th>
														</tr>
													</thead>
													<tbody>
														<?php
														$sql = mysqli_query($conn, "SELECT * FROM bookdetails $txt ORDER by name");
														$x = 0;
														while ($row = mysqli_fetch_array($sql)) { $x++;
															?>
															<tr>
																<td><?php echo $x; ?>.</td>
																<td><?php echo $row['name']; ?></td>
																<td><?php echo $row['price']; ?></td>
																<td><?php echo $row['isbn']; ?></td>
																<td><?php echo $row['discount']; ?></td>
																<td><?php if(!empty($row['front_image'])) { ?><img src="../image/books/thumb/<?php echo $row['front_image']; ?>" width="50px"><?php } ?></td>
																<td align="center"><a target="blank" href="edit-book-category?bid=<?php echo $row['id']; ?>"  class="btn btn-success btn-sm"><i class="ace-icon fa fa-pencil"></i></a></td>
																<td align="center"><a target="blank" href="edit-book-author?bid=<?php echo $row['id']; ?>"  class="btn btn-warning btn-sm"><i class="ace-icon fa fa-pencil"></i></a></td>
																<td align="center"><div class="action-buttons">
																	<button title="Edit" class="btn btn-primary btn-sm btn_edit" data-toggle="modal" data-target="#edit_data" value="<?php echo $row['id']; ?>"> <i class="ace-icon fa fa-pencil"></i> </button>
																	<button title="Remove" class="btn btn-danger btn-sm btn_remove" value="<?php echo $row['id']; ?>"> <i class="ace-icon fa fa-trash-o"> </i> </button> </div>
																</td>
															</tr>
														<?php } ?>
													</tbody>
												</table>
											</div>
										</div>
									</div>
								</div>
							<?php } ?>
							<!-- PAGE CONTENT ENDS --> 
						</div>
						<!-- /.col --> 
					</div>
					<!-- /.row --> 
				</div>
				<!-- /.page-content --> 
			</div>
		</div>
		<!-- /.main-content -->
		<?php include 'common/footer.php'; ?>
	</div>
	<!-- /.main-container -->

	<!-- Model -->
	<div id="edit_data" class="modal fade" tabindex="-1">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
					<h4 class="smaller lighter blue no-margin">Edit Book</h4>
				</div>
				<div class="widget-body">
					<div class="widget-main" style="margin: 15px;border: 1px solid #CCC;">
						<!-- Content -->
						<form id="form_update" method="post">
							<div class="form-group">
								<label>Name (English and Sinhala):<sup class="red">*</sup></label>
								<input type="text" class="form-control" name="name" id="name" required autocomplete="off"/>
								<span class="help-block"></span>
							</div>
							<div class="form-group">
								<label>Name (English Only):<sup class="red">*</sup></label>
								<input type="text" class="form-control" name="eng_name" id="eng_name" required autocomplete="off"/>
								<span class="help-block"></span>
							</div>
							<div class="row">
								<div class="form-group col-md-4">
									<label>Price:<sup class="red">*</sup></label>
									<input type="text" class="form-control" name="price" id="price" required autocomplete="off"/>
									<span class="help-block"></span>
								</div>
								<div class="form-group col-md-4">
									<label>ISBN:<sup class="red">*</sup></label>
									<input type="text" class="form-control" name="isbn" id="isbn" required autocomplete="off"/>
									<span class="help-block"></span>
								</div>
								<div class="form-group col-md-4">
									<label>Item Code:<sup class="red">*</sup></label>
									<input type="text" class="form-control" name="item_code" id="item_code" required autocomplete="off"/>
									<span class="help-block"></span>
								</div>
							</div>
							<div class="form-group">
								<label>Publisher:<sup class="red">*</sup></label>
								<input type="text" class="form-control" name="publisher" id="publisher" required autocomplete="off"/>
								<span class="help-block"></span>
							</div>
							<div class="row">
								<div class="form-group col-md-6">
									<label>Book Discount (%):<sup class="red">*</sup></label>
									<input type="text" class="form-control" name="discount" id="discount" required autocomplete="off">
									<span class="help-block"></span>
								</div>
								<div class="form-group col-md-6">
									<label>Width (mm):</label>
									<input type="text" class="form-control" name="width" id="width" autocomplete="off"/>
									<span class="help-block"></span>
								</div>
							</div>
							<div class="row">
								<div class="form-group col-md-6">
									<label>Height (mm):</label>
									<input type="text" class="form-control" name="height" id="height" autocomplete="off"/>
									<span class="help-block"></span>
								</div>
								<div class="form-group col-md-6">
									<label>Weight (g):<sup class="red">*</sup></label>
									<input type="text" class="form-control" name="weight" required id="weight" autocomplete="off"/>
									<span class="help-block"></span>
								</div>
							</div>
							<div class="form-group">
								<label>Description:</label>
								<textarea type="text" class="form-control" rows=5 name="descrip" id="descrip"></textarea>
								<span class="help-block"></span>
							</div>
							<div class="form-group">
								<label>Keywords:</label>
								<input type="text" class="form-control" name="keywords" id="keywords" autocomplete="off"/>
								<span class="help-block"></span>
							</div>
							<div class="form-group">
								<label>Front Cover Image:</label>
								<input class="form-control" type="file" id="id-input-file-2" accept="image/*" name="file_name1"/>
								<small class="text-danger">Max-Width: 350px</small>
								<span class="help-block"></span>
							</div>
							<span id="img_div"></span>
							<div class="form-group">
								<label>Back Cover Image:</label>
								<input class="form-control" type="file" id="id-input-file-2" accept="image/*" name="file_name2"/>
								<small class="text-danger">Max-Width: 350px</small>
								<span class="help-block"></span>
							</div>
							<span id="img_div2"></span>
							<div class="row">
								<div class="form-group col-md-4">
									<label>
										<input type="checkbox" class="ace" value="1" name="new_pro" id="new_pro" />
										<span class="lbl"> &nbsp;&nbsp;New Product</span>
									</label>
								</div>
								<div class="form-group col-md-4">
									<label>
										<input type="checkbox" class="ace" value="1" name="stock_out" id="stock_out" />
										<span class="lbl"> &nbsp;&nbsp;Out of Stock</span>
									</label>
								</div>
								<div class="form-group col-md-4">
									<label>
										<input type="checkbox" class="ace" value="1" name="feature_pro" id="featured_pro" />
										<span class="lbl"> &nbsp;&nbsp;Featured Product</span>
									</label>
								</div>
								<div class="form-group col-md-4">
									<label>
										<input type="checkbox" class="ace" value="1" name="best_sell" id="best_sell" />
										<span class="lbl"> &nbsp;&nbsp;Best Seller</span>
									</label>
								</div>
					  <!--<div class="form-group col-md-4">
						<label>
							<input type="checkbox" class="ace" value="1" name="kids_book" id="kids_book" />
							<span class="lbl"> &nbsp;&nbsp;Kids Book</span>
						</label>
					</div>-->
				</div>
				<br>
				<input type="hidden" class="form-control" name="id_up" id="id_up" readonly autocomplete="off"/>
				<div class="form-group">
					<button class="btn btn-danger btn-sm"> UPDATE</button>
				</div>
			</form>
			<!-- End Content --> 
		</div>
	</div>
	<!-- /End .widget-box --> 
	<div class="modal-footer">
		<button class="btn btn-xs btn-default pull-right" data-dismiss="modal"> <i class="ace-icon fa fa-times"></i> Close </button>
	</div>
</div>
<!-- /.modal-content --> 
</div>
<!-- /.modal-dialog --> 
</div>
<!-- // Model -->

<!-- basic scripts --> 
<!--[if !IE]> -->
<script src="assets/js/jquery-2.1.4.min.js"></script>
<!-- <![endif]--> 
<!--[if IE]>
<script src="assets/js/jquery-1.11.3.min.js"></script>
<![endif]--> 
<script type="text/javascript">
	if('ontouchstart' in document.documentElement) document.write("<script src='assets/js/jquery.mobile.custom.min.js'>"+"<"+"/script>");
</script> 
<script src="assets/js/bootstrap.min.js"></script> 
<!-- page specific plugin scripts --> 
<!--[if lte IE 8]>
  <script src="assets/js/excanvas.min.js"></script>
<![endif]-->
<script src="assets/js/jquery.dataTables.min.js"></script>
<script src="assets/js/jquery.dataTables.bootstrap.min.js"></script>
<!-- ace scripts -->
<script src="assets/js/ace-elements.min.js"></script>
<script src="assets/js/chosen.jquery.min.js"></script>
<script src="assets/js/ace.min.js"></script>
<script src="assets/jquery.validate.min.js"></script>
<link rel="stylesheet" href="bootstrap-sweetalert/lib/sweet-alert.css" />
<script src="bootstrap-sweetalert/lib/sweet-alert.min.js"></script>
<script src="assets/js/jquery-typeahead.js"></script>
<script src="assets/js/bootstrap-tag.min.js"></script>
<!-- inline scripts related to this page --> 
<script type="text/javascript">
	jQuery(function ($) {
	//initiate dataTables plugin
	var myTable =
	$('#dynamic-table')
	//.wrap("<div class='dataTables_borderWrap' />")   //if you are applying horizontal scrolling (sScrollX)
	.DataTable({
		bAutoWidth: false,
		"aaSorting": [],
	});
	
	if(!ace.vars['touch']) {
		$('.chosen-select').chosen({allow_single_deselect:true}); 
		//resize the chosen on window resize

		$(window)
		.off('resize.chosen')
		.on('resize.chosen', function() {
			$('.chosen-select').each(function() {
				var $this = $(this);
				$this.next().css({'width': $this.parent().width()});
			})
		}).trigger('resize.chosen');
		//resize chosen on sidebar collapse/expand
		$(document).on('settings.ace.chosen', function(e, event_name, event_val) {
			if(event_name != 'sidebar_collapsed') return;
			$('.chosen-select').each(function() {
				var $this = $(this);
				$this.next().css({'width': $this.parent().width()});
			})
		});
	}
	
	///////////////////
	
	var PUB_LIST=[];
	
	<?php $sql_pub = mysqli_query($conn, "SELECT * FROM publisher ORDER BY name");
	while($row_pub = mysqli_fetch_array($sql_pub)) {
		?>
		PUB_LIST.push('<?php echo $row_pub['name']; ?>');
	<?php } ?>

	//typeahead.js
	//example taken from plugin's page at: https://twitter.github.io/typeahead.js/examples/
	var substringMatcher = function(strs) {
		return function findMatches(q, cb) {
			var matches, substringRegex;

			// an array that will be populated with substring matches
			matches = [];

			// regex used to determine if a string contains the substring `q`
			substrRegex = new RegExp(q, 'i');

			// iterate through the pool of strings and for any string that
			// contains the substring `q`, add it to the `matches` array
			$.each(strs, function(i, str) {
				if (substrRegex.test(str)) {
					// the typeahead jQuery plugin expects suggestions to a
					// JavaScript object, refer to typeahead docs for more info
					matches.push({ value: str });
				}
			});

			cb(matches);
		}
	}

	$('#publisher').typeahead({
		hint: true,
		highlight: true,
		minLength: 1
	}, {
		name: 'states',
		displayKey: 'value',
		source: substringMatcher(PUB_LIST),
		limit: 10
	});

	//////////////
	
});

	/******************* Edit **********************/

	$(".btn_edit").click(function() {
		var id = $(this).val();
		$("#id_up").val(id);
		$( ".tag" ).remove();

		$.post( "connection/book_conn", { get_dataset: "data", id : id}, function( data ) {
			$("#publisher").val('');

			$("#name").val(data[0].name);
			$("#eng_name").val(data[0].eng_name);
			$("#price").val(data[0].price);
			$("#isbn").val(data[0].isbn);
			$("#item_code").val(data[0].item_code);
			$("#descrip").val(data[0].description);
			$("#keywords").val(data[0].tags);

			if(data[0].width === '0') {
				$("#width").val('');
			} else {
				$("#width").val(data[0].width);
			}

			if(data[0].height === '0') {
				$("#height").val('');
			} else {
				$("#height").val(data[0].height);
			}

			if(data[0].weight === '0') {
				$("#weight").val('');
			} else {
				$("#weight").val(data[0].weight);
			}

			$("#discount").val(data[0].discount);

			if(data[0].front_image === '') {
				$("#img_div").html('');
			} else {
				$("#img_div").html('<img src="../image/books/thumb/'+data[0].front_image+'" width="100" class="img-responsive"><br>');
			}

			if(data[0].back_image === '') {
				$("#img_div2").html('');
			} else {
				$("#img_div2").html('<img src="../image/books/thumb/'+data[0].back_image+'" width="100" class="img-responsive"><br>');
			}

			if(data[0].new_arrivals == 1) {
				$("#new_pro").prop("checked", true);
			} else {
				$("#new_pro").prop("checked", false);
			}

			if(data[0].stock_out == 1) {
				$("#stock_out").prop("checked", true);
			} else {
				$("#stock_out").prop("checked", false);
			}

			if(data[0].featured_pro == 1) {
				$("#featured_pro").prop("checked", true);
			} else {
				$("#featured_pro").prop("checked", false);
			}

			if(data[0].best_seller == 1) {
				$("#best_sell").prop("checked", true);
			} else {
				$("#best_sell").prop("checked", false);
			}

	/*if(data[0].kids_book == 1) {
		$("#kids_book").prop("checked", true);
	} else {
		$("#kids_book").prop("checked", false);
	}*/

	$("#publisher").val(data[1].publishern);
	
}, "json");

	});

	$("#form_update").validate({
		ignore: [],
		rules: {
			price: {
				number: true,
				min: 1,
			},
			width: {
				number: true,
				min: 1,
			},
			height: {
				number: true,
				min: 1,
			},
			weight: {
				number: true,
				min: 1,
			},
			discount: {
				number: true,
				min: 0,
			},
		},
		messages:
		{
			price: {
				number: "Invalid Price Value",
				min: "Invalid Price Value",
			},
			width: {
				number: "Invalid Value",
				min: "Invalid Value",
			},
			height: {
				number: "Invalid Value",
				min: "Invalid Value",
			},
			weight: {
				number: "Invalid Value",
				min: "Invalid Value",
			},
			discount: {
				number: "Invalid Value",
				min: "Invalid Value",
			},
		},
		errorPlacement : function(error, element) {
			$(element).closest('.form-group').find('.help-block').html(error.html());
		},
		highlight : function(element) {
			$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
		},
		unhighlight: function(element, errorClass, validClass) {
			$(element).closest('.form-group').removeClass('has-error');
			$(element).closest('.form-group').find('.help-block').html('');
		},
		submitHandler: editForm
	});
	function editForm(){
		//disable the default form submission
		event.preventDefault();
		//grab all form data  
		var formData = new FormData($('#form_update')[0]);
		
		$.ajax({
			url: 'connection/book_conn',
			type: 'POST',
			data: formData,
			async: false,
			cache: false,
			contentType: false,
			processData: false,
		})
		.done(function(data){
			if ( data === 'success' ) {
				swal({
					title: "",
					text: "Successfully Updated!",
					type: "success",
					confirmButtonText: "OK"
				},
				function (isConfirm) {
					if (isConfirm) {
						window.location.href = "view-book-list?cat_id=<?php echo $cat_id;?>";
					}
				});

			} else if(data ==='error2') {
				swal("", "Error While uploading file on the server. Please Try Again!", "warning");

			} else if(data ==='error3') {
				swal("", "Invaild File Type! Please Try Again!", "warning");

			} else if(data ==='exist') {
				swal("", "File Name Already Exists! Please Try Again!", "warning");

			} else if ( data === 'data exist' ) {
				swal("", "ISBN Already Exist. Please Try Again!", "warning");

			} else if ( data === 'data exist1' ) {
				swal("", "Book Name Already Exist. Please Try Again!", "warning");

			} else {
				swal("", "Something went wrong! Please Try Again!", "warning");
			}
		})
		.fail(function(){
			swal("", "Something went wrong! Please Try Again!", "warning");
		});
	}

	/******************* Remove **********************/

	$(".btn_remove").click(function(){
		var row_id = $(this).val();
		swal({
			title: "",
			text: "Are you sure you want to delete this?",
			type: "warning",
			showCancelButton: true,
			confirmButtonClass: "btn-danger",
			confirmButtonText: "Yes, delete it!",
			cancelButtonText: "No, cancel!",
			closeOnConfirm: false,
			closeOnCancel: true
		},
		function(isConfirm) {
			if (isConfirm) {
				$.post( "connection/book_conn", {remove_data: "data", id : row_id}, function( data ) {
					if (data.msgType === 1) {
						swal({
							title: "",
							text: "Successfully Deleted!",
							type: "success",
							confirmButtonText: "OK"
						},
						function (isConfirm) {
							if (isConfirm) {
								window.location.href = "view-book-list?cat_id=<?php echo $cat_id;?>";
							}
						});

					} else if (data.msgType === 3) {
						swal("", "Data Already Exist!", "warning");

					} else{
						swal("", "Something went wrong! Please Try Again!", "warning");
					}
				}, "json");
			}
		});
	});
</script>
</body>
</html>