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

/*
if($pgAct=="viewall"){
	global $db,$LinksDetails;
	$pgTable = "student";
	$dataAry = array();
	$sqlArray = array();
	$i = 0;
	$table = "";
	$select = "";
	$where = "";
	$whereAry = array();
	
	$whereAry[] = " school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' and status=1 and issue_TC=0";
	if (isset($_REQUEST["class"]) && $_REQUEST["class"] != "") {
		$whereAry[] = " class='".$_REQUEST["class"]."' "; 
	}
	if(isset($_REQUEST["section"]) && $_REQUEST["section"]!="" && $_REQUEST["section"]!="undefined"){
		$whereAry[] = " section='".$_REQUEST["section"]."' ";
	}
	if (isset($_REQUEST["q"]) && $_REQUEST["q"] != "") {
		$whereAry[] = " (admissionno like '%".$_REQUEST["q"]."%'
					OR name like '%".$_REQUEST["q"]."%'
					OR class like '%".$_REQUEST["q"]."%'
					OR section like '%".$_REQUEST["q"]."%'
					OR medium like '%".$_REQUEST["q"]."%'
					OR cast like '%".$_REQUEST["q"]."%'
					OR fname like '%".$_REQUEST["q"]."%'
					OR mobile like '%".$_REQUEST["q"]."%') ";
	}
	
	if (is_array($whereAry) && count($whereAry) > 0)
		$where = " WHERE " . implode(" AND ", $whereAry);
		
	$pcount = $db->getVal("select count(admissionno) from  student $where");

	$startV = $_REQUEST['startV'];
	$endV = $_REQUEST['endV'];
	$ProDetail["totPost"] = $pcount;

	$contentDetail = $db->getRows("select * from student $where order by name DESC " . ($endV == 'All' ? "" : "limit $startV, $endV"));

	$ProDetail["query"] = $db->getLastQuery();
	$ProDetail["ncount"] = count($contentDetail);
	$ProDetail["tcolumn"] = 9;
	if (is_array($contentDetail) && count($contentDetail) > 0) {
		$aryData = array();
		$i = 0;
		foreach ($contentDetail as $iList) {
			$button = "";
			//$aryPgAct["id"] = $iList['id'];
		//	$aryPgAct["page_id"] = $pgMod;
			$image="<img src='".URL_ROOT."uploads/product/50/50/".$iList['front_image']."' width='50'  />";
			$button = "";
		
		
		    $aryPgAct['src']="cms";
			$aryPgAct['page_id']="faculty_inventory";
			//$button .= '<a href="javascript:;" onclick="del(\''.URL_ADMIN_HOME.getQueryString($aryPgAct).'&id='.$iList['idno'].'\')" class="confirmation"><button type="button" class="btn btn-danger">Delete</button></a>';
			$button .= '<a href="'.URL_ADMIN_HOME.getQueryString($aryPgAct).'&action=add&id='.$iList['idno'].'"><button type="button" class="btn btn-info">Inventory</button></a>';
			$i++;
			//$aryPgAct["action"] = "submenu";
			$aryData[] = array(
				POST($iList['admissionno']),
				POST($iList['name']),
				POST($iList['class'])."(".POST($iList['section']).")",
				POST($iList['medium']),
			
				POST($iList["cast"]),
				POST($iList['fname']),
			
				$button,
			);
		}
		$ProDetail["Result"] = $aryData;
	}
	echo json_encode($ProDetail);
	exit;
}
*/

