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

$formname = 'Order Delivery';
$maindb = 'ordelmain';
$trandb = 'ordeltran';
$stkdb = 'ordelsacn';
$printfile = "ordelprin.php";
$file = 'orderdel.php';
$source = "ODL";
/* $grid = 'salemain.php'; */
$trandbexist = 1;
$keyfld = "vouchno";

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

$admin = $_SESSION["admin_" . $dbname];

include("includes/vouchno_generate.php");
include("includes/prev&next.php");

if (isset($_POST["submit"])) {
    $a = 1;
    $vouchdt = $_POST["vouchdt"];
    $party   = $_POST["party"];
    $ordno   = $_POST["order"];
    $payt    = $_POST["payterm"];
    $rem1    = trim($_POST["rem1"]);
    $rem2    = trim($_POST["rem2"]);
    $total   = trim($_POST["total"]);

    $count = $_POST["items"];

    $mvouch = $qvouch;

    $mgroup = $source . $qvouch;

    if (empty($vouchdt)) {
        browse("Delivery Date Cannot Be Empty");
        $a = 0;
    }

    /*  if ($billamt <= 0) {
      browse("Bill Amount Cannot Be Zero");
      $a = 0;
      }
     */
    if ($a == 1) {

        ###################### TRAN PART #####################################################


        mysqli_query($conn, "DELETE FROM `$trandb` WHERE vouchno='$mvouch'") or die(mysqli_error($conn));

        $cnt = 0;
        $cntamt = 0;
        for ($i = 0; $i < $count; $i++) {
            $msrno = $_POST["srno_$i"];
            $mdescrip = $_POST["descrip_$i"];
            $mqty = $_POST["qty_$i"];
            $munit = $_POST["unit_$i"];
            $mrate = $_POST["rate_$i"];
            $mamt = $_POST["amt_$i"];

            if (!empty($msrno) && !empty($mqty)) {
                $geti = mysqli_query($conn, "SELECT * FROM `item` WHERE `name`='$mdescrip' ") or die(mysqli_error($conn));
                $iget = mysqli_fetch_assoc($geti);
                $mdescode = $iget['code'];

                mysqli_query($conn, "INSERT INTO `$trandb`(`vouchno`, `ordno`, `srno`, `descrip`, qty, unit, rate, amt)
                                            VALUES('$mvouch', '$ordno', '$msrno','$mdescode', '$mqty', '$munit', '$mrate', '$mamt')") or die(mysqli_error($conn));
                
            }
        }

        ######################### STOCK PART ####################################################

        mysqli_query($conn, "DELETE FROM `$stkdb` WHERE vouchno='$mvouch' AND `source`='$source'") or die(mysqli_error($conn));

//        $cnt = 0;
        for ($i = 0; $i < $count; $i++) {
            $msrno = $_POST["srno_$i"];
            $mdescrip = $_POST["descrip_$i"];
            $mqty = $_POST["qty_$i"];
            $munit = $_POST["unit_$i"];
            $mrate = $_POST["rate_$i"];
            $mamt = $_POST["amt_$i"];

            if (!empty($mqty) && !empty($msrno)) {
                $geti = mysqli_query($conn, "SELECT * FROM `item` WHERE `name`='$mdescrip' ") or die(mysqli_error($conn));
                $iget = mysqli_fetch_assoc($geti);
                $mdescode = $iget['code'];

                mysqli_query($conn, "INSERT INTO `$stkdb`(`vouchno`, `ordno`, `srno`, `descrip`, qty, unit, rate, amt, source, `group`, `party` )
                                            VALUES('$mvouch', '$ordno', '$msrno','$mdescode', '$mqty', '$munit', '$mrate', '$mamt', '$source', '$mgroup', '$party' )") or die(mysqli_error($conn));
            }
        }

        ############################## MAIN  ######################################################

        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `$maindb`(vouchno, `ordno`, `vouchdt`, `party`,  payterm, `rem1`, `rem2`, total)
                                        VALUES($qvouch, '$ordno', '$vouchdt', '$party', '$payt', '$rem1', '$rem2', '$total')") or die(mysqli_error($conn));
            insmess();
            $mvouch = $qvouch; //1

            header("refresh: 1; $file?mode=edit&vouchno=$mvouch");
        } else {
            $mvouch = $qvouch; //1

            mysqli_query($conn, "UPDATE `$maindb` SET `vouchno`='$qvouch',`vouchdt`='$vouchdt', `party`='$party', `ordno`='$ordno', payterm='$payt',
                        `rem1`='$rem1', `rem2`='$rem2', total='$total' WHERE vouchno = '$mvouch' ") or die(mysqli_error($conn));
            updmess();
            header("refresh: 1; $file?mode=edit&vouchno=$mvouch");
        }
    }
}

if ($addflag != 1) {

    $getvouch = '';
    if ($addflag == 0) {
        $getvouch = $_GET[$keyfld];
    } else {
        $getvouch = $qvouch;
    }

    $result = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE $keyfld='$getvouch'") or die(mysqli_error($conn));
    $get = mysqli_fetch_array($result);

    $party = mysqli_query($conn, "SELECT * FROM `accmast` WHERE accode='$get[party]'") or die(mysqli_error($conn));
    $getparty = mysqli_fetch_object($party);
}

/* DELETE */
if (isset($_GET["delete"])) {
    delete($zdb, "$maindb", "vouchno", $_GET["vouchno"], "$file?mode=last");
    delete($zdb, "$trandb", "vouchno", $_GET["vouchno"], "$file?mode=last");

    $delcond = " source = '$source' and vouchno = '$_GET[vouchno]' ";
    delnew($zdb, "$stkdb", "$delcond", "$file?mode=last");
}
include("includes/files.php");
?>

<!DOCTYPE HTML>
<html lang="en-US">



    <meta charset="UTF-8">
    <title>Order Delivery</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" src="js/jquery.bpopup.min.js"></script>
    <script type='text/javascript'>
        $(document).ready(function () {
            $('#packdata').on('keyup', '.qty, .rate, .amt, .total ', calculateRow);
            //   $('#data').on('blur', '.size', showprevious);
            $("#main_container" ).on( "click", '.remove', remove );

            function addrows() {
                //alert('a');
                var ctr = $('#items').val();
                $.post('ordel_add.php', {ctr: ctr, xcode: 1}, function (data) {
                    $(data).appendTo('#data');
                    ctr++;
                    $('#items').val(ctr);
                });
            }

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

            $('#addnew').click(function () {
                addrows();
            });

            $('#addpack').click(function () {
                addrows(2);
            });
            
            function remove(){
                    $(this).closest("tr").remove();
                }

            function calculateTot() {
                var amt = 0;
                var val = 0;
                /*********Total Part************/

                $(".amt").each(function() {
                    if (!isNaN(this.value) && this.value.length != 0) {
                    val += parseFloat(this.value);
                    }
                });
                amt = val.toFixed(2);
                $("#total").val(amt);

        }
            
            function calculateRow() {

                var $row = $(this).closest("tr");

                var qty = $row.find('.qty').val();
                var rate = parseFloat($row.find('.rate').val());

                var amt = qty * rate;
                $row.find('.amt').val(amt.toFixed(2));
                
                if (isNaN(amt)) {
                    $row.find('.amt').val("0");
                } else {
                    $row.find('.amt').val(amt);
                }
                calculateTot();
            }


            /*##################TO SHOW VESSEL AGAINST PARTY########################*/

            $("#party").change(function () {
                var party = $("#party").val();
                $.post('get_ord.php', {code: party, para: "order"}, function (data) {
                    $('#orders').html(data);
                });
                
            });

            $("#orders").change(function () {
                var party = $("#orders").val();
                var mvouch = $("#vouchno").val();
                var maccode = $("#party").val();

                $.post('get_order_detail.php', {code: party}, function (data) {
                    //alert(data);
                    $('#destination').val(data);

                });
                $.post('get_tran.php', {code: party, vouchno: mvouch, accode: maccode}, function (data) {
                    $('#packdata').html(data);
                    calculateRow();

                });
            });

            
        });


    </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>
    <script type="text/javascript" src="jquery-1.6.1.min.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            //open popup
            $("#pop").click(function () {
                $("#overlay_form").fadeIn(1000);
                positionPopup();
            });

            //close popup
            $("#close").click(function () {
                $("#overlay_form").fadeOut(500);
            });
        });

        //position the popup at the center of the page
        function positionPopup() {
            if (!$("#overlay_form").is(':visible')) {
                return;
            }
            $("#overlay_form").css({
                left: ($(window).width() - $('#overlay_form').width()) / 2,
                top: ($(window).width() - $('#overlay_form').width()) / 7,
                position: 'absolute'
            });
        }

        //maintain the popup at center of the page when browser resized
        $(window).bind('resize', positionPopup);

    </script>
    <style>
        #overlay_form{
            position: absolute;
            border: 5px solid gray;
            padding: 10px;
            background: white;
            width: 800px;
            max-height: 400px;
            overflow: auto;
        }
        #pop{
            display: block;
            border: 1px solid gray;
            width: 65px;
            text-align: center;
            padding: 6px;
            border-radius: 5px;
            text-decoration: none;
            margin: 0 auto;
        }
    </style>
    

