<?php
include("../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$description = '';
$purchase_invoice_no = '';
$tax = 0;
$is_tax = 0;
$tax_price = 0;
$delivery_challan_no = '';
$po_no = '';
$inv_type = '';
$validate_date = '';

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
$invoice_date = '';
$current_date = '';
$purchase_invoice_date = '';
$delivery_challan_date = '';
$po_no_date = '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
<script>
    $(function () {
        // Initialize date pickers for each date field
        $('#datepicker').pickadate({
            format: 'dd-mm-yyyy',
            selectMonths: true,
            selectYears: true,
        });

        $('#datepicker_invoice').pickadate({
            format: 'dd-mm-yyyy',
            selectMonths: true,
            selectYears: true,
        });

        $('#datepicker_delivery_challan').pickadate({
            format: 'dd-mm-yyyy',
            selectMonths: true,
            selectYears: true,
        });

        $('#datepicker_po_no').pickadate({
            format: 'dd-mm-yyyy',
            selectMonths: true,
            selectYears: 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;
                    $invoice_date = date('d-m-Y', strtotime($getInvoice->create_date));
                    $invoiceNumber = $getInvoice->code;
                    $description = $getInvoice->description;
                  $purchase_invoice_no = $getInvoice->purchase_invoice_no;
                  $delivery_challan_no = $getInvoice->delivery_challan_no;
                  $po_no = $getInvoice->po_no;
                  $inv_type = $getInvoice->inv_type;
                  
                  
                  $purchase_invoice_date = date('d-m-Y', strtotime($getInvoice->purchase_invoice_date));
                  $delivery_challan_date = date('d-m-Y', strtotime($getInvoice->delivery_challan_date));
                  $po_no_date = date('d-m-Y', strtotime($getInvoice->po_no_date));
                  
                  
                  
                    $tax = $getInvoice->tax;
                    $is_tax = $getInvoice->is_tax;
                    $tax_price = $getInvoice->tax_price;
                } else if (isset($_GET['add'])) {
                    if (PROJECT_TAX == 1) {
                        $tax = PROJECT_TAX_AMOUNT;
                        $is_tax = PROJECT_TAX;
                    }
                    if ($_SESSION['clone'] == 1) {
                        $dateInvoice = date('Ymd', strtotime($invoice_date));
                        $purchasefilter = " WHERE code like '$dateInvoice%' ORDER BY id DESC limit 1 ";
                        $purchases = PurchaseSetup::GetPurchaseSetupList1($purchasefilter);
                        if (!empty($purchases[0]->code)) {
                            $invoiceNumber = intval($purchases[0]->code);
                            $invoiceNumber = $invoiceNumber + 1;
                        } else {
                            $invoiceNumber = $dateInvoice . '001';
                        }
                    } else {
                      	$dateInvoice = date('Ymd', strtotime($invoice_date));
                        $invoicefilter = " WHERE code like '$dateInvoice%' ORDER BY id DESC limit 1 ";
                        $purchases = PurchaseSetup::GetPurchaseSetupList1($invoicefilter);
                        if (!empty($purchases[0]->code)) {
                            $invoiceNumber = intval($purchases[0]->code);
                            $invoiceNumber = $invoiceNumber + 1;
                        } else {
                            $invoiceNumber = $dateInvoice . '001';
                        }
                    }
                }
                
                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[0];
                    $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;
                  	$data['purchase_invoice_no'] = $purchase_invoice_no;
                  	$data['delivery_challan_no'] = $delivery_challan_no;
                  	$data['po_no'] = $po_no;
                  	$data['inv_type'] = $inv_type;
                  	$data['validate_date'] = '';
                  	$data['purchase_invoice_date'] = date('Y-m-d H:i:s', strtotime(date('H:i:s'), strtotime($purchase_invoice_date)));
            	    $data['delivery_challan_date'] = date('Y-m-d H:i:s', strtotime(date('H:i:s'), strtotime($delivery_challan_date)));
                  	$data['po_no_date'] = date('Y-m-d H:i:s', strtotime(date('H:i:s'), strtotime($po_no_date)));

                    $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));
                               $dateInvoice = date('Ymd', strtotime($invoice_date));
                                $invoicefilter = " WHERE code like '$dateInvoice%' ORDER BY id DESC limit 1 ";
                                $invoices = PurchaseSetup::GetPurchaseSetupList1($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 ";
                               $dateInvoice = date('Ymd', strtotime($invoice_date));
                              	$invoicefilter = " WHERE code like '$dateInvoice%' ORDER BY id DESC limit 1 ";
                                $invoices = PurchaseSetup::GetPurchaseSetupList1($invoicefilter);
                                if (!empty($invoices[0]->code)) {
                                    $invoiceNumber = intval($invoices[0]->code);
                                    $invoiceNumber = $invoiceNumber + 1;
                                } else {
                                    $invoiceNumber = $dateInvoice . '001';
                                }
                            }
                            $data['code'] = $invoiceNumber;
                            $data['status'] = 'Pending';
                          
                       
                            $q = PurchaseSetup::AddPurchaseSetup($data);

                            // Loop through each item and add it to the purchase items and ingredient_stock tables
                            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];
                                $dataProduct['tax'] = $tax[$prKey];
                                $dataProduct['tax_amount'] = $tax_amount[$prKey];
                                $dataProduct['amount'] = $total_amount[$prKey];
                                $qp = PurchaseSetup::AddPurchaseItem($dataProduct);

                                // Update ingredient availability and average rate in the ingredient setup table
                                $ingSetup = IngSetup::GetIngSetupById($prRow);
                                $availability = 0;
                                $availability = $ingSetup->availability;
                                $availability = ($availability + $qty[$prKey]);

                                $newrate = $rate[$prKey];
                                if ($ingSetup->avg_rate != 0) {
                                    $newrate = ($rate[$prKey] + $ingSetup->avg_rate) / 2;
                                }

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

                              	$taxPercentage = (float)$tax[$prKey] / 100; // Convert tax percentage to decimal
								$rateWithTax = (float)$rate[$prKey] * (1 + $taxPercentage); // Calculate price including tax

                                // Insert into ingredient_stock for FIFO management
                               $ingredientStockData = [
    'ingredient_id' => $prRow, // Ingredient ID
    'purchase_id' => $q, // Purchase ID
    'batch_date' => date('Y-m-d', strtotime($invoice_date)), // Batch or Purchase date
    'qty' => $qty[$prKey], // Quantity purchased
    'remaining_qty' => $qty[$prKey], // Initially, remaining quantity is the same as purchased
    'price' => (float)$rate[$prKey], // Purchase price per unit including tax
    'status' => 'Available', // Set status as available for FIFO usage
    'datetime' => date('Y-m-d H:i:s'), // Current date and time
    'total_qty' => $qty[$prKey], // Set total_qty to the same as qty initially
    'reserved_qty' => 0, // Initially, nothing is reserved
    'available_qty' => $qty[$prKey], // Initially, available quantity is the same as qty
    'last_updated' => date('Y-m-d H:i:s') // Timestamp for when this record was created/updated
];
                                 $isNotNull = !empty($ingredientStockData) ? 'not null' : 'null';

                              // Display the result in an alert
                             // echo "<script>alert('The ingredientStockData is {$isNotNull}.');</script>";
                              
                                IngredientStock::AddIngredientStock($ingredientStockData); // Ensure this function exists in the IngredientStock class
                            }

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

    $purchaseId = $_GET["id"];

    // Retrieve the existing items for the purchase
    foreach ($item AS $prKey => $prRow) {
        $filterPItem = " WHERE purchase_id = '$purchaseId' AND ing_id = '$prRow'";
        $itemSetups = PurchaseSetup::GetPurchaseItems($filterPItem);
        $itemActualQty[$prRow] = intval($itemSetups[0]->qty); // Store the original quantity
    }

    // Delete existing purchase items
    PurchaseSetup::DeletePurchaseItems($_GET['id']);

    // Re-insert or update the purchase items and ingredient stock
    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];
        $dataProduct['tax'] = $tax[$prKey];
        $dataProduct['tax_amount'] = $tax_amount[$prKey];
        $dataProduct['amount'] = $total_amount[$prKey];
        $qp = PurchaseSetup::AddPurchaseItem($dataProduct);

        // Update ingredient availability and average rate
        $ingSetup = IngSetup::GetIngSetupById($prRow);
        $availability = $ingSetup->availability;

        $newrate = $rate[$prKey];
        if ($ingSetup->avg_rate != 0) {
            $newrate = ($rate[$prKey] + $ingSetup->avg_rate) / 2;
        }

        $dataProductSetup['avg_rate'] = $newrate;

        // Adjust availability based on the difference in quantity
        if ($itemActualQty[$prRow] > $qty[$prKey]) {
            $stockableProduct = $itemActualQty[$prRow] - $qty[$prKey];
            $availability += $stockableProduct;
        } else if ($itemActualQty[$prRow] < $qty[$prKey]) {
            $stockableProduct = $qty[$prKey] - $itemActualQty[$prRow];
            $availability -= $stockableProduct;
        }

        $dataProductSetup['availability'] = $availability;
        IngSetup::UpdateIngSetup($prRow, $dataProductSetup);
             // Retrieve the stock_id from ingredient_stock table
        $stock = IngredientStock::GetStockByIngredientId($prRow, $_GET['id']);
            if (!$stock) {
                echo "<script>alert('Failed to retrieve ingredient stock ID!');</script>";
                continue; // Skip updating if the stock ID is not found
            }
      $stock_id = $stock->id;
        // Insert or update ingredient stock for FIFO management
        $taxPercentage = (float)$tax[$prKey] / 100; // Convert tax percentage to decimal
        $rateWithTax = (float)$rate[$prKey] * (1 + $taxPercentage); // Calculate price including tax

        $ingredientStockData = [
            'ingredient_id' => $prRow,
            'purchase_id' => $_GET['id'],
            'batch_date' => date('Y-m-d', strtotime($invoice_date)),
            'qty' => $qty[$prKey],
            'remaining_qty' => $qty[$prKey],
            'price' => (float)$rate[$prKey], // Price including tax
            'status' => 'Available',
            'datetime' => date('Y-m-d H:i:s'),
            'total_qty' => $qty[$prKey], // Set total_qty to the same as qty initially
            'reserved_qty' => 0, // Initially, nothing is reserved
            'available_qty' => $qty[$prKey], // Initially, available quantity is the same as qty
            'last_updated' => date('Y-m-d H:i:s') // Timestamp for when this record was created/updated
        ];

        // Add or update ingredient stock
       $result = IngredientStock::UpdateIngredientStockById( $stock_id, $ingredientStockData);
        if (!$result) {
            echo "<script>alert('Failed to add or update ingredient stock!');</script>";
        }
    }
                        }

                        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 m3 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">Reference No *</label>
                                        </div>
                                    </div>
                                </div>
                     
                              
                                <div class="col m3 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($invoice_date) && $invoice_date != '01-01-1970' && $invoice_date != '00-00-0000' ? $invoice_date : ''; ?>'/><br/>
                                            <label for="invoice_date" class="control-label">Receiving Date *</label>
                                        </div>
                                    </div>
                                </div>
                        
                  
                  				<div class="col m3 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="po_no"
                                                   name="po_no" maxlength="100"
                                                   value='<?php echo $po_no; ?>'/><br/>
                                            <label for="po_no" class="control-label">Purchase Order No</label>
                                        </div>
                                    </div>
                                </div>
                             <div class="col m3 s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" required type="text" id="datepicker_po_no"
                                                   name="po_no_date"
                                                   placeholder="<?= date('01-01-Y') ?>"
                                                   value='<?= !empty($po_no_date) && $po_no_date != '01-01-1970' && $po_no_date != '00-00-0000' ? $po_no_date : ''; ?>'/><br/>
                                            <label for="po_no_date" class="control-label">Purchase Order Date</label>
                                        </div>
                                    </div>
                                </div>
                       </div>
                          
                          
                          
                            <div class="clearfix"></div>
                            <div class="row">
                                <div class=" ">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="sales_person"
                                                   name="sales_person" 
                                                   value='<?php echo $_SESSION['sess_username']; ?>'
                                                   style="display:none;"/> <!-- Hide this field -->

                                            <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" style="display:none;">Sales Person *</label> <!-- Hide label too -->
                                        </div>
                                    </div>
                                </div>
                                   
                            </div>
                            <div class="clearfix"></div>
                            <div class="row">
                              <div class="col s12 form-group">
                            <?php echo $output; ?>
                            <div class="row">
                                <div class="col m3 s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <?php
                                            $supplierfilter = " WHERE status = 'active'";
                                            $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>
                              
                              
                              <!-- Delivery Challan infor area -->
                              <div class="col m3 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="delivery_challan_no"
                                                   name="delivery_challan_no" maxlength="100"
                                                   value='<?php echo $delivery_challan_no; ?>'/><br/>
                                            <label for="delivery_challan_no" class="control-label">Delivery Challan No</label>
                                        </div>
                                    </div>
                                </div>
                              <div class="col m3 s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" required type="text" id="datepicker_delivery_challan"
                                                   name="delivery_challan_date"
                                                   placeholder="<?= date('01-01-Y') ?>"
                                                   value='<?= !empty($delivery_challan_date) && $delivery_challan_date != '01-01-1970' && $delivery_challan_date != '00-00-0000' ? $delivery_challan_date : ''; ?>'/><br/>
                                            <label for="delivery_challan_date" class="control-label">Delivery Challan Date</label>
                                        </div>
                                    </div>
                                </div>
                              
                              
                             
                               <div class="col m3 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>
                          
                          
                          
                          
                          <!-- To add Delivery Challan information -->
                          
                            <div class="clearfix"></div>
                            <div class="row">
                              
                              
                               <div class="col m4 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="purchase_invoice_no"
                                                   name="purchase_invoice_no" maxlength="100"
                                                   value='<?php echo $purchase_invoice_no; ?>'/><br/>
                                            <label for="purchase_invoice_no" class="control-label">Purchase Invoice No</label>
                                        </div>
                                    </div>
                                </div>
                              <div class="col m4 s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" required type="text" id="datepicker_invoice"
                                                   name="purchase_invoice_date"
                                                   placeholder="<?= date('01-01-Y') ?>"
                                                   value='<?= !empty($purchase_invoice_date) && $purchase_invoice_date != '01-01-1970' && $purchase_invoice_date != '00-00-0000' ? $purchase_invoice_date : ''; ?>'/><br/>
                                            <label for="purchase_invoice_date" class="control-label">Purchase Invoice Date</label>
                                        </div>
                                    </div>
                                </div>
                             
                              <div class="col m4 col s12">
                                <div class="row margin">
                                    <div class="input-field col s12">
                                        <select id="inv_type" name="inv_type">
                                            <option value="" disabled>Select an option</option>
                                          	<option value="GP" <?php echo ($inv_type == 'GP') ? 'selected' : ''; ?>>GP</option>
                                            <option value="IP" <?php echo ($inv_type == 'IP') ? 'selected' : ''; ?>>IP</option>
                                            
                                        </select>
                                        <label for="inv_type" class="control-label">Type</label>
                                    </div>
                                </div>
                            </div>

                            </div>
                          <!-- End of To add Delivery Challan information -->
                          
                            <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 isDoubleNumberKey(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 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="'.$invoiceProductsRow->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 '</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;
            rowTotal = Math.round(rowTotal); // Rounds off to the nearest integer
            $("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>
