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

$formname = 'Internal Transfer';
$maindb = 'trnfmain';
$trandb = 'trnftran';
$stkdb = 'transacn';
/*$printfile = "trnfprint.php";*/
$file = 'transfer.php';
$source = "TR";
$trandbexist = 1;

/* $grid = 'salemain.php'; */

$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;
    $billdate = $_POST["vouchdt"];
    $mloc1   = trim($_POST["loc1"]);
    $mloc2   = trim($_POST["loc2"]);
    $rem1 = trim($_POST["rem1"]);
    $rem2 = trim($_POST["rem2"]);

    $count = $_POST["items"];
    $mvouch = $qvouch;

    $mgroup = $source . $qvouch;

    if ($mloc1 == $mloc2) {
        browse("From Location & To Location Cannot Be Same");
        $a = 0;
    }
    
    if (empty($billdate)) {
        browse("Voucher Date Cannot Be Empty");
        $a = 0;
    }
    
    /*if ($mloc1  = $mloc2) {
        browse("From Location and To Location Cannot be Same");
        $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"];
            $mitem = $_POST["item_$i"];
            $mqty = $_POST["qty_$i"];
            
            if (!empty($mqty) && !empty($mitem)) {
                $geti = mysqli_query($conn, "SELECT * FROM `item` WHERE `name`='$mitem' ") or die(mysqli_error($conn));
                $iget = mysqli_fetch_assoc($geti);
                $mitemcode = $iget['code'];
                $grp = $iget['group'];

                $cnt = $cnt + 1;
                /* $cntamt = $cntamt + $mamt; */
                mysqli_query($conn, "INSERT INTO `$trandb`(`vouchno`,`srno`, `itemcode`, 
                                    qty)
                        VALUES('$mvouch', '$cnt','$mitemcode', '$mqty')") 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"];
            $mitem = $_POST["item_$i"];
            $mqty = $_POST["qty_$i"] * -1;

            if (!empty($mitem)) {
                $geti = mysqli_query($conn, "SELECT * FROM `item` WHERE `name`='$mitem' ") or die(mysqli_error($conn));
                $iget = mysqli_fetch_assoc($geti);
                $mitemcode = $iget['code'];
                $grp = $iget['group'];

                $cnt = $cnt + 1;
                mysqli_query($conn, "INSERT INTO `$stkdb`(`vouchno`, `vouchdt`, `source`,  `srno`, `itemcode`, 
                                   `itemgrp`, qty, `location`)
                        VALUES('$mvouch', '$billdate', '$source', '$cnt', '$mitemcode', '$grp', 
                                   '$mqty', '$mloc1')") or die(mysqli_error($conn));
            }
        }
        
        $scnt = 0;
        for ($j = 0; $j < $count; $j++) {
            $msrno = $_POST["srno_$j"];
            $mitem = $_POST["item_$j"];
            $mqty = $_POST["qty_$j"];

            if (!empty($mitem)) {
                $getj = mysqli_query($conn, "SELECT * FROM `item` WHERE `name`='$mitem' ") or die(mysqli_error($conn));
                $jget = mysqli_fetch_assoc($getj);
                $mitemcode = $jget['code'];
                $grp = $jget['group'];
        $scnt = $scnt + 1;
                mysqli_query($conn, "INSERT INTO `$stkdb`(`vouchno`, `vouchdt`, `source`,  `srno`, `itemcode`, 
                                   `itemgrp`, qty, `location`)
                        VALUES('$mvouch', '$billdate', '$source', '$scnt', '$mitemcode', '$grp', 
                                   '$mqty', '$mloc2')") or die(mysqli_error($conn));
            }
        }
        ############################## MAIN  ######################################################

        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `$maindb`(vouchno, `vouchdt`, `loc1`, `loc2`, `rem1`, `rem2`)
                                        VALUES($qvouch, '$billdate', '$mloc1', '$mloc2', '$rem1', '$rem2')") 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`='$billdate', `loc1`='$mloc1', `loc2`='$mloc2',
                        `rem1`='$rem1', `rem2`='$rem2' 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 *, DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as mydt FROM `$maindb`
                           WHERE vouchno='$getvouch'") or die(mysqli_error($conn));
    $get = mysqli_fetch_array($result);
    
    $getloc1 = mysqli_query($conn, "SELECT * FROM `location` WHERE `code`= '$get[loc1]'") or die(mysqli_error($conn));
    $getloc = mysqli_fetch_object($getloc1);

    $getloc2 = mysqli_query($conn, "SELECT * FROM `location` WHERE `code`= '$get[loc2]'") or die(mysqli_error($conn));
    $getloca = mysqli_fetch_object($getloc2);
    
}