if($pgAct=="viewall"){
	global $db,$LinksDetails;
	$pgTable = "staff";
	$dataAry = array();
	$sqlArray = array();
	$i = 0;
	$table = "";
	$select = "";
	$where = "";
	$whereAry = array();
	
	$whereAry[] = " school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' and status=1 ";
// 	if (isset($_REQUEST["class"]) && $_REQUEST["class"] != "") {
// 		$whereAry[] = " class='".$_REQUEST["class"]."' "; 
// 	}
// 	if(isset($_REQUEST["section"]) && $_REQUEST["section"]!="" && $_REQUEST["section"]!="undefined"){
// 		$whereAry[] = " section='".$_REQUEST["section"]."' ";
// 	}
	if (isset($_REQUEST["q"]) && $_REQUEST["q"] != "") {
		$whereAry[] = " (department like '%".$_REQUEST["q"]."%'
					OR name like '%".$_REQUEST["q"]."%'
					OR fname like '%".$_REQUEST["q"]."%'
					OR mobile like '%".$_REQUEST["q"]."%') ";
	}
	
	if (is_array($whereAry) && count($whereAry) > 0)
		$where = " WHERE " . implode(" AND ", $whereAry);
		
	$pcount = $db->getVal("select count(idno) from  staff $where");

	$startV = $_REQUEST['startV'];
	$endV = $_REQUEST['endV'];
	$ProDetail["totPost"] = $pcount;

	$contentDetail = $db->getRows("select * from staff $where order by name DESC " . ($endV == 'All' ? "" : "limit $startV, $endV"));

	$ProDetail["query"] = $db->getLastQuery();
	$ProDetail["ncount"] = count($contentDetail);
	$ProDetail["tcolumn"] = 9;
	if (is_array($contentDetail) && count($contentDetail) > 0) {
		$aryData = array();
		$i = 0;
		foreach ($contentDetail as $iList) {
			$button = "";

		    $aryPgAct['src']="cms";
			$aryPgAct['page_id']="faculty_inventory";

			$button .= '<a href="'.URL_ADMIN_HOME.getQueryString($aryPgAct).'&action=add&id='.$iList['idno'].'"><button type="button" class="btn btn-info">Inventory</button></a>';
			$i++;

			$aryData[] = array(
				POST($i),
				POST($iList['name']),
				POST($iList['fname']),
				POST($iList['mobile']),
				POST($iList["department"]),

				$button,
			);
		}
		$ProDetail["Result"] = $aryData;
	}
	echo json_encode($ProDetail);
	exit;
}





