<?php
include("../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$description = '';
$tax = 0;
$is_tax = 0;
$tax_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>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Purchase Invoice</h3>
            </div>
            <hr>
            <?php if ($_SESSION['sess_role'] == 'VEC') {
                if (isset($_GET['view'])) { ?>
                    <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;" href="?add">Add <i
                            class="mdi-content-add-box"></i></a>
                    <div class="clearfix"></div>
                <?php }
            } ?>
            <br/>
            <?php
            if (isset($_GET['add']) || isset($_GET['edit'])) {
                if (isset($_GET['edit'])) {
                    extract($_REQUEST);
                    $getInvoice = PurchaseSetup::GetPurchaseSetupById($id);
                    $supplier_name = $getInvoice->supplier_id;
                    $date = date('d-m-Y', strtotime($getInvoice->create_date));
                    $invoiceNumber = $getInvoice->code;
                    $description = $getInvoice->description;

                    // Fetch the tax value from the ingredient setup
                    $ingredientId = $getInvoice->ingredient_id; // Assuming you have the ingredient ID available here
                    $getIngredient = IngSetup::GetIngSetupById($ingredientId);
                    $tax = $getIngredient->stax; // Get the tax from the ingredients table
                    $is_tax = $getInvoice->is_tax;
                    $tax_price = $getInvoice->tax_price;
                } else if (isset($_GET['add'])) {
                    // Assuming you have a way to get the default ingredient ID for a new invoice
                    $defaultIngredientId = 1; // Placeholder, replace with actual logic
                    $getIngredient = IngSetup::GetIngSetupById($defaultIngredientId);
                    $tax = $getIngredient->stax; // Get the default tax from the ingredients table
                    $is_tax = 1; // Assuming tax is applied by default, adjust according to your needs
                    
                    if ($_SESSION['clone'] == 1) {
                        $dateInvoice = date('Ymd', strtotime($current_date));
                        $purchasefilter = " WHERE code like '$dateInvoice%' ORDER BY id DESC limit 1 ";
                        $purchases = PurchaseSetup::GetPurchaseSetupList($purchasefilter);
                        if (!empty($purchases[0]->code)) {
                            $invoiceNumber = intval($purchases[0]->code);
                            $invoiceNumber = $invoiceNumber + 1;
                        } else {
                            $invoiceNumber = $dateInvoice . '001';
                        }
                    } else {
                        $invoicefilter = " ORDER BY id DESC limit 1 ";
                        $purchases = PurchaseSetup::GetPurchaseSetupList($invoicefilter);
                        if (!empty($purchases[0]->code)) {
                            $invoiceNumber = intval($purchases[0]->code);
                            $invoiceNumber = $invoiceNumber + 1;
                        } else {
                            $invoiceNumber = __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['qty'] = $total_qty;
                $data['total_ex_amount'] = $total_ex_price;
                $data['tax'] = $tax; // Use tax from ingredients table
                $data['is_tax'] = $is_tax;
                $data['tax_price'] = $total_saletax_price;
                $data['create_date'] = date('Y-m-d H:i:s', strtotime(date('H:i:s'), strtotime($invoice_date)));
                $data['datetime'] = 'NOW()';
                $data['description'] = $description;

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

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

            if (count($errors) == 0) {
                if (isset($_GET['add'])) {
                    if ($_SESSION['clone'] == 1) {
                        $dateInvoice = date('Ymd', strtotime($invoice_date));
                        $invoicefilter = " WHERE code like '$dateInvoice%' ORDER BY id DESC limit 1 ";
                        $invoices = PurchaseSetup::GetPurchaseSetupList($invoicefilter);
                        if (!empty($invoices[0]->code)) {
                            $invoiceNumber = intval($invoices[0]->code);
                            $invoiceNumber = $invoiceNumber + 1;
                        } else {
                            $invoiceNumber = $dateInvoice . '001';
                        }
                    } else {
                        $invoicefilter = " ORDER BY id DESC limit 1 ";
                        $invoices = PurchaseSetup::GetPurchaseSetupList($invoicefilter);
                        if (!empty($invoices[0]->code)) {
                            $invoiceNumber = intval($invoices[0]->code);
                            $invoiceNumber = $invoiceNumber + 1;
                        } else {
                            $invoiceNumber = __PURCHASE__;
                        }
                    }
                    $data['code'] = $invoiceNumber;
                    $data['status'] = 'Pending';
                    $q = PurchaseSetup::AddPurchaseSetup($data);

                    foreach ($item AS $prKey => $prRow) {
                        $dataProduct['purchase_id'] = $q;
                        $dataProduct['ing_id'] = $prRow;
                        $dataProduct['quant'] = $quant[$prKey];
                        $dataProduct['uom'] = $uom[$prKey];
                        $dataProduct['qty'] = $qty[$prKey];
                        $dataProduct['rate'] = $rate[$prKey];

                        // Fetch tax for each ingredient
                        $ingSetup = IngSetup::GetIngSetupById($prRow);
                        $tax = $ingSetup->stax;

                        $dataProduct['tax'] = $tax;
                        $taxAmount = ($rate[$prKey] * $tax) / 100; // Calculate tax amount
                        $dataProduct['tax_amount'] = $taxAmount;
                        $dataProduct['amount'] = $rate[$prKey] * $qty[$prKey] + $taxAmount;

                        $qp = PurchaseSetup::AddPurchaseItem($dataProduct);

                        // Update inventory
                        $availability = 0;
                        $availability = $ingSetup->availability + $qty[$prKey];
                        $newrate = ($rate[$prKey] + $ingSetup->avg_rate) / 2;

                        $dataProductSetup['avg_rate'] = $newrate;
                        $dataProductSetup['availability'] = $availability;
                        IngSetup::UpdateIngSetup($prRow, $dataProductSetup);
                    }

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

                    $purchaseId = $_GET["id"];
                    foreach ($item AS $prKey => $prRow) {
                        $filterPItem = " WHERE purchase_id = '$purchaseId' AND ing_id = '$prRow'";
                        $itemSetups = PurchaseSetup::GetPurchaseItems($filterPItem);
                        $itemActualQty[$prRow] = intval($itemSetups[0]->qty);
                    }

                    PurchaseSetup::DeletePurchaseItems($_GET['id']);

                    foreach ($item AS $prKey => $prRow) {
                        $dataProduct['purchase_id'] = $_GET['id'];
                        $dataProduct['ing_id'] = $prRow;
                        $dataProduct['quant'] = $quant[$prKey];
                        $dataProduct['uom'] = $uom[$prKey];
                        $dataProduct['qty'] = $qty[$prKey];
                        $dataProduct['rate'] = $rate[$prKey];

                        // Fetch tax for each ingredient
                        $ingSetup = IngSetup::GetIngSetupById($prRow);
                        $tax = $ingSetup->stax;

                        $dataProduct['tax'] = $tax;
                        $taxAmount = ($rate[$prKey] * $tax) / 100; // Calculate tax amount
                        $dataProduct['tax_amount'] = $taxAmount;
                        $dataProduct['amount'] = $rate[$prKey] * $qty[$prKey] + $taxAmount;

                        $qp = PurchaseSetup::AddPurchaseItem($dataProduct);

                        // Update inventory
                        $availability = 0;
                        $availability = $ingSetup->availability;

                        $newrate = ($rate[$prKey] + $ingSetup->avg_rate) / 2;

                        $dataProductSetup['avg_rate'] = $newrate;

                        if ($itemActualQty[$prRow] > $qty[$prKey]) {
                            $stockableProduct = $itemActualQty[$prRow] - $qty[$prKey];
                            $availability = ($stockableProduct + $availability);
                            $dataProductSetup['availability'] = $availability;
                            IngSetup::UpdateIngSetup($prRow, $dataProductSetup);
                        } else if ($itemActualQty[$prRow] < $qty[$prKey]) {
                            $stockableProduct = $qty[$prKey] - $itemActualQty[$prRow];
                            $availability = ($availability - $stockableProduct);
                            $dataProductSetup['availability'] = $availability;
                            IngSetup::UpdateIngSetup($prRow, $dataProductSetup);
                        }

                    }

                }
                //exit;
            if ($qp) {
                $output = ''; ?>
                <script>window.location.href = 'purchase_setup.php?view'</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 {
                //Prepare errors for output
                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
                                            $supplierfilter = " WHERE status = 'active' ORDER BY name";
                                            $suppliers = SupplierSetup::GetSupplierSetupList($supplierfilter);
                                            ?>
                                            <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="customer_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="invoice_date"
                                                   placeholder="<?= date('01-01-Y') ?>"
                                                   value='<?= !empty($date) ? $date : $current_date; ?>'/><br/>
                                            <label for="invoice_date" class="control-label">Invoice 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_invoice_number"
                                                   name="purchase_invoice_number" readonly
                                                   value='<?php echo $invoiceNumber; ?>'/><br/>
                                            <label for="invoice_number" class="control-label">Purchase Invoice No. *</label>
                                        </div>
                                    </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>Item Name</th>
                                    <th>Description</th>
                                    <th>Quantity</th>
                                    <th>Uom</th>
                                    <!--  <th>Rent</th> -->
                                    <th>Rate</th>
                                    <th>Price Ex. Tax</th>
                                    <th>S.Tax</th>
                                    <th>S.Tax Amount</th>
                                    <th>Total Inc. Tax</th>
                                    </thead>
                                    <tbody id="addNewItem">
                                    <?php
                                    if (isset($_GET['edit'])) {
                                        $filteritems = " WHERE purchase_id = '$id'";
                                        $invoiceProducts = PurchaseSetup::GetPurchaseItems($filteritems);
                                        $counting = 0;
                                        if(isset($invoiceProducts[0])){
                                            foreach ($invoiceProducts AS $invoiceProductsRow) {
                                                $qry = IngSetup::GetIngSetupById($invoiceProductsRow->ing_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="item[]" id="item" value="' . $qry->id . '">';
                                                    echo '</td>';
                                                    echo '<td>';
                                                    echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $qry->description . '">';
                                                    echo '</td>';
                                                    echo '<td>';
                                                    echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isNumberKey(event)" class="form-control" value="' . $invoiceProductsRow->quant . '" type="text" name="quant[]" id="quant">';
                                                    echo '<input type="hidden" name="qty[]" id="qty" value="' . $invoiceProductsRow->qty . '">';
                                                    echo '</td>';
                                                    echo '<td>';
                                                    echo '<input class="form-control" style="width:70%!important;" type="text" name="uom[]" value="' . $invoiceProductsRow->uom . '"> '.$qry->unit;
                                                    echo '</td>';
                                                  //  echo '<td>';
                                                   // echo '<input class="form-control" style="width:100%!important;" type="text" name="rent[]" value="' . $invoiceProductsRow->rent . '"> ';
                                                  //  echo '</td>';
                                                    echo '<td>';
                                                    echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" value="' . $invoiceProductsRow->rate . '" name="rate[]" id="rate">';
                                                    echo '</td>';
                                                    echo '<td id="subTotal">';
                                                    echo '';
                                                    echo '</td>';
                                                    echo '<td>';
                                                    echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" name="tax[]" value="'.$tax.'" id="tax">';
                                                    echo '</td>';
                                                    echo '<td>';
                                                    echo '<input class="form-control" style="width:100%!important;" name="tax_amount_price[]" value="'.$invoiceProductsRow->tax_amount.'" id="tax_amount_price" type="text" readonly>';
                                                    echo '<input type="hidden" name="tax_amount[]" value="'.$invoiceProductsRow->tax_amount.'" id="tax_amount">';
//        echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" name="tax_amount[]" value="" id="tax_amount">';
                                                    echo '</td>';
                                                    echo '<td id="totalamount">';
                                                    echo $invoiceProductsRow->amount;
                                                    echo '</td>';
                                                    echo '<input type="hidden" name="total_amount[]" value="'.$invoiceProductsRow->amount.'" id="total_amount">';
                                                    echo "</tr>";
                                                    ?>
                                                    <script>
                                                        $('#trashing<?=$qry->id?>').on('click', function () {
                                                            $(this).parent('td').parent('tr').remove();
                                                            numbering();
                                                            Calculate();
                                                        });
                                                    </script>
                                                    <?php
                                                }
                                            }
                                        }
                                    }
                                    ?>
                                    </tbody>
                                    <tbody>
                                    <tr>
                                        <td colspan="5" style="text-align: right;">Total</td>
                                        <td id="totalQty">0</td>
                                        <input type="hidden" name="total_qty" id="total_qty"/>
                                        <td></td>
                                        <td id="totalExAmount">0</td>
                                        <input type="hidden" name="total_ex_price" id="total_ex_price"/>
                                        <td></td>
                                        <td id="totalSTaxAmount">0</td>
                                        <input type="hidden" name="total_saletax_price" id="total_saletax_price"/>
                                        <td id="totalAmount">0</td>
                                        <input type="hidden" name="total_price" id="total_price"/>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                            <hr>
                            <div class="clearfix"></div>
                            <div class="row">
                                <div class="input-field col m3 col s12">
                                    <?php
                                    $filter = " where status = 'active' ORDER BY name";
                                    $qry = IngSetup::GetIngSetupList($filter, $pageno = "null", $pagesize = "null");
                                    if ($qry) {
                                        echo '<select id="ingItem" style="width: 100%!important;" class="form-control"><option></option>';
                                        foreach ($qry as $qery) {
                                            echo '<option value=' . $qery->id . '>' . $qery->name . ' - ' . $qery->description . '</option>';
                                        }
                                        echo '</select>';
                                        echo '<label for="ingItem">Items</label>';
                                    }
                                    ?>
                                </div>
                            </div>
                            <div class="row">
                                <div class="clearfix"></div>
                                <div class="col m12 col s12">
                                    <div class="btn-group">
                                        <button id="newItem" type="button" class="btn waves-effect waves-light">
                                            Add New <i class="fa fa-plus"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="clearfix"></div>
                    <button id="btnsubmit" type="submit" class="btn waves-effect waves-light">Submit</button>
                    <button type="button" class="btn waves-effect waves-light"
                            onclick="location.href='purchase_setup.php?view'">Cancel
                    </button>
                </form>
                <?php

            } // close view
            ?>
        </div>
    </div>
</div>
</div>
<?php include('includes/inc_footer.php'); ?>

<?php include('includes/inc_js.php'); ?>
<script type="application/javascript">
    function numbering() {
        var count = 0;
        $('#addNewItem tr td:first-child').each(function () {
            count++;
            $(this).html(count);
        });
    }

    $(document).ready(function () {
        var fewSeconds = 2;
        $('#btnsubmit').click(function () {
            // Ajax request
            var btn = $(this);
            btn.hide();
            setTimeout(function () {
                btn.show();
            }, fewSeconds * 1000);
        });

        Calculate();
    });

    $('#newItem').on('click', function () {
        $('#newItem').attr('disabled', true);
        var product = $('#ingItem').val();
        var fewSeconds = 2;
        if (!$('#tr' + product).html() && product != '') {
            $('body #container').block({message: 'Loading...'});
            $.get('addPurItem.php?id=' + $('#ingItem').val(), function (data) {
                $("#addNewItem").append(data);
                numbering();
                Calculate();
                $('body #container').unblock();
            });
            setTimeout(function () {
                $('body #container').unblock();
            }, fewSeconds * 500);
        }
        $('#newItem').attr('disabled', false);
    });

    $(document).on('keyup', "input[name='quant[]'], input[name='rate[]'], input[name='uom[]'], input[name='tax[]']", function () {
        Calculate();
    });

    function Calculate() {
        var ptotal = 0;
        var ttax = 0;
        var tqty = 0;
        var tsub = 0;

        $("input[name='quant[]']").each(function (index) {
            var quantity = parseFloat($(this).val()) || 0;
            var rate = parseFloat($("input[name='rate[]']").eq(index).val()) || 0;
            var uom = parseFloat($("input[name='uom[]']").eq(index).val()) || 0;
            var tax = parseFloat($("input[name='tax[]']").eq(index).val()) || 0;

            var totalQty = quantity * uom;
            $("input[name='qty[]']").eq(index).val(totalQty);

            var subtotal = totalQty * rate;
            $(this).closest('tr').find('#subTotal').text(subtotal.toFixed(2));

            var taxAmount = (subtotal * tax) / 100;
            $("input[name='tax_amount[]']").eq(index).val(taxAmount.toFixed(2));
            $("input[name='tax_amount_price[]']").eq(index).val(taxAmount.toFixed(2));

            var rowTotal = subtotal + taxAmount;
            $("input[name='total_amount[]']").eq(index).val(rowTotal.toFixed(2));
            $(this).closest('tr').find('#totalamount').text(rowTotal.toFixed(2));

            ptotal += rowTotal;
            ttax += taxAmount;
            tqty += totalQty;
            tsub += subtotal;
        });

        $('#totalQty').text(tqty.toFixed(2));
        $('#total_qty').val(tqty.toFixed(2));
        $('#totalExAmount').text(tsub.toFixed(2));
        $('#total_ex_price').val(tsub.toFixed(2));
        $('#totalSTaxAmount').text(ttax.toFixed(2));
        $('#total_saletax_price').val(ttax.toFixed(2));
        $('#totalAmount').text(ptotal.toFixed(2));
        $('#total_price').val(ptotal.toFixed(2));
    }

    function isDoubleNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    }

    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    }
</script>

</section>
</section>
</body>
</html>