$senable = "";
$cenable = "";

/* 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");
?>


<script type='text/javascript'>
    $(document).ready(function() {
//                $('#data').on('keyup', '.s5, .s6, .s7, .s8, .s9, .s10, .s11, .s12, .soth, .qty, .rate', calculateRow);
        /*$('#data').on('keyup', ' .qty, .rate', calculateRow);
         $('#data').on('keyup', ' .s5, .s6, .s7, .s8, .s9, .s10, .s11, .s12, .soth', getstk);
         $('#data').on('change', ' .s5, .s6, .s7, .s8, .s9, .s10, .s11, .s12, .soth', calculateRow);
         $('#data').on('change', '.item', showdtl);
         $('#data').on('change', '.color', colorchange);
         $('#data').on('blur', '.amt', addrow2);
         $('#billing').on('keyup', '#discperc, #lessdisc, #vatperc, #addvat, #packing', calculat);
         $('#data').on('keyup', '.mrp', calculatemrp);
         $("#main_container").on("click", '.remove', remove);*/

        function addrow2() {
            if ($(this).closest("tr").is(":last-child")) {
                addrows();
            }
        }

        function remove() {
            $(this).closest("tr").remove();
        }


        function check() {
            $('#submit').removeAttr("disabled");
            var $row = $(this).closest("tr");
            var item = $row.find('.item').val();
            if ($row.find('.item').children(":selected").val() === "") {
                alert("ITEM CANNOT BE EMPTY");
                $('#submit').attr("disabled", true);
            }
        }

        function addrows() {
            var ctr = $('#items').val();
            var hide_check = "";
            if ($("#del_all").prop("checked")) {
                hide_check = 0;
            } else {
                hide_check = 1;
            }
            $.post('transfer_add.php', {ctr: ctr, hide: hide_check}, function(data) {
                $(data).appendTo('#data');
                ctr++;
                $('#items').val(ctr);
            });
        }

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


        function getstk() {
            var $row = $(this).closest("tr");
            var size_value = parseInt($(this).val());
            var chkstk = 1;
            if (size_value > 0) {
                var idx = $(this).attr("name");
                var id = idx.split("_")[1];
                var item_name = $row.find('.item').val();
                var item_color = $("select[name='location_" + id + "']").val();
                var item_size = idx.split("_")[0];
                var bill_date = $("#billdate").val();
//                        alert(idx + ' 1 ' + id + ' 2 ' + item_code + ' 3 ' + item_color + '  4 ' + item_size);
                $.ajax({
                    type: 'GET',
                    url: "checkstk_sale.php",
                    data: "itemname=" + item_name + "&location=" + item_location +  "&bill_date=" + bill_date,
                    success: function(response) {
                        var code = response.code;
                        if (code === "0") {
                            alert("No Stock Found");
                            var chkstk = 0;
                        } else {
                            var size_stk = response.isizeval;
                            if (size_stk < size_value) {
                                alert("Qty. Exceeds Stock Limit : " + size_stk);
                                var chkstk = 0;
                            }
                        }
//                                        var isize = "'." + item_size + "'"
//                                        $($row.find(isize)).val('0');

                        if (chkstk === 0) {
                            if (item === '$code') {
                                $($row.find('.item')).val('0');
                            }
                            return false;
                        } else {

//                                    calculateRow();
                        }
                    }
                });
            }
//                     calculateRow();
        }

        function calculateRow() {
            var mtot = 0;
            var $row = $(this).closest("tr");
            var ms5 = parseFloat($row.find('.s5').val());
            var ms6 = parseFloat($row.find('.s6').val());
            var ms7 = parseFloat($row.find('.s7').val());
            var ms8 = parseFloat($row.find('.s8').val());
            var ms9 = parseFloat($row.find('.s9').val());
            var ms10 = parseFloat($row.find('.s10').val());
            var ms11 = parseFloat($row.find('.s11').val());
            var ms12 = parseFloat($row.find('.s12').val());
            var msoth = parseFloat($row.find('.soth').val());
            var tempqty = ms5 + ms6 + ms7 + ms8 + ms9 + ms10 + ms11 + ms12 + msoth;
            parseFloat($row.find('.qty').val(tempqty));
            var qty = tempqty;
            var cost = parseFloat($row.find('.rate').val());
            var fintot = qty * cost;
            /*  console.log(fintot);*/
            if (isNaN(fintot)) {
                $row.find('.amt').val("0");
            } else {
                $row.find('.amt').val(fintot.toFixed(1));
                $row.find('.amt').trigger('change');
            }
            calculateTot();
        }

        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 = parseFloat(val);
            $("#subtotal").val(amt.toFixed(2));
            calculat();
        }


        function calculat() {
            var mamt = parseFloat($("#subtotal").val());
            var mdiscperc = parseFloat($("#discperc").val());
            var mdisc = parseFloat($("#lessdisc").val());
            var mvatperc = parseFloat($("#vatperc").val());
            var mvat = parseFloat($("#addvat").val());
            var mpack = parseFloat($("#packing").val());
            $('#discperc').removeAttr("readonly");
            $('#lessdisc').removeAttr("readonly");
            $('#vatperc').removeAttr("readonly");
            $('#addvat').removeAttr("readonly");
            if (mdiscperc > 0) {
                $('#lessdisc').attr("readonly", true);
            }
            if (mvatperc > 0) {
                $('#addvat').attr("readonly", true);
            }

            var mdisc = mamt * mdiscperc / 100;
            $('#lessdisc').val(mdisc);
            var mtot1 = mamt - mdisc;
            var mvat = mtot1 * mvatperc / 100;
            $('#addvat').val(mvat.toFixed(2));
            var mnet = mamt - mdisc + mvat + mpack;
            $('#billamt').val(mnet.toFixed(2));
            if (mdisc > 0 && mdiscperc <= 0) {
                $('#discperc').attr("readonly", true);
            }

        }

        /*Delete All Part*/
        function show_hide_delete() {
            if ($("#del_all").prop("checked")) {
                $(".remove").hide();
            } else {
                $(".remove").show();
            }

        }

        $("#del_all").attr("checked", true);
        show_hide_delete();
        $("#del_all").click(function() {
            show_hide_delete();
        });
    });
