<?php
$pgMod="inventory";
$pgAct="view";
if(isset($_GET['action']) && trim($_GET['action'])!='')
		$pgAct=strtolower($_GET['action']);

    $permission = $db->getVal("select id from tbl_privilages where roll_id='".$_SESSION["admin"]["roll"]."' and page_name='InventoryEditDelete' and a='1' ");

if($_POST)
{
	$_SESSION['form']=$_POST;
	$flgEr=FALSE;
	if(!isset($_POST['name']) || trim($_POST['name'])=='')
	{
		$flgEr=TRUE;
		array_push($alert_err,"Please enter Section Name.");
	}
	if($flgEr!=TRUE && $pgAct=="add")
	{
		
        $_POST["school_id"]=$_SESSION["admin"]["school_id"];
		$_POST["session"]=$_SESSION["admin"]["session"];
        $_POST["added_by"]=$_SESSION["admin"]["uid"];
		$flgIn=$db->insertAry("inventory",$_POST);
		if(!is_null($flgIn))
		{
			$_SESSION['msg']='Saved Successfully';
			unset($_SESSION['form']);
			redirect(URL_ADMIN_HOME.getQueryString(array("src"=>"cms", "page_id"=>$pgMod)));
		}
		else
		{
			array_push($alert_err,$db->getErMsg());
			
		}
	}
	elseif($pgAct=="edit" && isset($_GET['id']) && trim($_GET['id'])!='')
	{
		$flgUp=$db->updateAry("inventory",$_POST,"where school_id='".$_SESSION["admin"]["school_id"]."' and id='".$_GET['id']."'");
		if(!is_null($flgUp))
		{
			$_SESSION['msg']='update Successfully';
			unset($_SESSION['form']);
			redirect(URL_ADMIN_HOME.getQueryString(array("src"=>"cms", "page_id"=>$pgMod)));
		}
		else
		{
			array_push($alert_err,$db->getErMsg());
		
		}
	} 
}		
elseif($pgAct=="delete" && isset($_GET['id']) && trim($_GET['id'])!='')
{
	$res=$db->delete("inventory","where school_id='".$_SESSION["admin"]["school_id"]."' and id='".$_GET['id']."'");
	if(!is_null($res)) { $_SESSION['msg']='Deleted Successfully'; }
	else { array_push($alert_err,$db->getErMsg()); }
	redirect(URL_ADMIN_HOME.getQueryString(array("src"=>"cms", "page_id"=>$pgMod)));
} 
if(isset($_SESSION['msg']) && $_SESSION['msg']!="")
{
	?>
	<div class="alert alert-success">
	  <a class="close" data-dismiss="alert">×</a>
	  <i class="icon icon-thumbs-up-alt"></i> <b>Notice</b><?php echo $_SESSION['msg'] ?></i>
	</div>
	<?php
	unset($_SESSION["msg"]);
}
if(is_array($alert_err) && count($alert_err)>0)
{
	?>
	<div class="alert alert-error">
	  <a class="close" data-dismiss="alert">×</a>
	  <i class="icon icon-warning-sign"></i> <b>Notice</b> <?php echo $alert_err[0] ?></i>
	</div>
	<?php
}
if($pgAct=="edit" && $_GET["id"]!="")
{   
	$aryForm=$db->getRow("SELECT * FROM inventory WHERE school_id='".$_SESSION["admin"]["school_id"]."' and id='".$_GET['id']."'");
}
if($pgAct=="add" || ($pgAct=="edit" && isset($_GET['id']) && trim($_GET['id']) !=''))
{
?>

	<div class="row-fluid">
        <form method="post" action="">

			<div class="span12">

				<div class="top-bar">
					<h3><i class="icon-cog"></i> Create a New Section</h3>
				</div>

				<div class="well no-padding">

						<div class="control-group">
							<label class="control-label" for="name">Inventory Head </label>
							<div class="controls">
    							<select name="head" style="width:100%;" onchange="getInventory(this.value)">
                                   <option value="">--Select--</option>
                                    <?php $allSubjects = $db->getRows("select * from inventory_names where school_id='".$_SESSION["admin"]["school_id"]."' and head_type='Head' and status='1' ");
                                        foreach($allSubjects as $sub){
                                        ?>
                                        <option value="<?php echo $sub['name']; ?>" <?php if($sub['name'] == $aryForm['head'])echo "selected"; ?> ><?php echo $sub['name']; ?></option>
                                        <?php
                                        }
                                    ?>
                                </select>
                            </div>
						</div>

						<div class="control-group">
							<label class="control-label" for="name">Inventory name </label>
							<div class="controls" id="inventory_div">
    							<select name="name" style="width:100%;" >
                                   <option value="">--Select--</option>
                                   <?php $allSubjects = $db->getRows("select * from inventory_names where head_name='$aryForm[head]' and school_id='".$_SESSION["admin"]["school_id"]."' and status='1' ");
                                    foreach($allSubjects as $sub){
                                        ?>
                                        <option value="<?php echo $sub['name']; ?>" <?php if($sub['name'] == $aryForm['name'])echo "selected"; ?> ><?php echo $sub['name']; ?></option>
                                        <?php
                                        }
                                    ?>
                                </select>
                            </div>
						</div>
						<div class="control-group">
							<label class="control-label" for="date"> Date </label>
							<div class="controls">
								<input type="text" id="date" name="date" class="input-block-level datepicker" value="<?php if($_POST)echo $_POST["date"]; elseif (!empty($aryForm["date"])) echo $aryForm["date"]; else echo date('Y-m-d H:i:s'); ?>">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="invoice"> Invoice </label>
							<div class="controls">
								<input type="text" id="invoice" name="invoice" class="input-block-level" value="<?php if($_POST)echo $_POST["invoice"]; else echo $aryForm["invoice"] ?>">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="quantity">Quantity</label>
							<div class="controls">
								<input type="text" id="quantity" onkeyup="calculateAmount()" name="quantity" class="input-block-level" required value="<?php if($_POST)echo $_POST["quantity"]; else echo $aryForm["quantity"] ?>">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="unit">Unit</label>
							<div class="controls">
								<select name="unit" style="width:100%;">
								    <option value="">--Select--</option>
								    <option value="Piece" <?php if($aryForm['unit'] == "Piece")echo "selected"; ?>>Piece</option>
								    <option value="LITER" <?php if($aryForm['unit'] == "LITER")echo "selected"; ?>>LITER</option>
								    <option value="K.G." <?php if($aryForm['unit'] == "K.G.")echo "selected"; ?>>K.G.</option>
								    <option value="METER" <?php if($aryForm['unit'] == "METER")echo "selected"; ?>>METER</option>
								</select>
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="price">Price per Quantity</label>
							<div class="controls">
								<input type="text" onkeyup="calculateAmount()" id="price" name="price" class="input-block-level" required value="<?php if($_POST)echo $_POST["price"]; else echo $aryForm["price"] ?>">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="amount">Gross Amount</label>
							<div class="controls">
								<input type="text" id="amount" name="amount" class="input-block-level"  value="<?php if($_POST)echo $_POST["amount"]; else echo $aryForm["amount"] ?>" readonly>
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="location">Location</label>
							<div class="controls">
								<input type="text" id="location" name="location" class="input-block-level" value="<?php if($_POST)echo $_POST["location"]; else echo $aryForm["location"] ?>">
							</div>
						</div>

						<div class="form-actions">
							<button type="submit" class="btn btn-primary"> Save</button>
							<button type="button" class="btn"> Cancel</button>
						</div>
                        
				</div>
				<!-- / Forms: Content -->

			</div>
			<!-- / Forms: Box -->

        </form>
	</div>
<?php   
}else{
	?>
	<div class="row-fluid"><div class="span12"><div class="top-bar">
    <h3><i class="icon-eye-open"></i> <?php echo ucwords($pgAct." ".$pgMod); ?></h3>

    <?php
        if($permission){ ?>
            <button style="float:right; margin-top:5px" onclick="window.location='./?src=cms&page_id=<?php echo $pgMod; ?>&action=add'" class="btn" type="button">Add <?php echo $pgMod; ?></button>
            <?php } else {?>
            <button style="float:right; margin-top:5px" onclick="showalert('Add new Inventory.')" class="btn" type="button">Add <?php echo $pgMod; ?></button>
            <?php }    ?>

    <button type="button" style="float:right" onclick="printDiv('printDiv')" class="btn btn-danger">Print</button>
    <button class="btn btn-success" onclick="exportTableToExcel('example', 'Inventory')" style="margin-left:35px;float:right;">Excel</button>

    </div>
    <div id="printDiv">
    <div class="well no-padding">
	<?php
	$aryPgAct=array("src"=>"cms", "page_id"=>$pgMod,"action"=>"add");
	$aryList=$db->getRows("SELECT * FROM inventory where school_id='".$_SESSION["admin"]["school_id"]."'"); $i=0;
	if(is_array($aryList) && count($aryList)>0)
	{
		?>
        <table class="table" id="example" border="1" > 
            <thead>
                <tr>
                    <th>Inventory name</th>
                    <th>Quantity </th>
                    <th>Remaining</th>
                    <th>Price</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach($aryList as $clist){ $i++; 
            $aryPgAct["id"]=$clist['id'];
            ?>
                <tr class="grade<?php if($i%2==0)echo "C";else "U";?>">
                    <td><?php echo $clist["name"] ?></td>
                     <td><?php echo $clist["quantity"] ?></td>
                     <td>
                         <?php $sold = $db->getVal("select sum(num_item) from  inventory_receipt where inventory_id='".$clist['id']."' ");
                         $sold1 = $db->getVal("select sum(num_item) from  faculty_inventory_receipt where inventory_id='".$clist['id']."' ");
                         echo $rem = $clist["quantity"] - $sold - $sold1;
                         ?>
                     </td>
                      <td><?php echo $clist["price"] ?></td>
                    <td>
                    <?php 
                    if($permission){
        			$aryPgAct["action"] = "edit";
        			echo '<a href=\''.URL_ADMIN_HOME.getQueryString($aryPgAct).'\'><button type=\'button\' class=\'btn btn-info\'>Edit</button></a>';
        			$aryPgAct['action']="delete";
        			echo '<a href=\'javascript:;\' onclick="del(\''.URL_ADMIN_HOME.getQueryString($aryPgAct).'\')" class=\'confirmation\'><button type=\'button\' class=\'btn btn-danger\'>Delete</button></a>';
                    } else {
                        echo '<a href=\'#\' onclick="showalert(\'Edit Inventory.\')"><button type=\'button\' class=\'btn btn-info\'>Edit</button></a>';
                        echo '<a href=\'#\' onclick="showalert(\'Delete Inventory.\')"><button type=\'button\' class=\'btn btn-danger\'>Delete</button></a>';
                    }
                    
                    // $aryPgAct['action']="edit";$aryPgAct['page_id']=$pgMod; ?>
                         <!--<a style="float:left" href="<?php echo URL_ADMIN_HOME.getQueryString($aryPgAct); ?>"><button type="button" class="btn btn-info">Edit</button></a>-->
                    <?php // $aryPgAct['action']="delete"; ?>
                         <!--<a href="javascript:;" onclick="del('<?php echo URL_ADMIN_HOME.getQueryString($aryPgAct); ?>')" class="confirmation"><button type="button" class="btn btn-danger">Delete</button></a>  -->
                    </td>
                </tr>
            <?php } ?>
            </tbody>

        </table>
		<?php
	}
	else{
		?>
        <div class="alert alert-info">
          <a class="close" data-dismiss="alert">×</a>
          <i class="icon icon-warning-sign"></i> <b>Notice</b> Record not found </i>
        </div>
        <?php
	}
	?>
	</div></div></div></div>
	<?php
}
?>
<!-- / Forms -->