</head>
<!--<a href="#" id="pop" >PopUp</a>
<br />-->
<body style="background: transparent;" id="main_container">
    <div id="overlay_form" style="display:none;z-index:999;">
        <a href="#" id="close" style="float: right;font-weight: bold;font-size: 18px;color:red;" >X</a>
        <div style='width:100%;' id='browdata'>

        </div>
    </div>

<form action=''  name="cargo" method="POST">
    <br>
    <br>
    <div>   
        <div class="row">
            <div class="col-lg-6" style='width:100%;float:left;'>
                <div class="box dark">
                    <header class="navbar navbar-default navbar-fixed-top" style="padding-top: 10px">
                        <div class="icons"><i class="fa fa-edit"></i></div>
                        <h5><?php echo $flag . " " . $formname; ?></h5>
                        <div class="toolbar" >
                            <ul class="nav">
                                <li>
                                    <?php
                                    include_once("includes/buttons.php");
                                    ?>
                                </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>
                    </header>
                    <div id="div-1" class="accordion-body collapse in body">
                        <div class="form-horizontal">
                            <table border="0"  class="table table-ordered">
                            <tr>
                                <th>Delivery No.</th>  
                                <th style="width:50px;"></th>
                                <th>Delivery Date</th>  
                                <th style="width:50px;"></th>
                                <th>Party</th>  
                                <th style="width:50px;"></th>
                                <th>Order No.</th>                                    
                            </tr>
                            <tr>
                                <td>
                                    <input type="text"  name="vouchno" value="<?php echo ($addflag != 1) ? $get['vouchno'] : $qvouch; ?>"  class="form-control" style="width: 100px;" disabled /> 
                                </td>
                                <td style="width:50px;"></td>
                                <td>
                                    <input type="date" size="" id="vouchdt" name="vouchdt" value="<?php echo ($addflag != 1) ? $get['vouchdt'] : date("Y-m-d"); ?>"  class="form-control form"  required/>  
                                </td>
                                <td style="width:50px;"></td>
                                <td>
                                    <select id="party" name="party" class="form-control form" style="height: 30px;width: 350px;">
                                        <option value="<?php echo ($addflag != 1) ? $getparty->accode : ''; ?>"><?php echo ($addflag != 1) ? $getparty->name : ''; ?></option>
                                        <?php
                                        $mpart = mysqli_query($conn, "SELECT accode, `name` FROM `accmast` where grpcode = '009' ") or die(mysqli_error($conn));
                                        while ($urow = mysqli_fetch_array($mpart)) {
                                            echo "<option value=$urow[accode]>$urow[name]</option>";
                                        }
                                        ?>
                                    </select>
                                </td>
                                <td style="width:50px;"></td>
                                <td>
                                    <select id="orders" name="order" class="form-control form" style="height: 30px;width: 150px;">
                                    <?php
                                    if ($addflag != 1) {
                                        echo "readonly";
                                    }
                                    ?>
                                    <?php
                                        if ($addflag != 1) {
                                        echo "<option value='$get[ordno]' selected>$get[ordno]<option>";
                                    }
                                    ?>
                                    </select>
                                </td>

                            </tr>
                        </table>  
                        </div>              
                    </div>
                </div>
            </div>        
        </div>        

        <div class="col-lg-6" style='width:100%;float:left;'>
            <div class="box dark">
                <div id="div-2" class="accordion-body collapse in body">
                    <div id="packdata">
                        <table id="data" border="1px" width="60%" class="table table-ordered">
                            <header>
                                <div class="icons"><i class="fa fa-edit"></i></div>
                                <h5>Purchase Detail</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>
                            <tr>
                                <td></td>
                                <td width="5%" align="center"> <label class="control-label">Sr.</label></td>
                                <td width="50%" align="center"><label class="control-label">Description</label></td>
                                <td width="10%" align="center"><label class="control-label">Qty.</label></td>
                                <td width="10%" align="center"><label class="control-label">Unit</label></td>
                                <td width="10%" align="center"><label class="control-label">Rate</label></td>
                                <td width="17%" align="center"><label class="control-label">Amount</label></td>
                            </tr>
                            <?php
                            if ($addflag != 1) {
                                $qry = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE $keyfld='$qvouch' ORDER BY srno") or die(mysqli_error($conn));
                                $ctr = 0;
                                while ($row = mysqli_fetch_array($qry)) {
                                    $getdesc = mysqli_query($conn, "SELECT * FROM `item` WHERE code='$row[descrip]'") or die(mysqli_error($conn));
                                    $gdesc = mysqli_fetch_assoc($getdesc);

                                    echo "<tr>";
                                    echo '<td align="center" valign="top"><input type="image" src="images/delbut.png" name="remove form" class="remove form" value="remove"></td>';
                                    echo "<td align='left' valign='top'><input type='text' size='6' maxlength='6' name='srno_$ctr' class='sno form-control form' style='height:33px;' value='$row[srno]'/></td>";
                                    echo "<td align='left' valign='top'><input type='text' size='6' name='descrip_$ctr' class='descrip form-control form' style='height:33px;' value='$gdesc[name]'/></td>";
                                    echo "<td align='right' valign='top'><input type='text' size='4'  name='qty_$ctr' class='qty form-control form'  style='text-align:right;height:33px;' value='$row[qty]'></td>";
                                    echo "<td align='right' valign='top'><input type='text' size='4'  name='unit_$ctr' class='unit form-control form'  style='text-align:left;height:33px;' value='$row[unit]'></td>";
                                    echo "<td align='right' valign='top'><input type='text' size='4'  name='rate_$ctr' class='rate form-control form'  style='text-align:right;height:33px; width: 100px;' value='$row[rate]'></td>";
                                    echo "<td align='right' valign='top'><input type='text' size='4'  name='amt_$ctr' class='amt form-control form'  style='text-align:right;height:33px; width: 100px;' value='$row[amt]' readonly></td>";

                                    echo "</tr>";
                                    
                                    $ctr++;
                                }
                                /*                                browse($ctr); */
                            } 
                            ?>
                        </table>
                    </div>     
                    <table border='0' width='100%' >
                        <tr>
                            <td width="100px">&nbsp;&nbsp;&nbsp;
                                <input type="button" id="addnew" style="height: 30px; width: 30px; padding: 0px" class="btn btn-success btn-lg form" accode="addnew" value="+" />
                                <?php
                                    if ($addflag != 1) {
                                        ?>
                                        <input type="hidden" id="items" name="items" value="<?php echo $ctr; ?>" />  
                                        <?php
                                    }
                                    ?>
                            </td><td width="240px"></td><td width="140px"></td>

                            <td width="610px"></td>
                            <td width="100px" align="right"><label><font color="black" size="3px">Total </font></label></td>

                            <td width='100px'>
                                <input  type="text" id="total" name="total" class="total form-control form"  value="<?php echo ($addflag != 1) ? $get['total'] : "0"; ?>" readonly style='text-align:right; width:110px'>
                            </td>
                            
                        </tr>
                        <tr>
                            <td align="left" valign="top"><b>Credit Days</b></td>
                            <td width="50px">
                                <input type="text" size="3" id="payterm" name="payterm" value="<?php echo ($addflag != 1) ? $get['payterm'] : '' ?>" class="form-control form" style="width: 50px;"/>
                            </td>                        
                        </tr>
                        <tr>
                            <td align="left" valign="top"><b>Remarks</b></td>
                            <td colspan="2">
                                <input type="text" name="rem1" value="<?php echo ($addflag == 0) ? $get['rem1'] : ""; ?>" class="form-control form">
                                <input type="text" name="rem2" value="<?php echo ($addflag == 0) ? $get['rem2'] : ""; ?>" class="form-control form">
                            </td>
                            <td></td>
                            <td></td>
                        </tr>
                    </table>
                </div>
            </div>
            <!-- Search Part-->
                <div class="modal fade in slacker-modal"  role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="false">
                <div class="modal-dialog modal-slacker">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                            <h4 class="modal-title" id="myLargeModalLabel"></h4>
                        </div>
                        <div class="modal-body" style="height: 100%;white-space: nowrap;">
                            <div class="row">

                                <div class="col-md-12">

                                    <div class="col-lg-12">

                                        <div class="box">
                                            <div id="collapse4" class="body">
                                                <table id="dataTable" class="table table-bordered table-condensed table-hover table-striped">
                                                    <thead>
                                                        <tr>
                                                            <th align='left'>P.O. No.</th>
                                                            <th align='left'>P.O. Date</th>
                                                            <th align='left'>Party</th>
                                                            <th align='left'>Company</th>
                                                            <th align='left'>Action</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php
                                                        $srchresult = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE $keyfld!=''") or die(mysqli_error($conn));
                                                        while ($row = mysqli_fetch_array($srchresult)) {
                                                            
                                                            $getparty1 = mysqli_query($conn, "SELECT `name` FROM `accmast` WHERE accode='$row[party]'") or die(mysqli_error($conn));
                                                            $party1 = mysqli_fetch_object($getparty1);

                                                            $getc = mysqli_query($conn, "SELECT * FROM `branch` WHERE code='$row[company]'") or die(mysqli_error($conn));
                                                            $com = mysqli_fetch_object($getc);
                                                            
                                                            echo "<tr>";
                                                            echo "<td align='left'>$row[vouchno]</td>";
                                                            echo "<td align='left'>$row[vouchdt]</td>";
                                                            echo "<td align='left'>$party1->name</td>";
                                                            echo "<td align='left'>$com->compname</td>";
                                                            echo "<td align='left'><a href=\"$file?mode=edit&$keyfld=$row[$keyfld]\"><img src='images/edit.png'></a></td>";
                                                            echo "</tr>";
                                                        }
                                                        ?>
                                                    </tbody>
                                                </table>
                                                <script>
                                                    $(function () {
                                                        metisTable();
                                                        metisSortable();
                                                    });
                                                </script>

                                            </div>

                                        </div>

                                    </div>

                                </div><!-- /.row -->

                            </div>
                        </div>  
                        <div class="modal-footer" style="bottom: 0px;position: absolute;padding:0px;">
                            <!--"This is where i want to load my salemain.php"-->
                        </div>
                    </div>
                </div>
            </div>
            </div>
        </div>
    </form>
    <?php
    include("includes/files_footer.php");
    ?>
    <script>
        $(function () {
            formGeneral();
        });
    </script>