</script>
<style>
    #data td{
        padding:0px;

    }
</style>

</head>

<hr/>
<body onLoad="document.boq.vouchdt.focus()" id="main_container">
    <form action=''  name="invoice" method="POST">
        <div class="row">
            <div class="col-lg-6" style='width:100%;'>
                <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">

                        <table border="0">
                            <tr>
                                <th> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    Voucher No.&nbsp;
                                </th>  
                                <td>
                                    <input type="text"  name="vouchno" value="<?php echo ($addflag == 0) ? $get['vouchno'] : $qvouch; ?>"  class="form-control" disabled /> 
                                </td>
                                <th style="width:150px;"></th>
                                <th> &nbsp;&nbsp;&nbsp;
                                    Voucher Date.
                                </th>  
                                <td>
                                    <input type="date" size="" id="vouchdt" name="vouchdt" value="<?php echo ($addflag == 0) ? $get['vouchdt'] : date("Y-m-d"); ?>" class="form-control form"  required/>  
                                </td>
                                <th style="width:150px;"></th>
                                
                            </tr>
                            <tr style="height:10px;">
                            </tr>
                            <tr>
                                <th> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;
                                    From Location
                                    &nbsp;&nbsp;&nbsp;
                                </th>  
                                <td colspan ="1">
                                    <select id="loc1" name="loc1" class="form-control form" style='height:33px;' required>
                                         <option value="<?php echo ($addflag != 1) ? $getloc->code : ''; ?>"><?php echo ($addflag != 1) ? $getloc->name : ''; ?></option>
                                         <?php
                                           $mown = mysqli_query($conn, "SELECT code, `name` FROM `location` WHERE code != '' ORDER BY name") or die(mysqli_error($conn));
                                            while ($trow = mysqli_fetch_array($mown)) {
                                                echo "<option value=$trow[code]>$trow[name]</option>";
                                            }
                                            ?>
                                        </select>
                                </td>
                                <th style="width:150px;"></th>
                                <th> &nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;
                                    To Location
                                    &nbsp;
                                </th>  
                                <td colspan ="1">
                                    <select id="loc2" name="loc2" class="form-control form" style='height:33px;' required>
                                         <option value="<?php echo ($addflag != 1) ? $getloca->code : ''; ?>"><?php echo ($addflag != 1) ? $getloca->name : ''; ?></option>
                                         <?php
                                           $sown = mysqli_query($conn, "SELECT code, `name` FROM `location` WHERE code != '' ORDER BY name") or die(mysqli_error($conn));
                                            while ($prow = mysqli_fetch_array($sown)) {
                                                echo "<option value=$prow[code]>$prow[name]</option>";
                                            }
                                            ?>
                                        </select>
                                </td>
                            </tr>    
                            <tr style="height:10px;">
                            </tr>
                        </table>
                        <br/>
                        <table id="data" border="1px" width="60%">
                            <tr>
                                <td width="10%" align="center"> <label class="control-label">Sr.</label></td>
                                <td width="60%" align="center"><label class="control-label">Item Name</label></td>
                                <td width="30%" align="center"><label class="control-label">Qty.</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)) {
                                    $getitem = mysqli_query($conn, "SELECT * FROM `item` WHERE code='$row[itemcode]'") or die(mysqli_error($conn));
                                    $gitem = mysqli_fetch_array($getitem);

                                    echo "<tr>";
                                    echo "<td align='left' valign='top'><input type='text' size='6' maxlength='6' name='srno_0' class='sno form-control form' style='height:33px;' value='$row[srno]'/></td>";

                                    echo "<td align='left'>";
                                    echo "<input list='item_$ctr' name='item_$ctr' class='item form-control form'  value='$gitem[name]' style='height:33px;'>";
                                    echo "<datalist id='item_$ctr'>";
                                    echo "<option value='$gitem->name'>";
                                    $mitem = mysqli_query($conn, "SELECT `name` FROM `item` ORDER BY `name`") or die(mysqli_error($conn));
                                    while ($trow1 = mysqli_fetch_array($mitem)) {
                                        echo "<option value='$trow1[name]'>";
                                    }
                                    echo "</datalist>";
                                    echo "</td>";
                                    
                                    echo "<td align='center' 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 "</tr>";
                                    $ctr++;
                                }
                                //browse($ctr);
                            } else {
                                ?>
                                <tr>
                                    <td align="left" valign="top"><input type="text" size="6" maxlength="6" maxlength="6" name="srno_0" class="sno form-control form" style="height:33px;" value="1"/></td>

                                    <td align="left">
                                        <input list="item_0" name="item_0"  class="item form-control form" style="height:33px;">
                                        <datalist id="item_0"> 
                                            <option value=""></option>
                                            <?php
                                            $mitem = mysqli_query($conn, "SELECT `name` FROM `item` ORDER BY `name`") or die(mysqli_error($conn));
                                            while ($trow1 = mysqli_fetch_array($mitem)) {
                                                echo "<option value='$trow1[name]'>";
                                            }
                                            ?>
                                        </datalist>
                                    </td>
                                    
                                    <td align="center" valign="top"><input type="text" size="4"  name="qty_0" class="qty form-control form"  style="text-align:right;height:33px;" value="0"></td>
                                </tr>
                            <?php } ?>
                        </table>
                    </div>  

                </div>
                <table id="" border='0' width='90%'>
                    <tr>
                        <td width="150px">
                            &nbsp;&nbsp;
                            <input type="button" style="align:left" id="addnew" class="btn btn-success btn-lg form" accode="addnew" value="+" />
                            <input type="hidden" id="items" name="items" value="<?php echo ($addflag != 1) ? $ctr : 1; ?>" />  
                        </td><td width="240px"></td><td width="140px"></td>

                    </tr>
                    <tr>
                        <td align="right" 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>
                    <tr>

                    </tr>
                </table>

                <!--SEARCH PART-->

                <div class="modal fade in slacker-modal" tabindex="-1" 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'>Bill No.</th>
                                                                <th align='left'>Bill Date</th>
                                                                <th align='left'>From Location</th>
                                                                <th align='left'>To Location</th>
                                                                <th align='left'>Action</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php
                                                            $result = mysqli_query($conn, "SELECT *, DATE_FORMAT(`vouchdt`, '%d-%m-%Y')as invdt FROM `$maindb`  ORDER BY $keyfld") or die(mysqli_error($conn));                                                            
                                                            while ($row = mysqli_fetch_array($result)) {
                                                                $getlocation1 = mysqli_query($conn, "SELECT `name` FROM `location` WHERE code='$row[loc1]'") or die(mysqli_error($conn));
                                                                $location1 = mysqli_fetch_object($getlocation1);
                                                                
                                                                $getlocation2 = mysqli_query($conn, "SELECT `name` FROM `location` WHERE code='$row[loc2]'") or die(mysqli_error($conn));
                                                                $location2 = mysqli_fetch_object($getlocation2);
                                                                echo "<tr>";
                                                                echo "<td align='left'>$row[vouchno]</td>";
                                                                echo "<td align='left'>$row[vouchdt]</td>";
                                                                echo "<td align='left'>$location1->name</td>";
                                                                echo "<td align='left'>$location2->name</td>";
                                                                echo "<td align='left'><a href=\"$file?mode=edit&$keyfld=$row[vouchno]\"><img src='images/edit.png'></a>&nbsp;&nbsp;&nbsp;&nbsp;
                                                                </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>        
    </div>        

</div>    

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

</form>
<?php
include("includes/files_footer.php");
?>
<script>
    $(function() {
        formGeneral();
        metisTable();
        metisSortable();
    });
</script>

</body>
</html>

