<?php
include("../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$description = '';
$poNumber = '';
$discount = 0;
$discount_price = 0;
$tax = 0;
$is_tax = 0;
$tax_price = 0;
$total_price = 0;
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

$current_date = date('d-m-Y');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
    <script>
        $(function () {
            $('#datepicker').pickadate({
                format: 'dd-mm-yyyy',
                selectMonths: true,
            });
        });
    </script>
</head>
<body>
<div id="container">
    <?php include('../includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Purchase</h3>
            </div>
            <hr>
            <br/>
            <?php
            if (isset($_GET['add']) || isset($_GET['edit'])) {
                if (isset($_GET['edit'])) {
                    extract($_REQUEST);
                    $getPurchase = Purchase::GetPurchaseSetupById($id);
                    $supplier_name = $getPurchase->supplier_id;
                    $date = date('d-m-Y', strtotime($getPurchase->create_date));
                    $purchaseNumber = $getPurchase->code;
                    $discount = $getPurchase->discount;
                    $description = $getPurchase->description;
                    $discount_price = $getPurchase->discount_price;
                    $tax = $getPurchase->tax;
                    $is_tax = $getPurchase->is_tax;
                    $tax_price = $getPurchase->tax_price;
                    $poNumber = $getPurchase->po_number;
                } else if (isset($_GET['add'])) {
                    if (PROJECT_TAX == 1) {
                        $tax = PROJECT_TAX_AMOUNT;
                        $is_tax = PROJECT_TAX;
                    }
                    $purchasefilter = " ORDER BY id DESC limit 1 ";
                    $purchases = Purchase::GetPurchaseList($purchasefilter);
                    if (!empty($purchases[0]->code)) {
                        $purchaseNumber = intval($purchases[0]->code);
                        $purchaseNumber = $purchaseNumber + 1;
                    } else {
                        $purchaseNumber = __PURCHASE__;
                    }
                }
            if (isset($_POST) && !empty($_POST)) {
                extract($_REQUEST);
                $data['supplier_id'] = $supplier_name;
                $data['sales_person_id'] = $sales_person_id;
                $data['total_amount'] = $total_price;
                $data['discount'] = $discount;
                $data['discount_price'] = $discount_price;
                $data['tax'] = $tax;
                $data['is_tax'] = $is_tax;
                $data['tax_price'] = $tax_price;
                $data['create_date'] = date('Y-m-d H:i:s', strtotime(date('H:i:s'), strtotime($purchase_date)));
                $data['code'] = $purchase_number;
                $data['datetime'] = 'NOW()';
                $data['description'] = $description;
                $data['po_number'] = $poNumber;

                $errors = array();
                // Validate the input

                if ((strlen($supplier_name) == 0) || (strlen($supplier_name) > 255))
                    array_push($errors, "Please enter supplier name");
                if ((strlen($purchase_date) == 0))
                    array_push($errors, "Please enter purchase date");
                if (($total_price <= 0))
                    array_push($errors, "Total amount of purchase is not less than or equal to 0");
                if (!isset($products) || (count($products) == 0))
                    array_push($errors, "Please select at least one product");

            if (count($errors) == 0) {
                if (isset($_GET['add'])) {
                    $purchasefilter = " ORDER BY id DESC limit 1 ";
                    $purchases = Purchase::GetPurchaseList($purchasefilter);
                    if (!empty($purchases[0]->code)) {
                        $purchaseNumber = intval($purchases[0]->code);
                        $purchaseNumber = $purchaseNumber + 1;
                    } else {
                        $purchaseNumber = __PURCHASE__;
                    }
                    $data['code'] = $purchaseNumber;
                    $data['status'] = 'Draft';
                    $q = Purchase::AddPurchase($data);
                    foreach ($products AS $prKey => $prRow) {
                        $dataProduct['purchase_id'] = $q;
                        $dataProduct['product_id'] = $prRow;
                        $dataProduct['product_qty'] = $qty[$prKey];
                        $dataProduct['unit_cost_price'] = $unitcost[$prKey];
                        $qp = Purchase::AddPurchaseProduct($dataProduct);

                        $productSetup = ProductSetup::GetProductSetupById($prRow);
                        $availability = 0;
                        $availability = $productSetup->availability;
                        $availability = ($availability + $qty[$prKey]);

                        $dataProductSetup['availability'] = $availability;
                        ProductSetup::UpdateProductSetup($prRow, $dataProductSetup);
                    }

                } elseif (isset($_GET['edit'])) {
                    $supplierAmount = Purchase::GetPurchaseSetupById($_GET['id']);
                    $q = Purchase::UpdatePurchaseSetup($_GET['id'], $data);

                    $purchaseId = $_GET["id"];
                    foreach ($products AS $prKey => $prRow) {
                        $filterPurchaseProduct = " WHERE purchase_id = '$purchaseId' AND product_id = '$prRow'";
                        $productSetups = Purchase::GetPurchaseProducts($filterPurchaseProduct);
                        $productActualQty[$prRow] = intval($productSetups[0]->product_qty);
                    }
                    Purchase::DeletePurchaseProducts($_GET['id']);
                    foreach ($products AS $prKey => $prRow) {
                        $availability = 0;
                        $dataProduct['purchase_id'] = $_GET['id'];
                        $dataProduct['product_id'] = $prRow;
                        $dataProduct['product_qty'] = $qty[$prKey];
                        $dataProduct['unit_cost_price'] = $unitcost[$prKey];
                        $qp = Purchase::AddPurchaseProduct($dataProduct);

                        $productSetup = ProductSetup::GetProductSetupById($prRow);
                        $availability = $productSetup->availability;

                        if ($productActualQty[$prRow] > $qty[$prKey]) {
                            $stockableProduct = $productActualQty[$prRow] - $qty[$prKey];
                            $availability = ($availability - $stockableProduct);
                        } else if ($productActualQty[$prRow] < $qty[$prKey]) {
                            $stockableProduct = $qty[$prKey] - $productActualQty[$prRow];
                            $availability = ($availability + $stockableProduct);
                        }

                        $dataProductSetup['availability'] = $availability;
                        ProductSetup::UpdateProductSetup($prRow, $dataProductSetup);
                    }
                }
            if ($qp) {
                $output = '';
                ?>
                <script>window.location.href = 'purchase.php?view&sucess'</script>
            <?php
            echo "<div id='card-alert' class='card green lighten-5'>
                      <div class='card-content green-text'>
                        <p>SUCCESS : <strong>Attention! </strong>Submitted!</p>
                      </div>
                      <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
            } else {
                $output = '';
                echo "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>Some error occurred!</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
            }
            } else {
                foreach ($errors as $val) {
                    $output .= "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>$val</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                }
            }
            }
            ?>
                <form action="" method="post" id="purchase_create_form" novalidate="novalidate">
                    <div class="row">
                        <div class="col s12 form-group">
                            <?php echo $output; ?>
                            <div class="row">
                                <div class="col m6 s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <?php
                                            $suppliersfilter = " WHERE status = 'active' ORDER BY name";
                                            $suppliers = SupplierSetup::GetSupplierSetupList($suppliersfilter);
                                            ?>
                                            <select class="form-control" required id="supplier_name"
                                                    name="supplier_name">
                                                <option></option>
                                                <?php
                                                foreach ($suppliers AS $suppliersRow) {
                                                    $selected = $suppliersRow->id == $supplier_name ? "selected" : "";
                                                    echo '<option ' . $selected . ' value="' . $suppliersRow->id . '" >' . $suppliersRow->name . '</option>';
                                                }
                                                ?>
                                            </select>
                                            <label for="supplier_name" class="control-label">Supplier *</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col m6 s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" required type="text" id="datepicker"
                                                   name="purchase_date"
                                                   placeholder="<?= date('01-01-Y') ?>"
                                                   value='<?= !empty($date) ? $date : $current_date; ?>'/><br/>
                                            <label for="purchase_date" class="control-label">Purchase Date *</label>
                                        </div>
                                    </div>
                                </div>

                            </div>
                            <div class="clearfix"></div>
                            <div class="row">
                                <div class="col m6 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="sales_person"
                                                   name="sales_person" readonly
                                                   value='<?php echo $_SESSION['sess_username']; ?>'/>
                                            <input class="form-control" type="hidden" id="sales_person_id"
                                                   name="sales_person_id"
                                                   value='<?php echo $_SESSION['sess_userid']; ?>'/><br/>
                                            <label for="sales_person" class="control-label">Sales Person *</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col m6 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="purchase_number"
                                                   name="purchase_number" readonly
                                                   value='<?php echo $purchaseNumber; ?>'/><br/>
                                            <label for="purchase_number" class="control-label">Purchase No. *</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                          
                          <div class="col m6 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="po_number"
                                                   name="po_number"
                                                   value='<?php echo $poNumber; ?>'/><br/>
                                            <label for="po_number" class="control-label">PO No. *</label>
                                        </div>
                                    </div>
                                </div>
                          
                            <div class="clearfix"></div>
                            <div class="row">
                                <div class="col m12 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="description"
                                                   name="description" maxlength="100"
                                                   value='<?php echo $description; ?>'/><br/>
                                            <label for="description" class="control-label">Description</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                          
                           
                            <div class="clearfix"><br><br></div>
                            <div class="row">
                                <table style="margin-top: 60px;"
                                       class="bordered responsive-table table dataTable">
                                    <thead>
                                    <th>S.No</th>
                                    <th>Action</th>
                                    <th>Product Name</th>
                                    <th>Carton</th>
                                    <th>Quantity</th>
                                    <th>Unit Of Measure</th>
                                    <th>Unit Cost Price</th>
                                    <th id="distributorHeader" style="display: none;">Unit Distributor
                                        Price
                                    </th>
                                    <th>Sub Total</th>
                                    </thead>
                                    <tbody id="addNewItem">
                                    <?php
                                    if (isset($_GET['edit'])) {
                                        $filterpurchaseproducts = " WHERE purchase_id = '$id'";
                                        $purchaseProducts = Purchase::GetPurchaseProducts($filterpurchaseproducts);
                                        $counting = 0;
                                        foreach ($purchaseProducts AS $purchaseProductsRow) {
                                            $qry = ProductSetup::GetProductSetupById($purchaseProductsRow->product_id);
                                            if ($qry) {
                                                $counting++;
                                                echo "<tr id='tr" . $qry->id . "'>";
                                                echo '<td>' . $counting . ' </td>';
                                                echo '<td style="width: 30px; height: 30px; font-size: 12px; line-height: 15px; margin-top: 11px;" class="mini-stat-icon orange darken-2">';
                                                echo '<i id="trashing' . $qry->id . '" style="cursor: pointer;font-size: 18px;margin-top: 7px;" class="mdi-action-delete"></i>';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $qry->name . '">';
                                                echo '<input type="hidden" name="products[]" id="product" value="' . $qry->id . '">';
                                                echo '</td>';
                                                echo '<td id="carton">';
                                                echo '<input ' . ($qry->carton_pieces == 0 ? 'disabled' : '') . ' value="' . ($purchaseProductsRow->carton_piece != 0 ? ($purchaseProductsRow->product_qty / $purchaseProductsRow->carton_piece) : 0) . '" style="width:100%!important;" required maxlength="10" onkeypress="return isNumberKey(event)" class="form-control" type="text" name="totcarton' . ($qry->carton_pieces == 0 ? '1' : '') . '[]" id="totcarton">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isNumberKey(event)" class="form-control" type="text" onchange="handleChange' . $qry->id . '(this);" value="' . $purchaseProductsRow->product_qty . '" name="qty[]" id="qty">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input value="' . $qry->carton_pieces . '" type="hidden" name="carton_piece[]" id="cartonval">';
                                                echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $qry->unit . '">';
                                                echo '<input type="hidden" name="units[]" id="unit" value="' . $qry->unit . '">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" readonly name="unitcost[]" value="' . $purchaseProductsRow->unit_cost_price . '" id="unitcost">';
                                                echo '</td>';
                                                echo '<td id="subTotal">';
                                                echo '';
                                                echo '</td>';
                                                echo "</tr>";
                                                ?>
                                                <script>
                                                    $('#trashing<?=$qry->id?>').on('click', function () {
                                                        $(this).parent('td').parent('tr').remove();
                                                        numbering();
                                                        Calculate();
                                                    });
                                                    function handleChange<?=$qry->id?>(input) {

                                                        var total = <?=($qry->availability+$purchaseProductsRow->product_qty)?>;
                                                        if (input.value < 0) input.value = 0;
                                                        if (input.value > total) {
                                                            input.value = total;
                                                            swal({
                                                                title: "Stock Availability",
                                                                text: "Stock not available, max quantity is " + total,
                                                                type: "error",
                                                                confirmButtonColor: '#DD6B55',
                                                                closeOnConfirm: false
                                                            });
                                                            Calculate();
                                                            return false;
                                                        }
                                                        ;
                                                    }
                                                    function handleCh<?=$qry->id?>(val) {
                                                        var total = <?=($qry->availability+$purchaseProductsRow->product_qty)?>;
                                                        if (val.val() < 0) val.val(0);
                                                        if (val.val() > total) {
                                                            val.val(total);
                                                            swal({
                                                                title: "Stock Availability",
                                                                text: "Stock not available, max quantity is " + total,
                                                                type: "error",
                                                                confirmButtonColor: '#DD6B55',
                                                                closeOnConfirm: false
                                                            });
                                                            return false;
                                                        }
                                                        ;
                                                    }
                                                </script>
                                                <?php
                                            }
                                        }
                                    }
                                    ?>
                                    </tbody>
                                    <tbody>
                                        <tr>
                                            <td id="show1" style="display: none;"></td>
                                            <td colspan="7" style="text-align: right;">Sub Total</td>
                                            <td id="subAmount">0</td>
                                        </tr>
                                        <tr>
                                            <td id="show2" style="display: none;"></td>
                                            <td colspan="7"
                                                style="text-align: right; vertical-align: middle;">
                                                Discount (%)
                                            </td>
                                            <td><input style="width:100%!important;" maxlength="10"
                                                       onkeypress="return isDoubleNumberKey(event)"
                                                       class="form-control" onchange="Calculate();" type="text"
                                                       id="discount" name="discount" value="<?= !empty($discount) ? $discount : 0; ?>"></td>
                                        </tr>
                                        <tr>
                                            <td id="show3" style="display: none;"></td>
                                            <td colspan="7" style="text-align: right;">Discounted Amount</td>
                                            <td id="discountAmount"><?= !empty($discount_price) ? number_format($discount_price, 2) : 0; ?></td>
                                        </tr>
                                        <tr>
                                            <td id="show4" style="display: none;"></td>
                                            <td colspan="7" style="text-align: right;">Total (After
                                                Discount)
                                            </td>
                                            <td id="totalAmount"><?= !empty($total_price) ? number_format($total_price, 2) : 0; ?></td>
                                        </tr>
                                        <tr>
                                            <td id="show5" style="display: none;"></td>
                                            <td colspan="7"
                                                style="text-align: right; vertical-align: middle;">
                                                Sales Tax (%)
                                            </td>
                                            <td><input style="width:100%!important;" maxlength="10"
                                                       onkeypress="return isDoubleNumberKey(event)"
                                                       class="form-control" onchange="Calculate();" type="text"
                                                       id="tax" name="tax" value="<?= !empty($tax) ? $tax : 0; ?>">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td id="show6" style="display: none;"></td>
                                            <td colspan="7" style="text-align: right;">Tax Amount</td>
                                            <td id="taxAmount"><?= !empty($tax_price) ? number_format($tax_price, 2) : 0; ?></td>
                                        </tr>
                                        <tr>
                                            <td id="show7" style="display: none;"></td>
                                            <td colspan="7" style="text-align: right;">Total Amount</td>
                                            <td id="grandTotal">0</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col s12">
                            <button type="submit" class="btn btn-default waves-effect waves-light right">Submit</button>
                        </div>
                    </div>
                </form>
            <?php
            }
            ?>
        </div>
    </div>
</div>
<?php include('../includes/inc_footer.php'); ?>
<script>
    function numbering() {
        var rows = $("#addNewItem").children("tr");
        for (var i = 0; i < rows.length; i++) {
            $(rows[i]).find('td:first').text(i + 1);
        }
    }

    function Calculate() {
        var subtotal = 0;
        var discountAmount = 0;
        var taxAmount = 0;
        var grandTotal = 0;
        $('#addNewItem tr').each(function (i, el) {
            var qty = $(el).find("#qty").val();
            var cost = $(el).find("#unitcost").val();
            if (qty && cost) {
                var subtotalval = qty * cost;
                subtotal += subtotalval;
                $(el).find("#subTotal").text(subtotalval.toFixed(2));
            }
        });

        $("#subAmount").text(subtotal.toFixed(2));
        var discount = $("#discount").val();
        if (discount > 0) {
            discountAmount = (subtotal * discount) / 100;
        }
        var discountedSubtotal = subtotal - discountAmount;
        $("#discountAmount").text(discountAmount.toFixed(2));
        $("#totalAmount").text(discountedSubtotal.toFixed(2));

        var tax = $("#tax").val();
        if (tax > 0) {
            taxAmount = (discountedSubtotal * tax) / 100;
        }
        $("#taxAmount").text(taxAmount.toFixed(2));
        grandTotal = discountedSubtotal + taxAmount;
        $("#grandTotal").text(grandTotal.toFixed(2));
    }

    numbering();
    Calculate();
</script>
</body>
</html>