elseif($_POST)
{
	$_SESSION['form']=$_POST;
	//$section=$_POST["section"];unset($_POST["section"]);
		
	if(isset($_FILES["photo"]["name"]) && !empty($_FILES["photo"]["name"])){
		$lfilename = basename($_FILES['photo']['name']);
		$lext = strtolower(substr($lfilename, strrpos($lfilename, '.')+1));
		$lnewfile=md5(microtime()).".".$lext;
		if(move_uploaded_file($_FILES['photo']['tmp_name'],"media/photo/".$lnewfile))
		{
			$_POST["photo"]=$lnewfile;
		}
	}
	
	if($flgEr!=TRUE && $pgAct=="add")
	{
		$_POST["school_id"]=$_SESSION["admin"]["school_id"];
        $_POST["added_by"]=$_SESSION["admin"]["uid"];
		$flgIn=$db->insertAry("enquiry",$_POST);
		if(!is_null($flgIn))
		{
			$_SESSION['msg']='Saved Successfully';
			unset($_SESSION['form']);
			sms($_POST["mobile"],"Dear Parent Your admission enquiry is successfully submitted in ".$LinksDetails["site_name"],"student_enrollment");
			if($db->getErMsg()!=""){
				array_push($alert_err,$db->getErMsg());
			}else{
				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("enquiry",$_POST,"where school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$_GET['id']."' and session='".$_SESSION["admin"]["session"]."'");
		//echo $db->getLastQuery();exit;
		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'])!='')
{
	//$flgUp=$db->updateAry("student",array("status"=>0),"where idno='".$_GET['id']."' and session='".$_SESSION["admin"]["session"]."'");
	//$flgUp=$db->updateAry("installment",array("status"=>0),"where idno='".$_GET['id']."' and session='".$_SESSION["admin"]["session"]."'");
	$flgUp=$db->delete("inventory_receipt","where school_id='".$_SESSION["admin"]["school_id"]."' and rid='".$_GET['rid']."' and idno='".$_GET['id']."' and session='".$_SESSION["admin"]["session"]."'");
	if(!is_null($flgUp)) { $_SESSION['msg']='Deleted Successfully'; }
	else { array_push($alert_err,$db->getErMsg()); }
	redirect(URL_ADMIN_HOME.getQueryString(array("src"=>"cms", "page_id"=>$pgMod,"action"=>"add","id"=>$_GET['id'])));
}
/*elseif($pgAct=="cancel" && isset($_GET['id']) && trim($_GET['id'])!='')
{	 $idate=date("Y-m-d");
	$flgUp=$db->updateAry("student",array("status"=>3, "added_by"=>$_SESSION["admin"]["uid"], "idate"=>$idate),"where school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$_GET['id']."' and session='".$_SESSION["admin"]["session"]."'");
	redirect(URL_ADMIN_HOME.getQueryString(array("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 enquiry WHERE school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$_GET['id']."'");
}
if($pgAct=="add" || ($pgAct=="edit" && isset($_GET['id']) && trim($_GET['id']) !='')){
	 
	if(isset($_SESSION['form']))
	{
		$aryForm=$_SESSION['form'];
		unset($_SESSION['form']);
	}
	$aryForm=$db->getRow("SELECT * FROM staff WHERE school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$_GET['id']."'");
	
	
?>
<!-- Forms --> 
<style>.top-bar-minimize{display:none;}
thead, tfoot {display: table-header-group;}
.top-bar+.well,.accordion .accordion-heading+.accordion-body{display: inline-block !important;width: 96.7% !important;overflow: inherit !important;} 
</style>
<div id="printDiv">		
     <div class="row-fluid">
        <div class="span12">
            <div class="top-bar">
                <h3><i class="icon-cog"></i> Student detail</h3>
                <div style="float:right; margin-top:5px;">
                </div>
            </div>
            	<div style="float:right; margin-top:5px;">
            	    
            	    </div>
            <div class="well" id="userdetails" style="padding: 0;margin: 0;">
            	<table class="table">
                	<tr style="border-right: 5px solid #f00;border-left: 5px solid #f00;">
                    	<td><strong class="st">Name</strong></td><td style="border-right:5px solid #f00"><?php echo $aryForm["name"] ?></td>
                        <td><strong class="st">Father</strong></td><td style="border-right:5px solid #f00"><?php echo $aryForm["fname"] ?></td>
                        <td><strong class="st">Department</strong></td><td style="border-right:5px solid #f00"><?php echo $aryForm["department"] ?></td>

                        <td rowspan="2"><?php if($aryForm["photo"]!=""){
                        ?><img src="media/photo/<?php echo $aryForm["photo"]; ?>" style="height:70px" /><?php
                    }else{
                        echo "No photo uploaded";
                    }?></td>
                    </tr>
                    <tr style="border-right: 5px solid #f00;border-left: 5px solid #f00;">
                    	<td><strong class="st">DOB</strong></td><td style="border-right:5px solid #f00"><?php echo $aryForm["dob"] ?></td>
                        
                        <td><strong class="st">DOJ</strong></td><td style="border-right:5px solid #f00"><?php echo $aryForm["doj"] ?></td>
                        <td><strong class="st">Contact</strong></td><td style="border-right:5px solid #f00"><?php echo $aryForm["mobile"] ?></li></td>
                    </tr>
                </table>
            </div>
        </div>
     </div> 
     
     <?php //$inventroyList=$db->getRows("SELECT * FROM inventory_receipt r left join inventory i on r.inventory_id=i.id WHERE r.school_id='".$_SESSION["admin"]["school_id"]."' and r.idno='".$_GET['id']."'  GROUP BY r.rid");

     ?>

 	<!--<div>-->

  <!--  <table class="table">-->
  <!--      <tr>-->
  <!--          <th>S.No.</th>-->
  <!--          <th>Item</th>-->
  <!--          <th>Quantity</th>-->
  <!--          <th>Price</th>-->
  <!--          <th>Issue Date</th>-->
  <!--          <th>Action</th>-->
  <!--      </tr>-->
        <?php /* $j = 1;
            foreach($inventroyList as $inv){
                $aryPgAct['page_id']=$pgMod;
                $aryPgAct["rid"] =$inv['rid'];
                $aryPgAct["id"] =$_GET['id'];
                
                $items = $db->getRows("select * from inventory_receipt where rid='$inv[rid]' ");
                
                ?>
                    <tr>
                        <td><?php echo $inv['rid']; ?></td>
                        <td>
                            <?php foreach($items as $item){
                                $name = $db->getVal("select name from inventory where id='".$item['inventory_id']."' ");
                                echo $name."<br>";
                            } ?>
                        </td>
                        <td><?php foreach($items as $item){
                                echo $item['num_item']."<br>";
                            } ?>
                        </td>
                        <td><?php foreach($items as $item){
                                echo $item['total_amount']."<br>";
                            } ?>
                        </td>
                        <td><?php echo $inv['issue_date'];?></td>
                        <td>
                            <?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>
                            
                            <input type="button" class="btn btn-info" onclick="getReceipt(<?php echo $inv['rid']; ?>)" value="Print" />
                        </td>
                    </tr>
                <? $j++;
            }
    */    ?>
        
    <!--</table>-->

    <div id="preview_div">
        
    </div>


    <?php
    	$sql="select * from inventory where  school_id='".$_SESSION["admin"]["school_id"]."'  order by name";
    	$aryList=$db->getRows($sql);
        $itemvalue=$db->getVal("select sum(num_item) where idno= school_id='".$_GET['id']."'");
    ?>
<br><br>
  <div class="row-fluid">
        <div class="span12">
            <div class="top-bar">
                <h3><i class="icon-cog"></i>  detail</h3> 
                <div style="float:right; margin-top:5px">
                 <!--<button class="btn btn-default" onclick="paynow('<?php echo $clist['id'] ?>')" data-id="<?php echo $clist['id'] ?>" type="button" id="btn<?php echo $clist['id'] ?>">Pay</button>-->

                 <button type="button" class="btn btn-primary" onclick="receiptHistory()" >Receipt History</button>

                 <!--<button type="button" class="btn btn-primary" id="myBtn">View Detail</button>-->
                 <!--<input type="hidden" value="<?php echo count($aryList); ?>" id="allitem" />-->
                 <button class="btn btn-default" onclick="paynow(<?php echo count($aryList); ?>)" data-id="<?php echo $clist['id'] ?>" type="button" id="btn<?php echo $clist['id'] ?>">Pay</button>
                </div>
            </div>

<style>
.notfound{
  display: none;
}
</style>

            <div class="well no-padding">
                 
             	<div class="half">
             	    <br>
             	    <select onchange="getList(this.value)">
             	        <option value="">All</option>
             	        <?php 
             	            $heads = $db->getRows("select * from inventory_names where head_type='Head' ");
             	            foreach($heads as $hd){
             	                echo "<option value='$hd[name]'>$hd[name]</option>";
             	            }
             	        ?>
             	    </select>
                    <center style="color:blue">Inventory List Detail</center>
                    <input type='text' id='txt_searchall' placeholder='Enter search here' style="float:right;">
                    <!--<input type='text' id='txt_name' placeholder='Enter search name'>-->
                    <br/><br/>
                <div id="itemsDiv">
                <input type="hidden" value="<?php echo count($aryList); ?>" id="allitem" />
                <table class="table">
                <thead>
					<tr>
						<th>Serial No</th>
						<th>Inventory Name</th>
						<th>Inventory Quantity</th>
						<th>Price</th>
						<th>Booking Inventory </th>
                        <th>Total Amount</th>
                        <th>Discount</th>
                        <th>Tick</th>
					</tr>
				</thead>
				<tbody>
						<?php foreach($aryList as $clist){ $i++;

						?>
						<tr>
				    	<td><?php echo $i; ?></td>
						<td><?php echo $clist["name"] ?>
    						<input type="hidden" id="item_name<?php echo $i; ?>" value="<?php echo $clist["name"] ?>" />
						</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>
					        <input class="py" type="hidden"  data-id="<?php echo $i; ?>" id="price<?php echo $i; ?>" value="<?php echo $clist["price"] ?>" /> <?php echo $clist["price"] ?>
					    </td>

				     	<td width="15%">
				     	    <input class="py" type="text" name="advance_payment[]" data-id="<?php echo $i; ?>" id="itom<?php echo $i; ?>"  value="1" onkeyup="showpreview(<?php echo $i; ?>)" />
			     	    </td>
 
                        <td>
                            <input class="py" name="grasstotal[]" type="text" data-id="<?php echo $i; ?>" id="GrossTotal<?php echo $i; ?>"  value="<?php echo $clist["price"]*1; ?>" readonly />
                        </td>

                        <td>
                            <input class="py" type="text" name="discount[]" style="width:100px;" id="discount<?php echo $i; ?>" onkeyup="showpreview(<?php echo $i; ?>)" />
                        </td>

                        <td>
                            <input class="checkboxes" type="checkbox" name="sid[]" value="<?php echo $clist["id"];?>" id="item_<?php echo $i; ?>" onclick="showpreview(<?php echo $i;?>)" />
                        </td>

                   </tr>
					<?php	}
						?>
                    <tr class='notfound'>
                     <td colspan='4'>No record found</td>
                   </tr>
                    </tbody>
                 </table>
                 </div>
          </div>
         </div>
    </div>
</div>  
<!-- / Forms -->
<?php
}
else{
?>
    </script>
	<div class="row-fluid"><div class="span12"><div class="top-bar">
    <h3><i class="icon-eye-open"></i> <?php echo ucwords($pgAct." ".$pgMod); ?></h3>
    <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>
    </div>
    <div class="well no-padding">
	<?php
	$aryPgAct=array("src"=>"cms", "page_id"=>$pgMod,"action"=>"add");
	//$aryList=$db->getRows("select idno from student where school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' and status=1 and issue_TC=0 order by name");
	//if(is_array($aryList) && count($aryList)>0)
	{
		?>
        <div style="position: absolute;width:300px;z-index: 99999;margin: 30px;">
        	<select onchange="applyfilter()" class="span6 searchFilter" name="class" id="class" >
                <option value="">Class</option>
                <?php 
                    $class=$db->getRows("select * from class where school_id='".$_SESSION["admin"]["school_id"]."'");
                    foreach($class as $cla){
                        ?>
                        <option value="<?php echo $cla["class"] ?>">
                            <?php echo $cla["class"] ?>
                        </option>
                        <?php
            
                    }
                ?>
            </select>
            <select onchange="applyfilter()" class="span6 searchFilter" name="section" id="section" >
                <option value="">Section</option>
                <?php 
                    $class=$db->getRows("select * from section where school_id='".$_SESSION["admin"]["school_id"]."'");
                    foreach($class as $cla){
                        ?>
                        <option value="<?php echo $cla["name"] ?>">
                            <?php echo $cla["name"] ?>
                        </option>
                        <?php
            
                    }
                ?>
            </select>
         </div>
        <input type="hidden" id="tabletype" value="faculty_inventory" />
        <input type="hidden" id="CurrentPage" name="CurrentPage" value="1">
        <input type="hidden" name="startV" id="startV" value="0">
        <input type="hidden" name="endV" id="endV" value="5">
        <div class="searchData"></div>
        <table class="table table-widget table-striped" id="mssresulttable" data-action="viewall" data-extra="&type=student" data-page="index.php?src=cms&page_id=faculty_inventory&loadData=yes" data-table="student">
            <thead>
                <tr>
                   <th width="10%">S. No.</th>
                    <th width="20%">Name</th>
                    <th>Father Name</th>
                    <th>Mobile</th>
                    <th>Department</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tfoot>
            </tfoot>
            <tbody id="resultBody">
           
            </tbody>
        </table>
        <div class="paginationData"></div>
		<?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>
	<?php
}
?>


<style>

/* The Modal (background) */
.modal {
  display:none;
  border-radius:20px;
}

/* Modal Content */
.modal-content {
      border-radius:20px;
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 100%;
}

/* The Close Button */
.close {
  color: navy;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
</style>

<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
        
        <div id="previewdata"></div>
        
  </div>

</div>

<script>

function getList(inv){
$.post( "cms/ajax.php", { 	type: "getList",
			    				name:inv,
						} , function( data ) {

                $("#itemsDiv").html(data);

	});
	
}

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    
    var allitems = document.getElementById('allitem').value;

    var mydata = '<table class="table"><tr class="table table-danger"><th>S.No.</th> <th>Item</th> <th>Qty</th> <th>Price</th> <th>Total</th> </tr>';
    var j = 1;
    var totalamt = 0;
    for(var i = 1; i<=allitems; i++){
    
    if(document.getElementById('item_'+i).checked == true){
        var name = $("#item_name"+i).val();
        var id = $("#item_"+i).val();
        var qty = $("#itom"+i).val();
        var price = $("#price"+i).val();
        var amount = $("#GrossTotal"+i).val();
            
        totalamt= parseInt(totalamt) + parseInt(amount);

        mydata+= '<tr> <td>'+j+'</td> <td>'+name+'</td> <td>'+qty+'</td> <td>'+price+'</td> <td>'+amount+'</td>  </tr>';

        j++;

        }
    }
    mydata+='<tr class="table table-primary"> <th colspan="4">Total</th> <th>'+totalamt+'</th> </tr>';    
    mydata+='</table>';

    document.getElementById('previewdata').innerHTML = mydata;
    
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</script>


<script>
// $(".py").each(function(id) {
// 	$("#itom"+id).on("keyup",function(){
// 		getamountTotal(id)
// 	});

// 	$("#discount"+id).on("keyup",function(){
// 		getamountTotal(id)
// 	});
// });

function getamountTotal(id){
   // alert(id);
    	var itom=$("#itom"+id).val();
    //	alert(AdvancePayment);
    		var price=$("#price"+id).val();
            var discount = $("#discount"+id).val();
    		Finaltotal=((itom*price)-discount);

    		$("#GrossTotal"+id).val(Finaltotal);
    // 		showpreview();
}
 
function paynow(items){

    var items = document.getElementById('allitem').value;
    
    var totalitems = [];

    for(var i = 1; i<=items; i++){

    if(document.getElementById('item_'+i).checked == true){
        var id = $("#item_"+i).val();
        var qty = $("#itom"+i).val();
        var price = $("#price"+i).val();
        var discount = $("#discount"+i).val();
        var amount = $("#GrossTotal"+i).val();
        totalitems.push({"id":id,"qty":qty,"price":price,"amount":amount, "discount":discount})
        }
    }

	$.post( "cms/ajax.php", { 	type: "facultyinventory",
			    				items:totalitems,
								idno:'<?php echo  $_GET['id']  ?>',
						} , function( data ) {
						  //  alert(data);

	   // getPopup("<?php echo URL_ROOT ?>print/?page_id=inventory_receiptNew&idno="+<?php echo  $_GET['id'] ?>+"&rno="+data);
        getPopup("<?php echo URL_ROOT ?>print/?page_id=faculty_inventory_receipt&id="+<?php echo  $_GET['id'] ?>+"&rid="+data);
    		$(".close").click(function() {
    		$(this).parent().remove();
    		location.reload();
    	});
    	$(".outer").click(function() {
    		$(this).remove();
    		location.reload();
    	});
	});
	
// 	$.post( "cms/ajax.php", { 	type: "paybybranch" ,
// 			    				inventory_id:id,
// 								idno:'<?php echo  $_GET['id']  ?>',
// 				    			itom:$("#itom"+id).val(),
//     							price:$("#price"+id).val(),
// 	    						Grossamount:$("#GrossTotal"+id).val()
// 						} , function( data ) {

// getPopup("<?php echo URL_ROOT ?>print/?page_id=inventory_receiptNew&idno="+<?php echo  $_GET['id'] ?>);		
// 		$(".close").click(function() {
// 		$(this).parent().remove();
// 		location.reload();
// 	});
// 	$(".outer").click(function() {
// 		$(this).remove();
// 		location.reload();
// 	});

// 	});
}




function receiptHistory(){
	getPopup("<?php echo URL_ROOT ?>print/?page_id=faculty_inventory_history&id=<?php echo $_GET["id"]?>");
	$(".close").click(function() {
		$(this).parent().remove();
		window.location.reload();
	});
	$(".outer").click(function() {
		window.location.reload();
	});
}

function showpreview(id){
    getamountTotal(id);
    var allitems = document.getElementById('allitem').value;

    var mydata = '<table class="table"><tr class="table table-danger"><th>S.No.</th> <th>Item</th> <th>Qty</th> <th>Price</th> <th>Discount</th> <th>Total</th> </tr>';
    var j = 1;
    var totalamt = 0;
    for(var i = 1; i<=allitems; i++){
    
    if(document.getElementById('item_'+i).checked == true){
        var name = $("#item_name"+i).val();
        var id = $("#item_"+i).val();
        var qty = $("#itom"+i).val();
        var price = $("#price"+i).val();
        var discount = $("#discount"+i).val();
        var amount = ((qty*price)-discount);

        totalamt= parseInt(totalamt) + parseInt(amount);

        mydata+= '<tr> <td>'+j+'</td> <td>'+name+'</td> <td>'+qty+'</td> <td>'+price+'</td> <td>'+discount+'</td> <td>'+amount+'</td>  </tr>';

        j++;

        }
    }
    mydata+='<tr class="table table-primary"> <th colspan="5">Total</th> <th>'+totalamt+'</th> </tr>';    
    mydata+='</table>';
    if(j > 1){
        document.getElementById('preview_div').innerHTML = mydata;
    } else {
        document.getElementById('preview_div').innerHTML = '';
    }

}


</script>
<!-- / Forms -->
<script type="text/javascript">
$(document).ready(function(e) {
    var oTable = $('#ajaxtable').dataTable( {
		"bProcessing": true,
		'sPaginationType': 'full_numbers',
		"sAjaxSource": 'Enquiry/ajax.php?type='+$('#tabletype').val(),
		'iDisplayLength': 5,
		"oLanguage": {
			"sSearch": "Search by any columns:"
		}
	});
});
function fetchByClass(){
	var name=$("#class").val();
	var section=$("#section").val();
	if(name!=""){
		var url='ajax.php?class='+name+'&type='+$('#tabletype').val();
		if(section!=""){
			url+='&section='+section
		}
		 oTable = $('#ajaxtable').dataTable( {
			"bProcessing": true,
			'sPaginationType': 'full_numbers',
			"bServerSide": false,
			"bDestroy":true,
			"sAjaxSource": url,
			'iDisplayLength': 5,
			"oLanguage": {
				"sSearch": "Search by any columns:"
			}
		});
	}else{
		var oTable = $('#ajaxtable').dataTable( {
			"bProcessing": true,
			'sPaginationType': 'full_numbers',
			"bServerSide": false,
			"bDestroy":true,
			"sAjaxSource": 'ajax.php?type='+$('#tabletype').val(),
			'iDisplayLength': 5,
			"oLanguage": {
				"sSearch": "Search by any columns:"
			}
		});
	}
}
function checkform(){
	var data="name="+$("#name").val()+"&dob="+$("#dob").val()+"&fname="+$("#fname").val()+"&mname="+$("#mname").val()+"&cast="+$("#cast").val()+"&mobile="+$("#mobile").val();
	$.post( "ajax.php?"+data, { type: "PreCheckExist"} , function( data ) {
		//alert(data);
	  	if(data=="0"){
			$("#saveme").click();
		}else{
			alert(data);
			if(confirm("are you sureyou want to register a this student?")){
				$("#saveme").click();
			}else{
				if(confirm("You want to add new student?")){
					window.location='?page_id=make_admission&action=add';
				}else{
					window.location='?page_id=make_admission';
				}
			}
		}
	});
	return false;
}
function changeIns(){
	var cla=$("#class").val();
	$.post( "ajax.php", { type: "classinstallment" ,class: cla } , function( data ) {
	  	$("#ins").html(data);
		getTotal();
	});
}
function buschangeIns(){
	var bus=$("#bus").val();
	if(bus==""){
		$("#busins").html('');
	}else{
		$.post( "ajax.php", { type: "businstallment", bus: bus } , function( data ) {
			$("#busins").html(data);
			getbusTotal();
		});
	}
}
function hostelchangeIns(){
	var hostel=$("#hostel").val();
	if(hostel==""){
		$("#hostelins").html('');
	}else{
		$.post( "ajax.php", { type: "hostelinstallment", hostel: hostel } , function( data ) {
			$("#hostelins").html(data);
			gethostelTotal();
		});
	}
}
function getTotal(){
	var sum=0;var classfee=0;var busfee=0;
	var cost = document.getElementsByName('fee[]');
	classfee=$('#classfee').val();
	for(var i=0;i<cost.length;i++)
	{
		sum = parseFloat(sum) + parseFloat(cost[i].value);
	}
	$('#feetotal').val(parseInt(sum));
	$('#oldtotal').val(parseInt(sum));
}
function getbusTotal(){
	var sum=0;var classfee=0;var busfee=0;
	var cost = document.getElementsByName('busfee[]');
	classfee=$('#busclassfee').val();
	for(var i=0;i<cost.length;i++)
	{
		sum = parseFloat(sum) + parseFloat(cost[i].value);
	}
	$('#busfeetotal').val(parseInt(sum));
	$('#busoldtotal').val(parseInt(sum));
}
function gethostelTotal(){
	var sum=0;var hostelfee=0;
	var cost = document.getElementsByName('hostelfee[]');
	hostelfee=$('#hostelclassfee').val();
	for(var i=0;i<cost.length;i++)
	{
		sum = parseFloat(sum) + parseFloat(cost[i].value);
	}
	$('#hostelfeetotal').val(parseInt(sum));
	$('#hosteloldtotal').val(parseInt(sum));
}
function updateIns(){
	var sum=0;
	 var discountAmt=$("#discount").val();
	 var TotalAmt=$('#oldtotal').val();
	 var RestedAmt=TotalAmt-discountAmt;
	 var cost = document.getElementsByName('fee[]');
	 if(RestedAmt<=0){
		alert("Discount Cannot Greater Then Total Fees"+TotalAmt);
		$("#discount").val(0);
		var DevidedAmt = (TotalAmt/(cost.length));
		$('.feeInsCharge').val(DevidedAmt);
	}else{
		var DevidedAmt = (RestedAmt/(cost.length));
		$('.feeInsCharge').val(DevidedAmt);
	}
	for(var i=0;i<cost.length;i++)
	{
		sum = parseFloat(sum) + parseFloat(cost[i].value);
	}
	$('#feetotal').val(parseInt(sum));
}
function busupdateIns(){
	var sum=0;
	 var discountAmt=$("#busdiscount").val();
	 var TotalAmt=$('#busoldtotal').val();
	 var RestedAmt=TotalAmt-discountAmt;
	 var cost = document.getElementsByName('busfee[]');
	 if(RestedAmt<=0){
		alert("Discount Cannot Greater Then Total Fees"+TotalAmt);
		$("#busdiscount").val(0);
		var DevidedAmt = (TotalAmt/(cost.length));
		$('.busfeeInsCharge').val(DevidedAmt);
	}else{
		var DevidedAmt = (RestedAmt/(cost.length));
		$('.busfeeInsCharge').val(DevidedAmt);
	}
	for(var i=0;i<cost.length;i++)
	{
		sum = parseFloat(sum) + parseFloat(cost[i].value);
	}
	$('#busfeetotal').val(parseInt(sum));
}
function hostelupdateIns(){
	var sum=0;
	var discountAmt=$("#hosteldiscount").val();
	var TotalAmt=$('#hosteloldtotal').val();
	var RestedAmt=TotalAmt-discountAmt;
	var cost = document.getElementsByName('hostelfee[]');
	if(RestedAmt<=0){
		alert("Discount Cannot Greater Then Total Fees"+TotalAmt);
		$("#hosteldiscount").val(0);
		var DevidedAmt = (TotalAmt/(cost.length));
		$('.hostelfeeInsCharge').val(DevidedAmt);
	}else{
		var DevidedAmt = (RestedAmt/(cost.length));
		$('.hostelfeeInsCharge').val(DevidedAmt);
	}
	for(var i=0;i<cost.length;i++)
	{
		sum = parseFloat(sum) + parseFloat(cost[i].value);
	}
	$('#hostelfeetotal').val(parseInt(sum));
}
function getsibling(id){
	$.post( "ajax.php", { type: "getsibling", id: id } , function( data ) {
	  	alert(data);
	});
}
function checkvalid(id){
	if($("#name").val()=="")
		alert("student name cannot blank");
	else
	if($("#fname").val()=="")
		alert("student fathers name cannot blank")
	else
	if($("#class").val()=="")
		alert("please select student class")
	else
	{
		$("#saveformbutton").hide();
		$("#saveme").click();
	}
}


function getStudentfinePopup(){
		var url="";
		var idno = [];
		var price = [];
		var itom = [];
		$(".checkboxes").each(function(){
			if($(this).prop('checked')==true){
			     idno.push($(this).val());
			}
		})

		for (let i = 0; i < idno.length; ++i) {
        	itom.push($("#itom"+idno[i]).val())
        	price.push($("#price"+idno[i]).val());
        }
		url+="&itom="+itom;
		if(url!=""){
		getPopup("<?php echo URL_ROOT ?>print/?page_id=inventory_receipt&id=<?php echo $_GET["id"]?>&itom="+itom+"&idno="+idno+"&type=multiple_inventory   ");
			$(".close").click(function() {
				$(this).parent().remove();
			});
			$(".outer").click(function() {
				$(this).remove();
			});
		}else{
		//	alert("select atleast one student to mgrate");
		}
	}
</script>


<script>
    $(document).ready(function(){

  // Search all columns
  $('#txt_searchall').keyup(function(){
    // Search Text
    var search = $(this).val();

    // Hide all table tbody rows
    $('table tbody tr').hide();

    // Count total search result
    var len = $('table tbody tr:not(.notfound) td:contains("'+search+'")').length;

    if(len > 0){
      // Searching text in columns and show match row
      $('table tbody tr:not(.notfound) td:contains("'+search+'")').each(function(){
        $(this).closest('tr').show();
      });
    }else{
      $('.notfound').show();
    }

  });

  // Search on name column only
  $('#txt_name').keyup(function(){
    // Search Text
    var search = $(this).val();

    // Hide all table tbody rows
    $('table tbody tr').hide();

    // Count total search result
    var len = $('table tbody tr:not(.notfound) td:nth-child(2):contains("'+search+'")').length;

    if(len > 0){
      // Searching text in columns and show match row
      $('table tbody tr:not(.notfound) td:contains("'+search+'")').each(function(){
         $(this).closest('tr').show();
      });
    }else{
      $('.notfound').show();
    }

  });

});

// Case-insensitive searching (Note - remove the below script for Case sensitive search )
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
   return function( elem ) {
     return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
   };
});

</script>

<style>
.recepit {
	width: 900px !important;
	height: 500px !important;
}
.outer, .inner{
  max-height: 800px;
  min-height: 500px;
 }
  .outer .undefined{
  background-color: #DADADA !important;
  border: 5px inset #181616 !important;
  min-height: 500px;
  min-width:900px;
}
</style>