<script>

$(function() {
	$(".datepicker").each(function(index, element) {
        var d = new Date(); // for now
		datetext=d.getHours()+": "+d.getMinutes()+": "+d.getSeconds();
		$( this ).datepicker({
		  changeMonth: true,
		  changeYear: true,
		  showOn: "button",
		  buttonImage: "js/images/calendar.gif",
		  buttonImageOnly: true,
		  buttonText: "Select date",
		  dateFormat: 'yy-mm-dd ',
		  onSelect: function(datetext){
			var d = new Date(); // for now
			datetext=datetext+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
			$(this).val(datetext);
		  }
		});
    });
});


    function exportTableToExcel(tableID, filename = '',e){
    
    var tableType = document.getElementById('example').getAttribute("data-tblname");

    var downloadLink;
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

    // Specify file name
    filename = filename?filename+'.xls':'excel_data.xls';
    
    // Create download link element
    downloadLink = document.createElement("a");
    
    document.body.appendChild(downloadLink);
    
    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], {
            type: dataType
        });
        navigator.msSaveOrOpenBlob( blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
    
        // Setting the file name
        downloadLink.download = filename;
        
        //triggering the function
        downloadLink.click();
    }
    e.preventDefault();
}

function getInventory(head){

    $.post( "cms/ajax.php", { type: "get_inventory", head: head } , function( data ) {
        document.getElementById("inventory_div").innerHTML = data;
	});

}

    function showalert(msg){
        alert('You are not allowed to '+msg);
    }

function calculateAmount(){
    var qty = $("#quantity").val();
    var price = $("#price").val();
    
    var amount = 0;

    if(price > 0 && qty > 0){
         amount = qty*price;
    }
    
    $("#amount").val(amount);
}

</script>
