<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include ('includes/function.php');

$zdb = $_SESSION["zdbyear_$dbname"];
$ztit = $_SESSION["tit"];
$file = "outwdprin.php";
$maindb = 'outmain';
$trandb = 'outtran';


mysqli_select_db($conn, $zdb);
if (isset($_GET["mode"]) == "true") {
    $addflag = 1;
    $gen1 = mysqli_query($conn, "SELECT MAX(vouchno) AS maxcode FROM `$maindb` LIMIT 0,1 ") or die(mysqli_error($conn));
    if (mysqli_num_rows($gen1) > 0) {
        $vvouch = mysqli_fetch_assoc($gen1);
        $qvouch = $vvouch["maxcode"] + 1;
    } else {
        $qvouch = '1';
    }
} else {
    $addflag = 0;
    $qvouch = $_GET["vouchno"];
}
if($qvouch <=9){
   $dvouch = "00".$qvouch;
}elseif ($qvouch <=99) {
   $dvouch = "0".$qvouch;    
}else{
    $dvouch = $qvouch;
}        
if (isset($_POST["submit"])) {
    $a = 1;
    $billdate    = trim($_POST["vouchdt"]);
    $engine      = trim($_POST["engine"]);
    $site        = trim($_POST["site"]);
    $staff        = trim($_POST["staff"]);
    $rem1 = '';
    $rem2 = '';

    $count     = $_POST["items"];
        $mvouch = $qvouch;
        mysqli_query($conn, "DELETE FROM `$trandb` WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
    

        
    for ($i = 0; $i<$count; $i++){
         $msrno         = $_POST["srno_$i"];
         $mitem         = $_POST["item_$i"];
         $mqty          = $_POST["qty_$i"];
         $mlocation     = $_POST["location_$i"];
        
        if(!empty($msrno)){
        
             mysqli_query($conn, "INSERT INTO `$trandb`(vouchno, srno, item, qty, location)
                          VALUES('$mvouch', '$msrno', '$mitem', '$mqty', '$mlocation')") or die(mysqli_error($conn));
        }
    }
    
    
    if ($a == 1) {
        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `$maindb`(vouchno, `vouchdt`, `engine`, `site`, `staff`, `rem1`, `rem2`)
                                          VALUES($qvouch, '$billdate', '$engine', '$site', '$staff', $rem1', '$rem2')") or die(mysqli_error($conn));
            insmess();

            header("refresh: 1; $file?mode=true");
    }else{
            $mvouch = $qvouch;
            mysqli_query($conn, "UPDATE `outmain` SET `vouchdt`='$billdate', `engine`='$engine', `site`='$site', `staff`='$staff', 
                                               `rem1`='$rem1', `rem2`='$rem2' WHERE vouchno = '$mvouch' ") or die(mysqli_error($conn));
            updmess();
            header("refresh: 1; $file?vouchno=$mvouch");
        }
    }
}

if ($addflag == 0) {
    $getvouch = $_GET["vouchno"];
    $result = mysqli_query($conn, "SELECT *, DATE_FORMAT(`invdate`, '%d-%m-%Y') as mydt,
                           DATE_FORMAT(`orddate`, '%d-%m-%Y') as orddt FROM `outmain`
                           WHERE vouchno='$getvouch'") or die(mysqli_error($conn));
    $get = mysqli_fetch_array($result);
   
    
   /*
    $ves    =  mysqli_query($conn, "SELECT * FROM `vessel` WHERE `code`= '$get[vessel]'")or die (mysqli_error($conn));
    $getves =  mysqli_fetch_array($ves);*/

}
?>

<!DOCTYPE HTML>
<html lang="en-US">
    
    <head>
        <meta charset="UTF-8">
        <title>Outward</title>
        <meta name="msapplication-TileColor" content="#5bc0de"/>
        <meta name="msapplication-TileImage" content="assets/img/metis-tile.png"/>
        
        <link rel="stylesheet" href="assets/lib/bootstrap/css/bootstrap.css">
        <link rel="stylesheet" href="assets/css/main.css"/>
        <link rel="stylesheet" href="assets/lib/Font-Awesome/css/font-awesome.css"/>

        <link rel="stylesheet" href="assets/css/theme.css">

        
        <link rel="stylesheet" href="assets/lib/uniform/themes/default/css/uniform.default.css">
        <link rel="stylesheet" href="assets/lib/inputlimiter/jquery.inputlimiter.1.0.css">
        <link rel="stylesheet" href="assets/lib/chosen/chosen.min.css">
        <link rel="stylesheet" href="assets/lib/colorpicker/css/colorpicker.css">
        <link rel="stylesheet" href="assets/lib/tagsinput/jquery.tagsinput.css">
        <link rel="stylesheet" href="assets/lib/daterangepicker/daterangepicker-bs3.css">
        <link rel="stylesheet" href="assets/lib/datepicker/css/datepicker.css">
        <link rel="stylesheet" href="assets/lib/timepicker/css/bootstrap-timepicker.min.css">
        <link rel="stylesheet" href="assets/lib/switch/static/stylesheets/bootstrap-switch.css">
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/flick/jquery-ui.css">
        
        
        <script>
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  
                 m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

            ga('create', 'UA-1669764-16', 'onokumus.com');
            ga('send', 'pageview');

        </script>

        <script src="assets/lib/modernizr-build.min.js"></script>
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript">
            function keyPressed(evt)
            {
                var theEvent = evt || window.event;
                var k = theEvent.keyCode || theEvent.which;
                if (k == 89 || k == 78 || k == 8 || k == 46)
                    return true;
                else {
                    $.msgbox("Invalid Key. Press Y / N ");
                    // alert("Your Message");
                    evt.preventDefault();
                    return false;
                }
            }
        </script>
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type='text/javascript'>
            $(document).ready(function() {
                $('#data').on('keyup', '.packing, .carton, .rate ', calculateRow);

                function name(){
                          var $row  = $(this).closest("tr");
                          var mname = $row.find(".item" ).val();
                          $.get('invoice_add.php', {item: mname}, function(data){
                           
                            $row.find('.desc').val(data); 
                          });                     
                 }
                  
                  

               function addrows(xcode){ 
                  var xcode = xcode; 
                  var ctr = '';
                  if(xcode === 1){
                     var ctr   = $('#items').val();
                     
                     $.post('invoice_add.php', {ctr: ctr, xcode :1}, function(data) {
                            $(data).appendTo('#data');
                            ctr++;
                            $('#items').val(ctr);
                     });
                  }else{
                     var ctr   = $('#packcount').val();
                     $.post('invoice_add.php', {ctr: ctr, xcode :2}, function(data) {
                            $(data).appendTo('#data2');
                            ctr++;
                            $('#packcount').val(ctr);
                     });                      
                  }  
               }

                $('#addnew').click(function() {
                       addrows(1);
                });
                $('#addpack').click(function() {
                       addrows(2);
                });
                $("#discount").keyup(function() {
                    var value  = parseFloat($("#total").val());
                    var disc   = parseFloat($("#discount").val());
                    var taxes  = parseFloat($("#taxes").val());
                    var frgt   = parseFloat($("#freight").val());
                    var mtot   = value - disc + taxes + frgt;
                    $('#billamt').val(mtot.toFixed(2));
                });
                $("#freight").keyup(function() {
                    var value  = parseFloat($("#total").val());
                    var value2 = parseFloat($("#freight").val());
                    var mtax  = parseFloat($("#taxes").val());
                    var mdisc = parseFloat($("#discount").val());
                    var tot = value  + value2 - mdisc + mtax;
                    $('#billamt').val(tot.toFixed(2));
                });
                $("#taxes").keyup(function() {
                    var value  = parseFloat($("#total").val());
                    var value2 = parseFloat($("#taxes").val());
                    var value3 = parseFloat($("#freight").val());
                    var value4 = parseFloat($("#discount").val());
                    
                    var tot = value + value2 + value3 - value4;
                    $('#billamt').val(tot.toFixed(2));
                });
                 
                 
                 


               function calculateTot() {
                     var amt    = 0;
                     var tdisc  = 0;
                     var tvat   = 0;
                     var tst    = 0;
                     var bill   = 0;
                     var val = 0;
                     /*********Total Part************/
                     
                    $(".amount").each(function() {
                        if (!isNaN(this.value) && this.value.length != 0) {
                            val += parseFloat(this.value);
                        }
                    });
                    amt = val.toFixed(2);
                    $("#total").val(amt);
                    
                
               }
                function calculateRow() {
                    var cost = 0;
                    var $row = $(this).closest("tr");
                 
                    var packing = $row.find('.packing').val();
                    var carton  = parseFloat($row.find('.carton').val());
                    var rate    = parseFloat($row.find('.rate').val());
               
                    var pair = packing * carton;
                    $row.find('.pair').val(pair.toFixed(2));
                    var amt  = pair * rate;

                    
                    if (isNaN(amt)) {
                        $row.find('.amount').val("0");
                    } else {
                        $row.find('.amount').val(amt);
                    }
                    calculateTot();
                }
                
                
                /*##################TO SHOW VESSEL AGAINST PARTY########################*/
                /*
                 $("#party").change(function(){
                     var party = $("#party").val();
                   $.post('get_vessel.php', {code: party}, function(data) {
                          //alert(data);
                          $('#vessel').html(data);
                        
                    });
                 });*/
                 $("#consignee").change(function(){
                     var code = $("#consignee").val();
                   $.post('get_add.php', {code: code}, function(data) {
                       //   alert(data);
                          $('#conadd').html("");
                          $('#conadd').append("SHIP STORES IN TRANSIT");
                          $('#conadd').append(data);
                        
                    });
                 });
             /*   $("#party").change(function() {
                    alert("asda");
	           $("#vessel").load("get_vessel.php?code=" + $("#party").val());
                });*/
                
                
            });


        </script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("#lessamt").keyup(function() {
                    var value = parseFloat($("#billamt").val());
                    var value2 = parseFloat($("#lessamt").val());
                    //var newValue = parseInt(value) - parseInt(value2);
                    //alert('newValue');
                    $('#finamt').val(value - value2).toFixed(2);
                });

            });
        </script>
        <style>
          /*  input[type='text']{
                border-radius: 5px;
                height: 20px;
                border: 1px solid #ccc;
            }
            #data td{
                height:10px;
            }*/
        </style>

    </head>

    <body>
        <form action=''  name="invoice" method="POST">
<div class="row">
<div class="col-lg-6" style='width:30%;float:left;'>
    <div class="box dark">
        <header>
            <div class="icons"><i class="fa fa-edit"></i></div>
            <h5>Export Invoice</h5>
            <!-- .toolbar -->
            <div class="toolbar">
                <ul class="nav">
                    <li><a href="#"></a></li>
                    <li>
                        <a class="accordion-toggle minimize-box" data-toggle="collapse" href="#div-1">
                            <i class="fa fa-chevron-up"></i>
                        </a>
                    </li>
                </ul>
            </div>
            <!-- /.toolbar -->
        </header>
        <div id="div-1" class="accordion-body collapse in body">
            <div class="form-horizontal">
              <input type="hidden" size="6" maxlength="6" id="mvouch" maxlength="6" name="mvouch" value="<?php echo ($addflag == 0) ? $get['vouchno'] : $qvouch; ?>" />      
              <div class="form-group">
                <label class="control-label col-lg-4">Voucher No.</label>
                   <div class="col-lg-8"> 
                      <input type="text" size="6" maxlength="6" id="vouchno" name="vouchno" value="<?php echo ($addflag == 0) ? $get['vouchno'] : $qvouch; ?>"  class="form-control" disabled />
                   </div> 
              </div> 
              <div class="form-group">
                <label class="control-label col-lg-4">Engine</label>
                   <div class="col-lg-8">
                       <input type='text' name='chalno' value='<?php echo ($addflag == 0) ? $get['chalno'] : $qvouch; ?>' class="form-control" readonly/>
                   </div>
              </div>
              <div class="form-group">
                <label class="control-label col-lg-4">Site</label>
                   <div class="col-lg-8">
                       <input type='date' name='chaldt' value='<?php echo ($addflag == 0) ? $get['chaldt'] : ""; ?>' class="form-control" />
                   </div>
              </div>    

           </div>
    </div>
</div>        
</div>        

    <div class="col-lg-6" style='width:65%;float:right;'>
    <div class="box dark">
        <header>
            <div class="icons"><i class="fa fa-edit"></i></div>
            <h5>Challan Detail.</h5>
            <!-- .toolbar -->
            <div class="toolbar">
                <ul class="nav">
                    <li>
                      <?php
                       if($addflag == 0){
                            echo '<input class="btn btn-primary" type="button" id="submit" name="print" value="Custom Invoice" onclick="window.open(\'bmtcustinv_prin.php?vouchno=' . $getvouch . '\',\'popUpWindow\',\'height=800,width=950,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes\');" style="width:130px;"/>';
                       }
                           ?>

                    </li>
                    <li>
                     <?php
                        if ($addflag == 0) {
                            echo '<input class="btn btn-primary" type="button" id="submit" name="print" value="Party Invoice" onclick="window.open(\'bmtinvoice_prin.php?vouchno=' . $getvouch . '\',\'popUpWindow\',\'height=800,width=950,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes\');" style="width:130px;"/>';
                        }
                        ?>  
                    </li>
                    <li><input type='submit' name='submit' value='Save' class="btn btn-primary"></li>
                    <li><input type='button' name='exit' value='Exit' class="btn btn-danger" onClick="window.location.href='invoicemain.php'"></li>

                    <li>
                        <a class="accordion-toggle minimize-box" data-toggle="collapse" href="#div-2">
                            <i class="fa fa-chevron-up"></i>
                        </a>
                    </li>
                </ul>
            </div>
            <!-- /.toolbar -->
        </header>
        <div id="div-2" class="accordion-body collapse in body">
                <div style="max-height:300px;overflow: auto; border: 0px solid;">
                <div style="float:left; margin-right:-8220000px;">   
            <table id="data" border="1px" width="63%">

                <tr>
                    <td width="40px" align="center"> <label class="control-label">Sr.</label></td>
                    <td width="150px" align="center"><label class="control-label">Item</label></td>
                    <td width="60px" align="center"><label class="control-label">Location</label></td>
                    <td width="60px" align="center"><label class="control-label">Qty.</label></td>
                </tr>
                <?php
                   if ($addflag == 0) {
                    $qry = mysqli_query($conn, "SELECT * FROM  `outtran` WHERE vouchno='$getvouch' ORDER BY srno") or die(mysqli_error($conn));

                    $ctr = 0;
                    while ($row = mysqli_fetch_array($qry)) {
                        
                         $getitem = mysqli_query($conn, "SELECT * FROM `item` WHERE code='$row[item]'")or die(mysqli_error($conn));
                         $item = mysqli_fetch_object($getitem);
                         
                         $getlocation = mysqli_query($conn, "SELECT * FROM `location` WHERE code='$row[location]'")or die(mysqli_error($conn));
                         $ilocation = mysqli_fetch_object($getlocation);
                echo "<tr>";
                echo "<td align='left'><input type='text' size='6' maxlength='6' maxlength='6' name='srno_$ctr' value='$row[srno]' class='sno form-control'/></td>";
                echo "<td align='left'>";
                echo "<select placeholder='Item'  name='item_$ctr' class='item form-control'>";
                        echo "<option value='$item->code'>$item->name</option>";
                        $mown = mysqli_query($conn, "SELECT code, `name` FROM `item`") or die(mysqli_error($conn));
                        while ($trow = mysqli_fetch_array($mown)) {
                               echo "<option value=$trow[code]>$trow[name]</option>";
                        }
                        echo "</select>";
                        echo "</td>";
                        echo "<td>";
                        echo "<input type='text' size='6'  name='qty_$ctr' value='$row[qty]'  class='qty form-control' style='text-align:right'/>";
                        echo "</td>";
                echo "<td align='left'>";
                echo "<select placeholder='Location'  name='location_$ctr' class='location form-control'>";
                        echo "<option value='$ilocation->code'>$ilocation->name</option>";
                        $mloc = mysqli_query($conn, "SELECT code, `name` FROM `location`") or die(mysqli_error($conn));
                        while ($lrow = mysqli_fetch_array($mloc)) {
                               echo "<option value=$lrow[code]>$lrow[name]</option>";
                        }
                        echo "</select>";
                        echo "</td>";
                        
                    echo "</tr>";
                        $ctr++;
                    }
                    //browse($ctr);
                }else{
                ?>
                    <tr>
                        <td align="left"><input type="text" size="6" maxlength="6" maxlength="6" name="srno_0" class="sno form-control" value="1"/></td>
                        <td align="left">
                            <input type="text" size="6" name="item_0" class="article form-control" />
                        </td>
                        <td align="center"><input type="text"  name="qty_0" class="color form-control"/></td>
                        <td align="left">
                            <input type="text" name="location_0" class="size form-control"/>
                        </td>
                        
                    </tr>
                <?php } ?>
   </table>
            </div>  
        
    </div>
            <table border='0' width='100%'>
   

        <tr>
            <td width="150px">
                <input type="button" id="addnew" class="btn btn-success btn-lg" name="addnew" value="+" />
                       <input type="hidden" id="items" name="items" value="<?php echo ($addflag == 0) ? $ctr : 1; ?>" />  
           </td><td width="240px"></td><td width="140px"></td><td width="200px" align="right"><label for=""><font color="black" size="3px">Bill Amount</font><span></span></label></td>
            <td width="200px"><input id="total" type="text" name="total" class="form-control"  value="<?php echo ($addflag == 0) ? $get['total'] : "0.00"; ?>" readonly style='text-align:right'></td>
        </tr>
   
            </table>
    </div>    
        
</div>
    <div class="box dark">
        <header>
            <div class="icons"><i class="fa fa-edit"></i></div>
            <h5>Packing List.</h5>
            <!-- .toolbar -->
            <div class="toolbar">
                <ul class="nav">

                    <li>
                        <a class="accordion-toggle minimize-box" data-toggle="collapse" href="#div-2">
                            <i class="fa fa-chevron-up"></i>
                        </a>
                    </li>
                </ul>
            </div>
            <!-- /.toolbar -->
        </header>
        <div id="div-2" class="accordion-body collapse in body">
                <div style="max-height:300px;overflow: auto; border: 0px solid;">
                <div style="float:left; margin-right:-8220000px;">   
            <table id="data2" border="1px" width="100%">

                <tr>
                    <td width="60px" align="center"> <label class="control-label">Sr No.</label></td>
                    <td width="180px" align="center"><label class="control-label">Title</label></td>
                    <td width="90px" align="center"><label class="control-label">Qty</label></td>
                    <td width="300px" align="center"><label class="control-label">Description</label></td>
                </tr>
                <?php
                   if ($addflag == 0) {
                    $pqry = mysqli_query($conn, "SELECT * FROM  `packlist` WHERE vouchno='$getvouch' ORDER BY srno") or die(mysqli_error($conn));

                    $pctr = 0;
                    while ($prow = mysqli_fetch_array($pqry)) {
                        
                       echo "<tr>";
                        echo "<td align='left' valign='top'><input type='text' size='6' maxlength='6' maxlength='6' name='psrno_$pctr' value='$prow[srno]' class='sno form-control'/></td>";
                        echo "<td align='left' valign='top'>";
                        echo "<input type='text' name='title_$pctr' value='$prow[title]'  class='form-control' style='text-align:left;'/>";
                        echo "</td>";
                        echo "<td align='left' valign='top'><input type='text' size='6' name='pqty_$pctr' value='$prow[qty]' class='sno form-control'/></td>";
                        echo "<td align='center' valign='top'><input type='text' name='pdescrip_$pctr' class='desc form-control' value='$prow[description]'/></td>";
                      echo "</tr>";
                        $pctr++;
                    }
                    //browse($ctr);
                }else{
                ?>
                    <tr>
                        <td align="left" valign="top"><input type="text" size="6" maxlength="6" maxlength="6" name="psrno_0" class="sno form-control" value="1"/></td>
                        <td align="left" valign="top">
                            <input type="text"  name="title_0" class="form-control" style='text-align:left;'/>
                        </td>
                        <td align="left" valign="top"><input type="text" size="6" name="pqty_0" class="form-control"/></td>
                        <td align="center" valign="top"><input type="text" name="pdescrip_0" class="desc form-control" /></td>

                    </tr>
                <?php } ?>
   </table>
            </div>  
        
    </div>
            <table border='0' width='100%'>
   

        <tr>
            <td width="150px">
                <input type="button" id="addpack" class="btn btn-success btn-lg" name="addnew" value="+" />
                       <input type="hidden" id="packcount" name="packcount" value="<?php echo ($addflag == 0) ? $pctr : 1; ?>" />  
            </td><td width="240px"></td><td width="140px"></td><td width="200px" align="right"><label for=""><font color="black" size="3px"></font><span></span></label></td>
            <td width="200px"></td>
        </tr>
            </table>

    </div>    
        
</div>
</div>
</div>
</div>            
            
        </form>





              
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="assets/lib/jquery.min.js"><\/script>')</script> 

        <script src="assets/lib/bootstrap/js/bootstrap.js"></script>
        
        <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
        

        
   <script src="assets/lib/uniform/jquery.uniform.min.js"></script>
<script src="assets/lib/jquery.dualListbox-1.3/jquery.dualListBox-1.3.min.js"></script>
<script src="assets/lib/autosize/jquery.autosize.min.js"></script>
<script src="assets/lib/jasny/js/bootstrap-inputmask.js"></script>
        

        <script src="assets/js/main.js"></script>

        
        <script>
            $(function() { formGeneral(); });
        </script>
        

    </body>
</html>
