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

$formname = 'Offline Entry';
$maindb = 'ordoff';
$trandb = 'ordofftran';

$stkdb = 'transacn';

$printfile = "offline_print.php";
$file = 'offline_ent.php';
$trandbexist = 1;
$keyfld = "vouchno";
$source = 'OFSL';

$keycond = "";

$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
$myyear = $_SESSION[$myyear];
mysqli_select_db($conn, $zdb);
include("includes/vouchno_generate.php");
include("includes/prev&next.php");

if (isset($_POST["submit"])) {
    $a = 1;
    $vouchno = $_POST["vouchno"];
    $vouchdt = $_POST["vouchdt"];
    $party = $_POST["party"];
    $sltype = $_POST["sltype"];
    $add1 = $_POST["add1"];
    $add2 = $_POST["add2"];
    $address = $add1 . "  " . $add2;
    $contact = $_POST["contact"];
    $email = $_POST["email"];
    $pincode = $_POST["pincode"];
    $total = $_POST["total"];
    $pickrflag = $_POST["pickr"];
    $rem1 = $_POST["remark"];
    $rem2 = $_POST["remark2"];
    $flag = $sltype;

//    Company Details
    $compdtl = mysqli_query($conn, "SELECT * FROM `company`") or die(mysqli_error($conn));
    $cdtl = mysqli_fetch_array($compdtl);
    $compname = $cdtl['pname'];
    $fmobile = $cdtl['mobile'];
    $femail = $cdtl['email'];
    $fpin = $cdtl['pin'];
    $faddress = $cdtl['add1'] . " " . $cdtl['add2'] . " " . $cdtl['add3'];


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

    $codamount = $total;
    if ($sltype == 'OF') {
        $paymode = "COD";
    } else {
        $paymode = "OTH";
        $codamount = 0;
    }

    if ($a == 1) {

#################################TRAN PART #################################
//
        mysqli_query($conn, "DELETE FROM `$trandb` WHERE `$keyfld`='$mvouch'") or die(mysqli_error($conn));
        mysqli_query($conn, "DELETE FROM `$stkdb` WHERE `$keyfld`='$mvouch' and `source`='$source'") or die(mysqli_error($conn));
//
//        $srl = 0;
        for ($i = 0; $i < $count; $i++) {
            $srno = $_POST["srno_$i"];
            $item = $_POST["item_$i"];
            $trsize = $_POST["size_$i"];
            $trqty = $_POST["trqty_$i"];
            $trrate = $_POST["trrate_$i"];
            $tramount = $_POST["tramount_$i"];

            if (!empty($item)) {
                $srl++;

                $getprod = mysqli_query($conn, "SELECT `name` FROM `product` WHERE `code`='$item'") or die(mysqli_error($conn));
                $fprod = mysqli_fetch_array($getprod);

                $prodname .= $fprod['name'];
                $prodname1 = $fprod['name'];

                $totqty = $totqty + $trqty;
                mysqli_query($conn, "INSERT INTO `$trandb`(`srl`, `vouchno`, `code`, `qty`, `size`, `mrp`, `total`, `email`, `prodname`)
                                        VALUES( '$srl', '$qvouch', '$item', '$trqty', '$trsize', '$trrate', '$tramount','$email', '$prodname1')") or die(mysqli_error($conn));

                ##########STOCK PART########
                mysqli_query($conn, "INSERT INTO `$stkdb`(`srno`, `vouchno`, `vouchdt`, `itemcode`, `source`, `qty`, `size`, `flag`)
                                        VALUES( '$srl', '$qvouch', '$vouchdt', '$item', '$source','$trqty' * -1, '$trsize', '$flag')") or die(mysqli_error($conn));
            }
        }
#################################TRAN PART END #################################
############################## MAIN ######################################################
        if ($addflag == 1) {

            if ($flag != 'D') {
                if ($pickrflag == 1) {
//                $pickrtestid = "36af5c05fa1317700ad50ccb3921a8c65544";

                    $pickrid = "4ca0976d532557eabeb33e52738e13d159990";

                    function createShipment($params) {
                        try {
                            $json_params = json_encode($params);
                            $url = 'http://www.pickrr.com/api/place-order/';
                            //open connection
                            $ch = curl_init();
                            //set the url, number of POST vars, POST data
                            curl_setopt($ch, CURLOPT_URL, $url);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $json_params);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            //execute post
                            $result = curl_exec($ch);
                            $result = json_decode($result, true);
                            //close connection
                            curl_close($ch);
                            if (gettype($result) != "array")
                                throw new \Exception(print_r($result, true) . "Problem in connecting with Pickrr");
                            if ($result['err'] != "")
                                throw new \Exception($result['err']);
                            return $result;
                        } catch (\Exception $e) {
                            echo $e;
                        }
                    }

                    $params = array(
                        'auth_token' => $pickrid,
                        'item_name' => $prodname,
                        'from_name' => $compname,
                        'from_phone_number' => $fmobile,
                        'from_address' => $faddress,
                        'from_pincode' => $fpin,
                        'pickup_gstin' => 'XXXXXXXXXX',
                        'to_name' => $party,
                        'to_phone_number' => $contact,
                        'to_pincode' => $pincode,
                        'to_address' => $address,
                        'quantity' => $totqty,
                        'invoice_value' => $total,
                        'cod_amount' => $codamount
//                'client_order_id' => 'WAYNE007',
//                'item_breadth' => 10,
//                'item_length' => 10,
//                'item_height' => 5,
//                'item_weight' => 5,
//                'is_reverse' => False
                    );

                    $pickrr_result = createShipment($params);
                    if (is_array($pickrr_result)) {
                        $pikrord_id = $pickrr_result['order_id'];
                        $pikrtrck_id = $pickrr_result['tracking_id'];
                    }
                }
            } else {
                $pikrord_id = "";
                $pikrtrck_id = "";
            }

            mysqli_query($conn, "INSERT INTO `$maindb`(`vouchno`, `orderdt`, `username`, `email`, `contact`, `add1`,`add2`, `total`,
                                                       `paymode`, `pikrord_id`, `pikrtrck_id`, `flag`, `pincode`, `pickrflag`, `rem1`, `rem2`)
                                     VALUES ($qvouch, '$vouchdt', '$party','$email', '$contact', '$add1', '$add2', '$total', '$paymode',
                                             '$pikrord_id', '$pikrtrck_id', '$flag', '$pincode', '$pickrflag', '$rem1', '$rem2')") or die(mysqli_error($conn));

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

            mysqli_query($conn, "UPDATE `$maindb` SET `vouchno`='$mvouch',`orderdt`='$vouchdt', `username`='$party', `email`='$email',
                                 `contact`='$contact', `add1` = '$add1',`add2` = '$add2', `total` = '$total', `paymode` = '$paymode',
                                 `flag`='$flag', `rem1` = '$rem1', `rem2` = '$rem2' WHERE `vouchno`= '$mvouch' ") or die(mysqli_error($conn));
            updmess();
            header("refresh: 1; $file?$keyfld=$mvouch&mode=edit");
        }
    }
}

if ($addflag != 1) {

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

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

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


if (isset($_GET["delete"])) {
    delete($zdb, "$maindb", "$keyfld", $_GET[$keyfld], "$file?mode=last", $conn);
    delete($zdb, "$trandb", "$keyfld", $_GET[$keyfld], "$file?mode=last", $conn);
    $delcond = " `source`='$source'  and `vouchno`='$_GET[vouchno]' ";
    delnew($zdb, "$stkdb", "$delcond", "$file?mode=last", $conn);
}
include("../includes/linkshead.php");
?>
<script src="MyScript/offline_ent.js" type="text/javascript"></script>
<!--<script type="text/javascript">
    $(document).ready(function () {
        $('#addnew').click(function () {
            alert(1);
        });
    });
</script>-->

</head>
<body>
    <!--    <div id="preloader" class="col-lg-12 text-center">
            <h3 class="text-center">Loading</h3>
            <div id="status">&nbsp;</div>
        </div>-->
    <form action='' method='POST' enctype="multipart/form-data">
        <!-- Default box -->
        <div>
            <div class="col-lg-8 col-md-6 col-sm-6 col-xs-6  pad">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title" style="color:inherit"><?php Echo $formname; ?></h3>
                        <div class="actions pull-right">
                            <i class="fa fa-chevron-down"></i>
                            <i class="fa fa-times"></i>
                        </div>
                    </div>
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-lg-2 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg vouchabd">Voucher</label>
                            </div>
                            <div class="col-lg-2 col-md-2 col-sm-8 col-xs-8 pad">
                                <input type="text" class="form-control text-size form" name="vouchno" value="<?php Echo ($addflag != 1) ? $get["vouchno"] : " $qvouch"; ?>" required readonly>
                            </div>
                            <div class="col-lg-4 col-md-2 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Date</label>
                            </div>
                            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 pad">
                                <input type="date" class="form-control form"  name="vouchdt" value="<?php Echo ($addflag != 1) ? $get["orderdt"] : date('Y-m-d'); ?>">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-2 col-md-4 col-sm-4 col-xs-4 numeric pad">
                                <label class="label-control marg" style="color: #B9408F">Party Name</label>
                            </div>
                            <div class="col-lg-4 col-md-6 col-sm-6 col-xs-6 pad">
                                <input type="text" class="form-control form party" name="party" value="<?php Echo ($addflag != 1) ? $get["username"] : ""; ?>" required>
                            </div>
                            <div class="col-lg-2 col-md-4 col-sm-4 col-xs-4 numeric pad">
                                <label class="label-control marg">Sale Type</label>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-3 col-xs-3 pad">
                                <select class="form-control form" name="sltype" style='width:100%' required>
                                    <?php
                                    if ($addflag != 1) {
                                        if ($get['flag'] == 'OF') {
                                            $saletype = "Sale";
                                        } elseif ($get['flag'] == 'G') {
                                            $saletype = "Giveaway";
                                        } else {
                                            $saletype = "Damage";
                                        }
                                    }
                                    ?>
                                    <option value="<?php echo ($addflag != 1) ? $get['flag'] : ""; ?>"><? echo ($addflag != 1) ? $saletype : ""; ?></option>
                                    <option value="OF">Sale</option>
                                    <option value="G">Give Away</option>
                                    <option value="D">Damage</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-2 col-md-4 col-sm-4 col-xs-4 numeric pad">
                                <label class="label-control marg">Address</label>
                            </div>
                            <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 pad">
                                <input type="text" class="form-control form add1" name="add1" value="<?php Echo ($addflag != 1) ? $get["add1"] : ""; ?>" required>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-2 col-md-4 col-sm-4 col-xs-4 numeric pad">
                            </div>
                            <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 pad">
                                <input type="text" class="form-control form add2" name="add2" value="<?php Echo ($addflag != 1) ? $get["add2"] : ""; ?>" required>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-2 col-md-4 col-sm-4 col-xs-4 numeric pad">
                                <label class="label-control marg">Pin Code</label>
                            </div>
                            <div class="col-lg-2 col-md-6 col-sm-6 col-xs-6 pad">
                                <input type="number" class="form-control form pin" name="pincode" value="<?php Echo ($addflag != 1) ? $get["pincode"] : ""; ?>" required>
                            </div>
                            <!--</div>-->
                            <!--<div class="row">-->
                            <div class="col-lg-1 col-md-4 col-sm-4 col-xs-4 numeric pad">
                                <label class="label-control marg">Contact</label>
                            </div>
                            <div class="col-lg-3 col-md-6 col-sm-6 col-xs-6 pad">
                                <input type="number" class="form-control form contact" name="contact" value="<?php Echo ($addflag != 1) ? $get["contact"] : ""; ?>" required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-lg-2 col-md-4 col-sm-4 col-xs-4 numeric pad">
                                <label class="label-control marg">Email Id</label>
                            </div>
                            <div class="col-lg-3 col-md-6 col-sm-6 col-xs-6 pad">
                                <input type="email" class="form-control form email" name="email" value="<?php Echo ($addflag != 1) ? $get["email"] : ""; ?>" required>
                            </div>
                            <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1 text-right pad">
                                <label class="label-control marg" style="color: #B9408F">Pickrr</label>
                            </div>
                            <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1 pad text-right checkbox">
                                <input type="checkbox" class="form" name="pickr" value="1" style="height: 18px; margin-left: -40px; width: 25%; margin-top: 0px;" <?php
                                if ($get['pickrflag'] == 1) {
                                    echo "checked";
                                }
                                ?>>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <table class="table table-striped table-condensed table-bordered table-padd" width="100%">
                                <thead  style="background-color: #B9408F">
                                    <tr>
                                        <th width="5%"></th>
                                        <th width="5%" class='text-right'>Sr.</th>
                                        <th width="30%">Itemname</th>
                                        <th width="10%">Size</th>
                                        <th width="15%" class='text-right'>Qty.</th>
                                        <th width="15%" class='text-right'>Rate</th>
                                        <th width="20%" class='text-right'>Amount</th>
                                    </tr>
                                </thead>
                                <tbody class="tbody">
                                    <?php
                                    if ($addflag != 1) {
                                        $ctr = 0;
                                        $tqty = 0;
                                        $tamt = 0;
                                        $gettran = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE `vouchno`='$get[vouchno]' ORDER BY `srl`")or die(mysqli_error($conn));
                                        while ($tran = mysqli_fetch_array($gettran)) {

                                            $getitem1 = mysqli_query($conn, "SELECT * FROM `product` WHERE `code`='$tran[code]' ")or die(mysqli_error($conn));
                                            $fitem = mysqli_fetch_array($getitem1);

                                            $getsize1 = mysqli_query($conn, "SELECT * FROM `size` WHERE `code`='$tran[size]' ")or die(mysqli_error($conn));
                                            $fsize = mysqli_fetch_array($getsize1);

                                            Echo "<tr>";
                                            Echo "<td><i class='fa fa-close remove' style='display:none;'></i></td>";
                                            Echo "<td><input type='text' class='form-control form text-right srno'  name='srno_$ctr'        value='$tran[srl]'></td>";

                                            Echo "<td>";
                                            Echo "<select class='form-control form select2 item' name='item_$ctr' style='width:100%'>";
                                            Echo "<option value='$fitem[code]'>$fitem[name]</option>";
                                            $gitem = mysqli_query($conn, 'SELECT * FROM `product` order by name')or die(mysqli_error($conn));
                                            while ($item = mysqli_fetch_array($gitem)) {
                                                Echo "<option value='$item[code]'>$item[name]</option>";
                                            }
                                            Echo "</select>";
                                            Echo "</td>";
//---
                                            Echo "<td>";
                                            Echo "<select class='form-control form select2 size' name='size_$ctr' style='width:100%'>";
                                            Echo "<option value='$fsize[code]'>$fsize[name]</option>";
//                                            $getsize = mysql_query("SELECT * FROM `size` ORDER BY name")or die(mysql_error());
//                                            while ($size = mysql_fetch_array($getsize)) {
//                                                Echo "<option value='$size[code]'>$size[name]</option>";
//                                            }
                                            Echo "</select>";
                                            Echo "</td>";
//---                                            
                                            Echo "<td><input type='text' class='form-control form text-right trqty'  name='trqty_$ctr'       value='$tran[qty]'>  </td>";
                                            Echo "<td><input type='number' class='form-control form text-right trrate'  name='trrate_$ctr'       value='$tran[mrp]'>  </td>";
                                            Echo "<td><input type='number' class='form-control form text-right tramount'  name='tramount_$ctr'       value='$tran[total]'>  </td>";
                                            Echo "</tr >";
                                            $ctr++;
                                        }
                                    } else {
                                        $pctr = 0;
//                                        $yctr = 1;
                                        ?>
                                        <tr>
                                            <td><i class="fa fa-close remove"></i></td> 
                                            <td><input type="text" class="form-control form text-right srno"      name="srno_<?= $pctr ?>"        value="1"></td> 
                                            <td>
                                                <select name="item_<?= $pctr ?>" class="form-control form select2 item">
                                                    <option value=""></option>
                                                    <?
                                                    $getitem = mysqli_query($conn, "SELECT * FROM `product` ORDER BY name")or die(mysqli_error($conn));
                                                    while ($item1 = mysqli_fetch_array($getitem)) {
                                                        Echo "<option value='$item1[code]'>$item1[name]</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </td>
                                            <td>
                                                <select name="size_<?= $pctr ?>" class="form-control form select2 size">
                                                    <option value=""></option>
                                                </select>
                                            </td>
                                            <td><input type="text" class="form-control form text-right trqty"     name="trqty_<?= $pctr ?>"       value=""></td> 
                                            <td><input type="number" class="form-control form text-right trrate"     name="trrate_<?= $pctr ?>"       value=""></td> 
                                            <td><input type="number" class="form-control form text-right tramount"     name="tramount_<?= $pctr ?>"       value=""></td> 
                                        </tr>  
                                        <?php
                                    }
                                    $pctr++;
                                    ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="row">
                            <div class="col-lg-1" >
                                <button type="button" class="btn btn-square form addgen" style="background-color: #B9408F"  id="addnew">
                                    <i class="fa fa-plus" style="color:#ffffff" data-toggle='tooltip' title='Add Row' ></i>    
                                </button>
                                <input type="hidden" id="items" name="items" value="<?php echo ($addflag != 1) ? $ctr : $pctr; ?>" />  
                            </div> 
                        </div> 

                        <div class="row">
                            <div class="col-lg-10 col-md-9 col-sm-9 col-xs-9 text-right pad">
                                <label class="label-control marg">Total</label>
                            </div>
                            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 pad">
                                <input type="text" class="form-control form text-right totamt" name="total" value="<?php Echo ($addflag != 1) ? $get["total"] : ""; ?>" readonly>
                            </div>
                        </div>
                        <hr>
                        <div class="row">
                            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 text-right pad">
                                <label class="label-control text-size marg">Remark</label>
                            </div>
                            <div class="col-lg-6 col-md-6 col-sm-8 col-xs-8 pad">
                                <input type="text" class="form-control form " name="remark" value="<?php Echo ($addflag != 1) ? $get["rem1"] : ""; ?>" >
                                <input type="text" class="form-control form " name="remark2" value="<?php Echo ($addflag != 1) ? $get["rem2"] : ""; ?>" >
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-7 col-md-7 col-sm-7 col-xs-7 pad">
        </div>
        <div class="col-lg-8 col-md-6 col-sm-6 col-xs-6 pad">
            <div class="panel panel-default">
                <div class="panel-body">
                    <?php include("../includes/buttons.php"); ?>
                </div>
            </div>
        </div>
    </div>
</form>
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button class="close" data-dismiss="modal"><span>&times;</span></button>
                <h4 class="modal-title" id="myLargeModalLabel">Search <? Echo $formname; ?></h4>
            </div>
            <div class="modal-body">
                <div class=" table-responsive">
                    <table id="example1" class="table table-striped">
                        <thead>
                            <tr class="mySearchTr" style="background-color: #0098DA;">
                                <th>Voucher</th>
                                <th>Date</th>
                                <th>Party Name</th>
                                <th>Address</th>
                                <th>Pin Code</th>
                                <th>Contact</th>
                                <th>Email Id</th>
                                <th>Total</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            if ($addflag != 1) {
                                $srchresult = mysqli_query($conn, "SELECT * FROM `$maindb`")or die(mysql_error($conn));
                                while ($row = mysqli_fetch_array($srchresult)) {
                                    echo "<tr class='clickable-row' data-href='$file?mode=edit&$keyfld=$row[$keyfld]'>";
                                    echo "<td align='left'>$row[vouchno]</td>";
                                    echo "<td align='left'>$row[orderdt]</td>";
                                    echo "<td align='left'>$row[username]</td>";
                                    echo "<td align='left'>$row[add1] $row[add2]</td>";
                                    echo "<td align='left'>$row[pincode]</td>";
                                    echo "<td align='left'>$row[contact]</td>";
                                    echo "<td align='left'>$row[email]</td>";
                                    echo "<td align='left'>$row[total]</td>";
                                    echo "<td align='left'><a href=\"$file?mode=edit&$keyfld=$row[$keyfld]\"><i class='fa fa-pencil' style='font-size:1.3em;color:#00C0EF;cursor:pointer;'></i></a></td>";
                                    echo "</tr>";
                                }
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer"></div>
        </div>
    </div>
</div>
<?php include("../includes/linksfoot.php"); ?>
</body>
</html>
