vb_book/app/Views/invoice_form.php
2025-02-25 09:40:51 +05:30

2689 lines
145 KiB
PHP
Executable File

<style>
.selection .select2-selection__arrow{
background-color: #37cde6 !important;
height: 36px !important;
border-radius: 2px !important;
}
.select2-container .select2-selection--single .select2-selection__arrow b{
border-color: white transparent transparent transparent !important;
}
.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b
{
border-color: transparent transparent white transparent !important;
}
tbody td.last-column { border: none !important; }
.table thead th.last-column, .table tbody td.last-column {
border: none !important;
background-color: #fff !important;
}
.select2-selection.select2-selection--single{
margin-right: 2px;
}
.fixed-width-select {
width: 100px; /* Adjust width as needed */
}
table .select2-container {
width: 400px !important;
}
.custom-icon {
background-color: #37cde6;
color: white;
border-radius: 50%;
padding: 10px;
display: inline-block;
text-align: center;
}
.table thead th.last-column, .table tbody td.last-column {
border-right: none;
}
.last-column {
border: none;
position: relative;
}
.last-column .icon {
position: absolute;
top: 50%;
transform: translateY(-50%);
justify-content: center;
align-items: center;
color: red; /* Change to the desired color */
}
.btn-white {
border-color: #37cde6;
}
.item-discount-type{
background-color: #FAFAFA;
}
.form-control[readonly] {
background-color: white;
}
/* .select2-container--default .select2-selection--single .select2-selection__arrow b
{ border-style: none; } */
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* For Firefox */
input[type=number] {
-moz-appearance: textfield;
}
/* Hide the calendar icon in Chrome, Safari, and Edge */
/* input[type="date"]::-webkit-calendar-picker-indicator {
display: none;
} */
/* Hide the calendar icon in Firefox */
/* input[type="date"] {
-moz-appearance: textfield;
} */
.modal {
position: fixed;
top: 0; /* Adjust this value to move it further down */
left: 50%;
transform: translateX(-50%);
z-index: 1050; /* Ensure it appears above other content */
}
#invoiceDate~.parsley-errors-list{
position: absolute;
top:35px;
}
#customerName~.parsley-errors-list{
position: absolute;
color: red;
font-size: 12px;
top: 100%; /* Below the input field */
left: 0;
}
#loadShippingDropdown~.parsley-errors-list{
position: absolute;
color: red;
font-size: 12px;
top: 100%; /* Below the input field */
left: 0;
}
#fromsubcription~.parsley-errors-list{
position: absolute;
top:35px;
}
#tosubcription~.parsley-errors-list{
position: absolute;
top:35px;
}
/* .book-select~.parsley-errors-list{
position: absolute;
top:35px;
} */
</style>
<?php $flag_name = $invoice_type === '1' ? " Books" : " Scheme";
$formattedinvdate = date('d/m/Y');
if (isset($invoice_details['invoice_date']) && !empty($invoice_details['invoice_date'])) {
$date = DateTime::createFromFormat('Y-m-d', $invoice_details['invoice_date']);
if ($date !== false) {
$formattedinvdate = $date->format('d/m/Y');
}
}
$formattedfromsubdate = '';
if (isset($invoice_item_details[0]['from_subscription']) && !empty($invoice_item_details[0]['from_subscription'])) {
$date = DateTime::createFromFormat('Y-m-d', $invoice_item_details[0]['from_subscription']);
if ($date !== false) {
$formattedfromsubdate = $date->format('d/m/Y');
}
}
$formattedtosubdate = '';
if (isset($invoice_item_details[0]['to_subscription']) && !empty($invoice_item_details[0]['to_subscription'])) {
$date = DateTime::createFromFormat('Y-m-d', $invoice_item_details[0]['to_subscription']);
if ($date !== false) {
$formattedtosubdate = $date->format('d/m/Y');
}
}
?>
<div class="row">
<div class="col-lg-12">
<h4 class="header-title"><center><?= $page_name; ?></center></h4>
<?php if (session()->getFlashdata('success') || session()->getFlashdata('error')) : ?>
<?php if (session()->getFlashdata('success')) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= session('success') ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<?php endif; ?>
<?php if (session()->getFlashdata('error')) : ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session('error') ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<?php endif; ?>
<?php endif; ?>
<div class="card">
<div class="card-body">
<br>
<form class="parsley-examples" method="POST" enctype="multipart/form-data" action="<?= base_url() . "save_invoice"; ?>" id="myForm">
<!-- class="parsley-examples" -->
<div class="form-group">
<div id = 'name_div' class="form-row">
<div class="form-group col-md-5">
<?php
$first_name ="";
$last_name ="";
if (isset($invoice_details['customer_id']) && $invoice_details['customer_id'] != "") {
$displayvalue = "";
foreach ($customers as $customer) {
if ($customer->customer_id === $invoice_details['customer_id']) {
$displayvalue = $customer->first_name . ' ' . $customer->last_name;
$last_name = $customer->last_name;
$first_name = $customer->first_name;
}
} ?>
<label for="customerName">Customer Name</label>
<input type="hidden" name="customer_name" id="customer_name" value="<?= $invoice_details['customer_id']; ?>" />
<input type="text" class="form-control" value="<?= $displayvalue ?>" readonly />
<?php } else { ?>
<label for="customerName">Customer Name<span class="text-danger"> *</span></label>
<select class="form-control" id="customerName" name="customer_name" required data-toggle="select2" onchange="get_customer_billing_details(this.value); get_customer_membership_details(this.value)" >
<option value="">Select a customer</option>
<?php if ($invoice_type === '1') { // invoice means Add new costomers;
?>
<option class="blueText" value="0"> + Add a customer</option>
<?php } ?>
<?php foreach ($customers as $customer) :
if ($customer->first_name != '' && $customer->first_name != null){
if ((int)$customer->isactive == 1) {?>
<option value="<?= $customer->customer_id ?>"> <?= $customer->first_name . ' ' . $customer->last_name; ?>
</option>
<?php } }
endforeach; ?>
</select>
<?php } ?>
<input type="hidden" class="form-control" id="hidden_last_name" value="<?= $last_name ?>" readonly />
<input type="hidden" class="form-control" id="hidden_first_name" value="<?= $first_name ?>" readonly />
<div class="subscribedetails" style="display: none">
<!-- <div id="schemeName"></div> -->
</div>
</div>
<div class="form-group col-md-5">
<label for="loadShippingDropdown">Shipping Address<span class="text-danger"> *</span></label>
<select class="form-control" id="loadShippingDropdown" name="shipping_address_id" data-toggle="select2" onchange="get_customer_shipping_details(this.value)" <?= $invoice_type == 2?'required':'' ?>>
<option value="">Select an address</option>
</select>
</div>
</div>
<div id = 'address_div' class="form-row" style="margin-top: 19px;">
<div class="form-group col-md-5">
<label for="storeBillingAddress"> Billing Address &ensp;( <input type="checkbox" id="editAddressesCheckbox" /> Do you want to change addresses?)</label>
<input type="hidden" id="hiddenBillingAddressId" name="billing_address_id" placeholder="hidden for billing address id" value="<?= isset($invoice_details['billing_address_id']) ? $invoice_details['billing_address_id'] : '' ?>" />
<textarea class="form-control" id="storeBillingAddress" name="billing_address" rows="2" readonly><?= isset($invoice_details['billing_address']) ? $invoice_details['billing_address'] : '' ?></textarea>
</div>
<div class="form-group col-md-5">
<label for="storeShippingAddress">Shipping Address</label>
<textarea class="form-control" id="storeShippingAddress" name="shipping_address" rows="2" readonly><?= isset($invoice_details['shipping_address']) ? $invoice_details['shipping_address'] : '' ?></textarea>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-5">
<label for="event" class="col-form-label">Events</label>
<select class="form-control" id="event" name="event_id" data-toggle="select2">
<option value="">Select an Events</option>
<?php foreach ($events as $event) : ?>
<!-- <option value="<?= $event->event_id ?>"><?= $event->event_name ?></option> -->
<option value="<?= $event->event_id ?>" <?php if ((int)$event->is_the_default === 1 || isset($invoice_details['event_id']) && (($invoice_details['event_id'] === $event->event_id))) echo "selected"; ?>>
<?= $event->event_name ?></option>
<?php endforeach; ?>
</select>
</div>
<div id = 'membership_id_div' class="form-group col-md-5">
<label for="event" class="col-form-label">Select Membership ID to Renew</label>
<select class="form-control" id="membership_id" name="membership_id">
<option value="">No Existing Membership ID</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="invoiceNumber">Invoice Number</label>
<input type="text" class="form-control" id="invoiceNumber" name="invoice_number" value="<?= isset($invoice_details['invoice_number']) ? $invoice_details['invoice_number'] : '' ?>">
<input type="hidden" id="hiddenNextId" name="next_id" placeholder="hidden for next id" />
</div>
<div class="form-group col-md-4">
<label for="invoiceDate">Invoice Date<span class="text-danger"> *</span></label>
<div class="input-group">
<input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/mm/yyyy" data-date-autoclose="true" id="invoiceDate" name="invoice_date" value="<?= $formattedinvdate; ?>" data-date-end-date="<?= date('d/m/Y'); ?>" required>
<div class="input-group-append" style="margin-left: -11px;">
<span class="input-group-text" style="background-color: #37cde6;color:#fff;">
<i class="ri-calendar-event-fill" style="position: relative;left: 4px;"></i>
</span>
</div>
</div><!-- input-group -->
</div>
<?php if ($invoice_type === '2') : ?>
<div class="form-group col-md-4">
<label for="fromsubcription">From Subscription<span class="text-danger"> *</span></label>
<!-- <input type="date" class="form-control" id="fromsubcription" name="from_subscription" value="<?= $formattedfromsubdate; ?>" required onchange="updateToDateMinDate(this.value)"> -->
<div class="input-group">
<input type="text" data-provide="datepicker" data-date-format="dd/mm/yyyy" data-date-autoclose="true" class="form-control" id="fromsubcription" name="from_subscription" value="<?= $formattedfromsubdate; ?>" required onchange="updateToDateMinDate(this.value)">
<div class="input-group-append" style="margin-left: -11px;">
<span class="input-group-text" style="background-color: #37cde6;color:#fff;">
<i class="ri-calendar-event-fill" style="position: relative;left: 4px;"></i>
</span>
</div>
</div><!-- input-group -->
</div>
<div class="form-group col-md-4">
<label for="tosubcription">To Subscription<span class="text-danger"> *</span></label>
<!-- <input type="date" class="form-control" id="tosubcription" name="to_subscription" value="<?= $formattedtosubdate; ?>" required> -->
<div class="input-group">
<input type="text" class="form-control" id="tosubcription" name="to_subscription" value="<?= $formattedtosubdate; ?>" data-provide="datepicker" data-date-format="dd/mm/yyyy" data-date-autoclose="true" required>
<div class="input-group-append" style="margin-left: -11px;">
<span class="input-group-text" style="background-color: #37cde6;color:#fff;">
<i class="ri-calendar-event-fill" style="position: relative;left: 4px;"></i>
</span>
</div>
</div><!-- input-group -->
</div>
<?php endif; ?>
</div>
<div class="col-md-12 mt-1" style="overflow: auto;">
<h4>Item Details</h4>
<br />
<table class="table table-bordered" id="itemTable" style="border: white!important;">
<thead class="thead-light">
<tr>
<th>ITEM DETAILS</th>
<th class="text-right">QUANTITY</th>
<th class="text-right">RATE</th>
<th style="display:none;">TAX</th>
<th class="text-right">DISCOUNT</th>
<th class="text-right">AMOUNT</th>
<?php if ($invoice_type === '1') : ?> <th class="last-column"></th><?php endif; ?>
</tr>
</thead>
<tbody>
<!-- Dynamically add rows for item details -->
<?php if (!empty($invoice_item_details)) {
foreach ($invoice_item_details as $inx => $ii_details) : ?>
<tr>
<td style="width:17% !important;">
<select class="form-control book-select fixed-width-select" id="<?= "book" . $inx; ?>bookSelect" name="item_details[]" onchange="displayBookTag(this,<?= $inx; ?>)" required data-toggle="select2" style="width: 249px !important;">
<option value="">Select a <?= $flag_name; ?></option>
<?php if ($invoice_type === '1') { ?>
<option value="add_new_book">+ Add New Book</option>
<?php }
foreach ($books as $book) : ?>
<?php $disabled = ((int)$book->isactive == 0) ? 'disabled' : ''; ?>
<option value="<?= $book->book_id ?>" <?php if (isset($ii_details['product']) && ($ii_details['product'] === $book->book_id)) echo "selected"; ?> <?= $disabled; ?>>
<?php if ((int)$book->isactive == 0) {
echo $book->title . " (Disabled) ";
} else {
echo $book->title;
} ?></option>
<?php endforeach; ?>
</select>
<!-- <textarea name="description[]" class="form-control" placeholder="Enter Description" id="<?= "description" . $inx; ?>" cols="26" rows="2" style="margin-top: 16px;border-color: lightgray;width:247px;"><?= isset($ii_details['description']) ? $ii_details['description'] : '' ?></textarea> -->
<span>&ensp;</span>
<textarea name="description[]" class="form-control" placeholder="Enter Description" id="<?="description".$inx;?>" rows="2" style="border: 1px dashed #ddd"><?= isset($ii_details['description']) ? $ii_details['description'] : '' ?></textarea>
<input type="hidden" class="form-control" id="<?= "hiddenInvoiceChildId" . $inx; ?>" name="invoice_child_id[]" placeholder="hidden for invoice child/item id" value="<?= isset($ii_details['invoice_child_id']) ? $ii_details['invoice_child_id'] : '' ?>" />
</td>
<td style="width:8%;"><input type="number" class="form-control item-quantity" id="<?="quantity".$inx;?>" name="quantity[]" oninput="calculateInvoice(this,<?= $inx; ?>)" value="<?= isset($ii_details['quantity']) ? $ii_details['quantity'] : '' ?>" min="1" />
</td>
<td style="width:20%;"><input type="text" class="form-control item-rate" id="<?="rate".$inx;?>" name="rate[]" oninput="calculateInvoice(this,<?= $inx; ?>)" value="<?= isset($ii_details['unit_price']) ? $ii_details['unit_price'] : '' ?>" /> <!-- readonly /> -->
</td>
<td style="display:none;"><input type="number" class="form-control item-tax" id="<?="tax".$inx;?>" name="tax[]" value="<?= isset($ii_details['tax']) ? $ii_details['tax'] : '' ?>" readonly />
</td>
<td style="width:22%;">
<div class="input-group">
<input type="number" style="width: 41%;" class="form-control item-discount-amount item-discount-group" id="<?="item_discount_amount".$inx;?>" name="discount_amount[]" oninput="calculateInvoice(this,<?= $inx; ?>)" value="<?= isset($ii_details['discount_amount']) ? $ii_details['discount_amount'] : '' ?>" min="0" step="0.001" />
<select class="item-discount-type custom-select item-discount-group" id="<?="discount_type".$inx;?>" name="discount_type[]" oninput="calculateInvoice(this,<?= $inx; ?>)">
<option value="%" <?php if (isset($ii_details['discount_type']) && $ii_details['discount_type'] === '%') echo "selected"; ?>>
%</option>
<option value="₹" <?php if (isset($ii_details['discount_type']) && $ii_details['discount_type'] === '₹') echo "selected"; ?>>
₹</option>
</select>
</div>
</td>
<td style="width:15%;"><input type="number" class="form-control item-amount" id="<?="amount".$inx;?>" name="amount[]" value="<?= isset($ii_details['subtotal']) ? $ii_details['subtotal'] : '' ?>" readonly />
</td>
<?php if ($invoice_type === '1') : ?>
<td class="last-column" style="width:5%">
<span class="icon"><center><i class="fa fa-trash remove-item "></i></center></span>
</td>
<?php endif; ?>
</tr>
<?php endforeach;
} else { ?>
<tr>
<td style="width:17% !important;">
<select class="form-control book-select fixed-width-select" id="book0" name="item_details[]" onchange="displayBookTag(this,0)" required data-toggle="select2" style="width: 249px !important;">
<option value="">Select a <?= $flag_name ?></option>
<?php if ($invoice_type === '1') { ?>
<option value="add_new_book">+ Add New Book</option>
<?php }
foreach ($books as $book) :
if ((int)$book->isactive === 1) : ?>
<option value="<?= $book->book_id ?>"><?= $book->title; ?></option>
<?php endif;
endforeach; ?>
</select>
<!-- <textarea name="description[]" class="form-control" placeholder="Enter Description" id="" cols="26" rows="2" style="margin-top: 16px;border-color: lightgray;width:247px;"></textarea> -->
<span>&ensp;</span>
<textarea name="description[]" class="form-control" placeholder="Enter Description" id="description0" rows="2" style="border: 1px dashed #ddd"></textarea>
<input type="hidden" class="form-control" id="hiddenInvoiceChildId0" name="invoice_child_id[]" placeholder="hidden for invoice child/item id" />
</td>
<td style="width:8%;"><input type="number" class="form-control item-quantity" id="quantity0" name="quantity[]" oninput="calculateInvoice(this,0)" min="1" />
</td>
<td style="width:20%;"><input type="text" class="form-control item-rate" id="rate0" name="rate[]" oninput="calculateInvoice(this,0)" /></td>
<td style="display:none"><input type="text" class="form-control item-tax" id="tax0" name="tax[]" /></td>
<td style="width:22%;">
<div class="input-group">
<input type="number" style="width: 41%;" class="form-control item-discount-amount item-discount-group" id="item_discount_amount0" name="discount_amount[]" oninput="calculateInvoice(this,0)" min="0" step="0.001" />
<select class="item-discount-type custom-select item-discount-group" id="<?= "discount_type0"; ?>" name="discount_type[]" oninput="calculateInvoice(this,0)">
<option value="%">%</option>
<option value="₹">₹</option>
</select>
</div>
</td>
<td style="width:15%;"><input type="text" class="form-control item-amount" id="amount0" name="amount[]" />
</td>
<?php if ($invoice_type === '1') : ?>
<td class="last-column" style="width:5%">
<span class="icon"><center><i class="fa fa-trash remove-item "></i></center></span>
</td>
<?php endif; ?>
</tr>
<?php } ?>
<!-- You can add more rows as needed using JavaScript -->
</tbody>
</table>
<div class="form-group m-b-0">
<?php if ($invoice_type !== '2') : ?>
<!-- Show the "Add More Item" button only if invoice_type is not 1 -->
<!-- <a class="btn" id="addItem">
<h4><i class="fa fa-plus" aria-hidden="true"></i> Add More Item</h4>
</a> -->
<button type="button" id="addItem" class="btn btn-light waves-effect"><i class="fa fa-plus custom-icon" aria-hidden="true"></i>&ensp; Add More Item</button>
<?php endif; ?>
</div>
</div>
<div class="offset-md-5 col-md-7">
<h4><center>Calculation</center></h4>
<div class="card" style="background-color: #FAFAFA;">
<div class="card-body">
<div class="form-row">
<div class="form-group col-md-6">
<label for="subtotal">Subtotal</label>
<input type="number" class="form-control" id="subtotal" name="sub_total" readonly value="<?= isset($invoice_details['subtotal']) ? (float)$invoice_details['subtotal'] : 0 ?>" min="0" step="0.001">
</div>
<div class="form-group" style="display: none;">
<label for="invoicetax">Tax Amount</label>
<input type="hidden" class="form-control" id="invoicetax" name="invoice_tax" readonly value="<?= isset($invoice_details['tax']) ? (float)$invoice_details['tax'] : 0 ?>" min="0" step="0.001">
</div>
<div class="form-group col-md-6">
<label for="discount">Discount</label>
<div class="input-group">
<input type="number" style="width: 60%;" class="form-control" id="discount" name="discount" value="<?= isset($invoice_details['discount']) ? $invoice_details['discount'] : 0 ?>" onchange="discountTypeKeyup(this)" value="0" min="0" step="0.001">
<?php
$disType = isset($invoice_details['dis_type']) ? $invoice_details['dis_type'] : '';
if (strlen($disType) > 0) {
echo '<select class="custom-select" id="discount-type" name="dis_type">';
// Length is greater than 0, proceed with displaying the select element without the name attribute
} else {
// Length is 0 or $invoice_details['dis_type'] is not set, proceed with displaying the select element with the name attribute
echo '<select style="display: none;" class="custom-select" id="discount-type">';
}
?>
<option value="%" <?php if (isset($invoice_details['dis_type']) && $invoice_details['dis_type'] === '%') echo "selected"; ?>>%</option>
<option value="₹" <?php if (isset($invoice_details['dis_type']) && $invoice_details['dis_type'] === '₹') echo "selected"; ?>>₹</option>
</select>
</div>
</div>
</div>
<?php
// Check if it's a subscription invoice
$isSubscriptionInvoice = ($page_name === 'Add Subscription Invoice Details' || $page_name === 'Edit Subscription Invoice Details');
// Conditionally set the "hidden" attribute for the fields
$shippingChargesHidden = $isSubscriptionInvoice ? 'hidden' : '';
$shippingChargesStyle = $isSubscriptionInvoice ? 'display: none;' : '';
?>
<div class="form-row" <?= $shippingChargesHidden ?> >
<div class="form-group col-md-6">
<span style="<?= $shippingChargesStyle ?>">
<label for="shippingChargesLabel">Charge Name </label>
<input type="text" class="form-control" id="shippingChargesLabel" name="shippingChargesLabel" placeholder="Shipping Charges Label" value="<?= isset($invoice_details['shipping_label']) ? $invoice_details['shipping_label'] : 'Shipping Charge' ?>" <?= $shippingChargesHidden ?>>
</span>
</div>
<div class="form-group col-md-6">
<span style="<?= $shippingChargesStyle ?>">
<label for="shippingCharges">Charge Amount </label>
<input type="number" class="form-control" id="shippingCharges" name="shippingCharges" placeholder="Charges Amount" value="<?= isset($invoice_details['shipping_charge']) ? $invoice_details['shipping_charge'] : 0 ?>" oninput="if(this.value) calculateOverallTotals()" <?= $shippingChargesHidden ?> step="0.001" >
</span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="exacttotal">Total</label>
<input type="number" class="form-control" id="exacttotal" name="exact_total_amount" value="<?= isset($invoice_details['total_amount']) ? (float)$invoice_details['exact_total_amount'] : 0 ?>" readonly min="0" step="0.001">
</div>
<div class="form-group col-md-6">
<label for="grandtotal">Total (Round-off)</label>
<input type="number" class="form-control" id="grandtotal" name="grand_total" readonly value="<?= isset($invoice_details['total_amount']) ? (int)round($invoice_details['total_amount']) : 0 ?>">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="balanceAmount">Balance Amount</label>
<input type="number" class="form-control" id="balanceAmount" name="balanceAmount" value="<?= (isset($invoice_details['status']) && $invoice_details['status'] === 'Draft') ? (isset($invoice_details['total_amount']) ? (int)round($invoice_details['total_amount']) : '') : '0' ?>" oninput="calculateOverallTotals()" readonly min="0" step="0.001">
</div>
<div class="form-group col-md-6">
<label for="paidAmount">Paid Amount</label>
<input type="number" class="form-control" id="paidAmount" name="paidAmount" value="<?= (isset($invoice_details['status']) && $invoice_details['status'] === 'Approved') ? (isset($invoice_details['total_amount']) ? (int)round($invoice_details['total_amount']) : '') : '0' ?>" oninput="calculateOverallTotals()" readonly min="0" step="0.001">
</div>
</div>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-5">
<label for="payment_note">Payment Notes</label>
<textarea class="form-control" id="payment_note" name="payment_note" rows="3"><?= isset($invoice_details['payment_note']) ? $invoice_details['payment_note'] : '' ?></textarea>
</div>
<!-- </div>
<div class="form-row"> -->
<div class="form-group col-md-5">
<label for="notes">Notes</label>
<textarea class="form-control" id="notes" name="notes" rows="3"><?= isset($invoice_details['notes']) ? $invoice_details['notes'] : '' ?></textarea>
</div>
</div>
</div>
<!-- Payment Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1" role="dialog" aria-labelledby="paymentModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="paymentModalLabel">Select Mode of Payment</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<!-- Add your mode of payment options here -->
<select class="form-control" id="paymentMode" name="payment_method">
<option value="">Select a mode</option>
<option value="credit">Credit Card</option>
<option value="debit">Debit Card</option>
<option value="cash">Cash</option>
<option value="upi">UPI</option>
<option value="banktransfer">Bank Transfer</option>
<!-- Add more options as needed -->
</select><br>
<label>Contact Method:</label><br>
<div class="form-check form-check-inline">
<input checked type="checkbox" class="form-check-input" id="email" name="contact_method_mail" value="Email">
<label class="form-check-label" for="email">Email</label>
</div>
<div class="form-check form-check-inline">
<input checked type="checkbox" class="form-check-input" id="whatsapp" name="contact_method_whatsapp" value="WhatsApp">
<label class="form-check-label" for="whatsapp">WhatsApp</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="saveas" value="Approved" id="saveapproved">Save as Approved</button>
</div>
</div>
</div>
</div>
<input type="hidden" id="status" name="status" value="<?= isset($invoice_details['status']) ? $invoice_details['status'] : 'Draft' ?>">
<input type="hidden" id="hiddenInvoiceId" name="invoice_id" placeholder="hidden for invoice id" value="<?= isset($invoice_details['invoice_id']) ? $invoice_details['invoice_id'] : '' ?>" />
<input type="hidden" id="invoice_type" name="invoice_type" value="<?php echo ($page_name === 'Add Subscription Invoice Details' || $page_name === 'Edit Subscription Invoice Details') ? '2' : '1'; ?>">
<div class="form-group m-b-0">
<button type="submit" class="btn btn-white waves-effect waves-light" name="saveas" value="Draft" id="saveDraftButton">Save as Draft</button>
<button type="button" class="btn btn-primary waves-effect" name="saveas" value="Approved" id="saveApprovedButton">Save as Approved</button>
<button type="button" class="btn btn-white waves-effect waves-light" name="save" value="Save" id="saveButton">Save</button>
<button type="button" class="btn btn-white waves-effect waves-light" name="void" value="Void" id="voidButton">Void</button>
<button type="button" class="btn btn-white waves-effect" name="cancel" value="Cancel" id="cancelButton">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Reason for Void Modal -->
<div class="modal fade" id="voidReasonModal" tabindex="-1" role="dialog" aria-labelledby="voidReasonModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="voidReasonModalLabel">Reason for Void</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<textarea class="form-control" id="voidReason" rows="3" placeholder="Enter reason for voiding..." required></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="submitVoidReason">Submit</button>
</div>
</div>
</div>
</div>
<!-- </div>
</div> -->
<!-- Reason for Cancel Modal -->
<div class="modal fade" id="cancelReasonModal" tabindex="-1" role="dialog" aria-labelledby="voidReasonModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="cancelReasonModalLabel">Reason for Cancel</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<textarea class="form-control" id="cancelReason" rows="3" placeholder="Enter reason for cancel..."></textarea>
<!-- <input type="hidden" id="invoiceId" name="invoiceId"> -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="submitCancelReason">Submit</button>
</div>
</div>
</div>
</div>
<!-- Add Customer Modal -->
<!-- Customer Quick Add Modal -->
<div class="modal fade" id="customerModal" tabindex="-1" role="dialog" aria-labelledby="paymentModalLabel" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<!-- Add Form -->
<form class="needs-validation w-100" novalidate id="addCustomerForm">
<div class="d-flex justify-content-between align-items-center w-100">
<!-- Add New Customer (Aligned Left) -->
<h5 class="modal-title" id="customerModalLabel" style="margin: 0;">Add New Customer</h5>
<!-- Buttons (Aligned Right) -->
<div class="d-flex">
<button type="submit" class="btn btn-primary save-invoice-customer" style="margin-right: 10px;">Save Customer</button>
<button type="button" class="close closeCustomerModal" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
</div>
</form>
</div>
<div class="modal-body">
<div class="form-row">
<div class="form-group col-md-6">
<label for="cus_first_name" class="col-form-label">First Name<span class="text-danger"> *</span></label>
<input type="text" class="form-control" id="cus_first_name" placeholder="First Name" required/>
</div>
<div class="form-group col-md-6">
<label for="cus_last_name" class="col-form-label">Last Name</label>
<input type="text" class="form-control" id="cus_last_name" placeholder="Last name" />
</div>
<!-- <div class="form-group col-md-4">
<label for="cus_date_of_birth" class="col-form-label">Date Of Birth</label>
<input type="date" id="cus_date_of_birth" class="form-control" max="<?= date('Y-m-d', strtotime('-18 years')); ?>" placeholder="Date Of Birth" />
</div> -->
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="cus_email" class="col-form-label">Email</label>
<input type="text" class="form-control" id="cus_email" placeholder="Email" onkeyup="validateEmail(this.value)" onchange="checkExisting(this.value,'email','cus_email')" />
<span id="emailValidationMessage"></span>
</div>
<div class="form-group col-md-6">
<label for="cus_mobile_no" class="col-form-label">Mobile</span></label>
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text">+91</div>
</div>
<input type="text" class="form-control" id="cus_mobile_no" placeholder="Mobile Number (Enter only numbers)" maxlength="10" onkeypress="return restriction(event)" onchange="checkExisting(this.value,'mobile_no','cus_mobile_no')"/>
</div>
<span id="mobileValidationMessage"></span>
</div>
<div class="form-group col-md-6">
<label for="baddress1" class="col-form-label">Billing Address 1</span></label>
<input type="text" class="form-control" id="baddress1" name="baddress1" placeholder="Address (eg : 1234 Main St)" />
</div>
<!-- Address 2 -->
<div class="form-group col-md-6">
<label for="baddress2" class="col-form-label">Billing Address 2</label>
<input type="text" class="form-control" id="baddress2" name="baddress2" placeholder="Address (eg : 1234 Main St)" />
</div>
<div class="form-group col-md-6">
<label for="bcountry" class="col-form-label">Country</span></label>
<select class="form-control" id="bcountry" name="bcountry[]"placeholder="Choose Your Country" >
<option selected value="India">India</option> <?php
if(!empty($country_details)){
foreach ($country_details as $value) { ?>
<option value="<?php echo $value['country_short_name']; ?>">
<?php echo $value['country_name']; ?>
</option>
<?php }} ?>
</select>
</div>
<div class="form-group col-md-6">
<label for="bstate" class="col-form-label">State</label>
<input type="text" class="form-control" id="bstate" name="bstate" value="Tamil Nadu" />
</div>
<div class="form-group col-md-6">
<label for="sstate" class="col-form-label">City</span></label>
<input type="text" class="form-control" id="bcity" name="bcity" placeholder="City" />
</div>
<div class="form-group col-md-6">
<label for="bpincode" class="col-form-label">Pincode</span></label>
<input type="number" class="form-control" id="bpincode" name="bpincode" maxlength="6" oninput="this.value=this.value.slice(0, this.maxLength)" pattern="\d{6}" title="Please enter a 6-digit postal code." placeholder="Pincode" />
</div>
<div class="form-row">
<!-- Checkbox for Copy -->
<div class="form-group col-md-12 text-right checkbox checkbox-purple">
<input type="checkbox" id="addressCopiedAsShipping" />
<label for="addressCopiedAsShipping"> Is the above address same as the shipping address?</label>
</div>
</div>
<div class="after-shipping-addr-add-more">
<div class="form-group">
<div class="form-row">
<!-- Shipping Address 1 -->
<div class="form-group col-md-6">
<label for="saddress1" class="col-form-label">Shipping Address 1</span></label>
<input type="text" class="form-control" id="saddress1" name="saddress1" placeholder="Address (eg : 1234 Main St)" />
</div>
<!-- Shipping Address 2 -->
<div class="form-group col-md-6">
<label for="saddress2" class="col-form-label">Shipping Address 2</label>
<input type="text" class="form-control" id="saddress2" name="saddress2" placeholder="Address (eg : 1234 Main St)" />
</div>
<!-- Country -->
<div class="form-group col-md-6">
<label for="scountry" class="col-form-label">Country</span></label>
<select class="form-control" id="scountry" name="scountry[]"placeholder="Choose Your Country" >
<option selected value="India">India</option> <?php
if(!empty($country_details)){
foreach ($country_details as $value) { ?>
<option value="<?php echo $value['country_short_name']; ?>">
<?php echo $value['country_name']; ?>
</option>
<?php } } ?>
</select>
</div>
<!-- State -->
<div class="form-group col-md-6">
<label for="sstate" class="col-form-label">State</label>
<input type="text" class="form-control" id="sstate" name="sstate" value="Tamil Nadu" />
</div>
<div class="form-group col-md-6">
<label for="sstate" class="col-form-label">City</span></label>
<input type="text" class="form-control" id="scity" name="scity" placeholder="City" />
</div>
<!-- Pincode -->
<div class="form-group col-md-6">
<label for="spincode" class="col-form-label">Pincode</span></label>
<input type="number" class="form-control" id="spincode" name="spincode" maxlength="6" oninput="this.value=this.value.slice(0, this.maxLength)" pattern="\d{6}" title="Please enter a 6-digit postal code." placeholder="Pincode" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary closeCustomerModal" data-dismiss="modal" id="closeCustomerModal">Close</button>
</div>
<!-- Country, State, City, Postal Code, etc. fields for Shipping Address -->
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Add Book Modal -->
<div class="modal fade" id="addBookModal" tabindex="-1" role="dialog" aria-labelledby="addBookModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addBookModalLabel">Add Book</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<form class="needs-validation" novalidate id="addBookForm">
<div class="modal-body">
<div class="form-row">
<div class="form-group col-md-6">
<label for="bookName">Book Name<span class="text-danger"> *</span></label>
<input type="text" class="form-control" id="bookName" name="bookName" required />
</div>
<div class="form-group col-md-6">
<label for="bookPrice">Price<span class="text-danger"> *</span></label>
<input type="number" class="form-control" id="bookPrice" name="bookPrice" required min="0">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="publication_date" class="col-form-label">Publication Date</label>
<input type="date" class="form-control" id="publication_date" name="publication_date" value="<?= isset($details['publication_date']) ? $details['publication_date'] : '' ?>" max="<?= date('Y-m-d'); ?>" placeholder="Publication Date">
</div>
<div class="form-group col-md-6">
<label for="isbn_code" class="col-form-label">ISBN Code</label>
<input type="text" class="form-control" id="isbn_code" name="isbn_code" placeholder="ISBN Code" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="publisher" class="col-form-label">Publisher Name</label>
<input type="text" class="form-control" id="publisher" name="publisher" placeholder="Publisher Name" value="<?= isset($details['publisher']) ? $details['publisher'] : '' ?>" />
</div>
<div class="form-group col-md-6">
<label for="publishers_code" class="col-form-label">Publisher Code<span class="text-danger"> *</span></label>
<input type="text" class="form-control" id="publishers_code" name="publishers_code" placeholder="Publisher Code" required />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Add Book</button>
</div>
</form>
</div>
</div>
</div>
<div id="billing_shipping_addresses_modal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-body">
<div class="text-center mt-2 mb-4">
<h4 id="form_add_edit">Billing & Shipping Address</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="hideBillingShippingModel(this)">
<span aria-hidden="true">&times;</span>
</button>
</div>
<h5 >Billing Address</h5>
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label for="quick_billing_address"> Address<span class="text-danger"> *</span></label>
<input class="form-control" type="text" id="quick_billing_address" required placeholder="Billing Address">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="quick_billing_country"> Country<span class="text-danger"> *</span></label>
<select class="form-control" id="quick_billing_country">
<option selected value="India">India</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="quick_billing_state">State</label>
<input class="form-control" type="text" id="quick_billing_state" value="Tamil Nadu">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="quick_billing_city"> City<span class="text-danger"> *</span></label>
<input class="form-control" type="text" id="quick_billing_city" required placeholder="City">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="quick_billing_postal_code"> Postal Code<span class="text-danger"> *</span></label>
<input class="form-control" type="number" id="quick_billing_postal_code" required placeholder="Postal Code" maxlength="6" oninput="this.value=this.value.slice(0, this.maxLength)" pattern="\d{6}" title="Please enter a 6-digit postal code.">
</div>
</div>
<div class="form-group col-md-12 text-right">
<input type="checkbox" id="addressCopiedAsShippingModel" >
<label for="addressCopiedAsShippingModel"> Is the above address same as the shipping address?</label>
</div>
</div>
<div class="text-center">
<hr class="center-line">
</div>
<h5 >Shipping Address</h5>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="shipping_name"> Shipping Address Name<span class="text-danger"> *</span></label>
<input class="form-control" type="text" id="shipping_name" required placeholder="Shipping Address Name">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="quick_shipping_address"> Address<span class="text-danger"> *</span></label>
<input class="form-control" type="text" id="quick_shipping_address" required placeholder="Shipping Address">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="quick_shipping_country"> Country<span class="text-danger"> *</span></label>
<select class="form-control" id="quick_shipping_country">
<option selected value="India">India</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="quick_shipping_state"> State</label>
<input class="form-control" type="text" id="quick_shipping_state" value="Tamil Nadu">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="quick_shipping_city"> City<span class="text-danger"> *</span></label>
<input class="form-control" type="text" id="quick_shipping_city" required placeholder="City">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="quick_shipping_postal_code"> Postal Code<span class="text-danger"> *</span></label>
<input class="form-control" type="number" id="quick_shipping_postal_code" required placeholder="Postal Code" maxlength="6" oninput="this.value=this.value.slice(0, this.maxLength)" pattern="\d{6}" title="Please enter a 6-digit postal code.">
</div>
</div>
</div>
<div class="form-group text-center">
<button class="btn btn-rounded btn-primary" type="submit" onclick="submitAddress()">Submit</button>
</div>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Creating a model for new custome alert box -->
<!-- Creating a model for new custome alert box -->
<!-- Custom Alert Modal -->
</div>
</div>
<div class="modal fade" id="customAlertModal" tabindex="-1" role="dialog" aria-labelledby="customAlertLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="customAlertLabel">Alert</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body" id="customAlertMessage">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
var status = "<?php echo isset($invoice_details['status']) ? $invoice_details['status'] : ''; ?>";
var invoice_type = "<?php echo isset($invoice_type) ? $invoice_type : ''; ?>";
console.log('Invoice Type:', invoice_type);
console.log('Status:', status);
// Call the function to show buttons based on initial status
showButtonsBasedOnStatus(status, invoice_type);
// Handling button clicks
$('#cancelButton').click(function() {
console.log('Cancel button clicked');
});
$('#saveDraftButton').click(function() {
console.log('Save as Draft button clicked');
});
$('#voidButton').click(function() {
console.log('Void button clicked');
});
$('#saveApprovedButton').click(function() {
console.log('Save as Approved button clicked');
});
});
function hideAllButtons() {
$('#cancelButton, #saveDraftButton, #voidButton, #saveApprovedButton, #saveButton').hide();
}
// Function to show buttons based on status and invoice_type
function showButtonsBasedOnStatus(status, invoice_type) {
hideAllButtons();
if (invoice_type == '1' || invoice_type =='2') {
if (status == '') {
$('#saveDraftButton, #saveApprovedButton').show();
} else if (status == 'Draft') {
$('#voidButton, #saveDraftButton, #saveApprovedButton').show();
} else if (status == 'Approved') {
$('#cancelButton').show();
if (invoice_type == '2') {
$('#saveButton').show();
}
} else if (status == 'Cancelled' || status == 'Void') {
hideAllButtons();
}
}
}
document.getElementById('fromsubcription').value = new Date().toLocaleDateString('en-GB');
</script>
<script>
var bookData = <?php echo json_encode($books); ?>;
localStorage.setItem('add_book_index', 0);
document.querySelector("#itemTable tbody tr:first-child .remove-item").style.visibility = 'hidden';
document.getElementById("addItem").addEventListener("click", function() {
var bookArray = bookData;
console.log(bookArray);
var table = document.getElementById("itemTable").getElementsByTagName("tbody")[0];
var counter = table.rows.length;
var newRow = table.insertRow(table.rows.length);
var cell1 = newRow.insertCell(0);
cell1.style.width ="17%";
var cell2 = newRow.insertCell(1);
cell2.style.width = "8%";
var cell3 = newRow.insertCell(2);
cell3.style.width = "20%";
var cell4 = newRow.insertCell(3);
cell4.style.display = "none";
var cell5 = newRow.insertCell(4);
cell5.style.width = "22%";
var cell6 = newRow.insertCell(5);
cell6.style.width = "15%";
var cell7 = newRow.insertCell(6);
cell7.style.width = "5%";
cell7.className = "last-column";
// var cell9 = newRow.insertCell(8);
html = `<select class="form-control book-select fixed-width-select" id="book${counter}" name="item_details[]" onchange="displayBookTag(this, ${counter})" data-toggle="select2" required>
<option value="">Select a <?= $flag_name ?></option>
<option value="add_new_book">+ Add New Book</option>`;
// Populate options from the bookArray
bookArray.forEach(function(book) {
html += `<option value="${book.book_id}">${book.title}</option>`;
});
html += `</select>`;
cell1.innerHTML = html;
// cell1.innerHTML = '<input type="text" class="form-control" name="item_details[]">';
cell1.innerHTML += '<span>&ensp;</span><textarea name="description[]" class="form-control" placeholder="Enter Description" id="description'+counter+'" rows="2" style="border: 1px dashed #ddd"></textarea>';
cell1.innerHTML += '<input type="hidden" class="form-control" id="hiddenInvoiceChildId' + counter + '" placeholder="hidden for invoice child/item id" name="invoice_child_id[]" value="">';
cell2.innerHTML = '<input type="number" class="form-control item-quantity" id="quantity' + counter + '" name="quantity[]" oninput="calculateInvoice(this,' + counter + ')" min="1">';
cell3.innerHTML = '<input type="number" class="form-control item-rate" id="rate' + counter + '" name="rate[]" oninput="calculateInvoice(this,' + counter + ')" min="0" step="0.001">';
cell4.innerHTML = '<input type="hidden" type="number" class="form-control item-tax" id="tax' + counter + '" name="tax[]" min="0" step="0.001">';
cell5.innerHTML = '<div class="input-group"><input type="number" style="width: 41%;" class="form-control item-discount-amount item-discount-group" id="item_discount_amount' + counter + '" name="discount_amount[]" oninput="calculateInvoice(this,' + counter + ')" min="0" step="0.001"><select class="item-discount-type custom-select item-discount-group" style=""width:12%;" id="item_discount_type' + counter + '" name="discount_type[]" oninput="calculateInvoice(this,' + counter + ')"><option value="%">%</option><option value="₹">₹</option></select></div>';
cell6.innerHTML = '<input type="number" class="form-control item-amount" id="amount' + counter + '" name="amount[]" min="0" step="0.001">';
cell7.innerHTML = '<span class="icon"><center><i class="fa fa-trash remove-item "></i></center></span>';
$(newRow.querySelector('.book-select')).select2();
localStorage.setItem('add_book_index', counter);
});
function displayBookTag(inputElement, counter) {
var row = inputElement.parentElement.parentElement;
var bookId = inputElement.value;
// Check if the selected option is "add_new_book"
if (bookId === "add_new_book") {
// Open the modal dialog for adding a new book
$('#addBookModal').modal('show');
// Reset the select back to its default value
$(inputElement).val('');
} else {
// Get the selected book details
var selectedBook = bookData.find(book => book.book_id == bookId);
if (selectedBook) {
// console.log(row);
// Update the fields in the current row with book details
row.querySelector('#quantity' + counter).value = 1;
row.querySelector('#rate' + counter).value = selectedBook.price;
// row.querySelector('#rate' + counter).readOnly = true;
row.querySelector("#tax" + counter).value = selectedBook.tax ? selectedBook.tax : 0;
row.querySelector("#tax" + counter).readOnly = true;
calculateInvoice(inputElement, counter);
} else {
console.log(bookData);
// Handle case where selectedBook is undefined
console.log("Book ID:", bookId); // Check the extracted book ID
console.log("Book Array:", bookData);
console.error("Selected book not found!");
}
}
}
function calculateInvoice(inputElement, counter) {
if (!inputElement.classList.contains('item-quantity') && !inputElement.classList.contains('book-select')) {
$('#discount-type').hide();
$('#discount-type').removeAttr('name');
}
if(inputElement.classList.contains('item-discount-group')){
var row = inputElement.parentElement.parentElement.parentElement; // now we added input group so 3 parent here..
}else{ var row = inputElement.parentElement.parentElement; }
var quantity = row.querySelector('#quantity' + counter).value;
if (quantity == 0 || quantity < 1){
$('#quantity' + counter).val(1);
quantity = 1;
}
var rate = row.querySelector('#rate' + counter).value;
var discountType = row.querySelector('#item_discount_amount'+ counter).value; // Get the selected discount type
if (!inputElement.classList.contains('item-quantity')) {
var discountAmount = parseFloat(row.querySelector('#item_discount_amount'+ counter).value) || 0;
}
console.log(rate);
if (!isNaN(quantity) && !isNaN(rate)) {
var amount = quantity * rate;
amount = parseFloat(amount).toFixed(2);
if (discountType === '₹') {
// Calculate discount based on ₹
var discountedAmount = parseFloat(amount - discountAmount);
row.querySelector('#amount' + counter).value = parseFloat(amount).toFixed(2);
} else if (discountType === '%') {
// Calculate discount based on %
var discountPercentage = discountAmount;
var discountValue = parseFloat((amount * discountPercentage) / 100);
var discountedAmount = parseFloat(amount - discountValue);
row.querySelector('#amount' + counter).value = parseFloat(amount).toFixed(2);
} else {
// Invalid discount type
row.querySelector('#amount' + counter).value = parseFloat(amount).toFixed(2); // No discount applied
}
} else {
row.querySelector('#amount' + counter).value = ''; // Clear the amount if either quantity or rate is not a number
}
row.querySelector('#amount' + counter).readOnly = true;
calculateOverallTotals(inputElement);
}
function calculateOverallTotals(inputElement = 0) {
var itemAmountInputs = document.querySelectorAll('.item-amount');
var itemTaxInputs = document.querySelectorAll('.item-tax');
var itemDiscountAmountInputs = document.querySelectorAll('.item-discount-amount');
var itemDiscountTypeInputs = document.querySelectorAll('.item-discount-type');
var overallAmount = 0;
var overallTax = 0;
var overallDiscount = 0;
itemAmountInputs.forEach(function(input, index) {
var amount = parseFloat(input.value) || 0;
overallAmount += amount;
var tax = parseFloat(itemTaxInputs[index].value) || 0;
overallTax += tax;
var discountType = itemDiscountTypeInputs[index].value;
var discountAmount = parseFloat(itemDiscountAmountInputs[index].value) || 0;
if (discountType === '₹') {
overallDiscount += discountAmount;
} else if (discountType === '%') {
var discountValue = (amount * discountAmount) / 100;
overallDiscount += discountValue;
}
});
// Get the shipping charges value, tax, and discount values
var shippingCharges = parseFloat(document.getElementById('shippingCharges').value) || 0;
var tax = parseFloat($("#invoicetax").val()) || 0;
var discount = parseFloat($("#discount").val()) || 0;
// Calculate the total using the formula: subtotal - tax + shipping - discount
var total = overallAmount - overallTax + shippingCharges - overallDiscount;
// console.log(total);
// Update the subtotal, tax, shipping charges, discount, and total in the calculation card
var subtotalElement = parseFloat(overallAmount.toFixed(2));
$("#subtotal").val(subtotalElement);
var taxElement = parseFloat(overallTax.toFixed(2));
$("#invoicetax").val(taxElement);
var discountElement = parseFloat(overallDiscount.toFixed(2));
if ($('#discount-type').css('display') == 'none') {
$("#discount").val(discountElement);
}
var totalElement = Math.round(total);
$("#exacttotal").val(parseFloat(total.toFixed(2)));
$("#grandtotal").val(totalElement);
var status = document.getElementById('status').value;
// $("#balanceAmount").val(totalElement);
if (status == 'Draft' || status == '') {
$("#balanceAmount").val(totalElement);
$("#paidAmount").val('0');
} else if (status == 'Approved') {
$("#balanceAmount").val('0');
$("#paidAmount").val(totalElement);
}
if (inputElement == 0) {
if ($('#discount-type').css('display') == 'block') {
var dis_count_value = 0;
var shippingCharges = parseInt($('#shippingCharges').val());
var subtotal = $('#subtotal').val();
if ($('#discount-type').val() == '%') {
dis_count_value = subtotal * $('#discount').val() / 100;
}else{
dis_count_value =subtotal - $('#discount').val();
}
if (isNaN(shippingCharges)) {
shippingCharges =0;
}
$('#exacttotal').val((subtotal - dis_count_value) + shippingCharges);
$('#grandtotal').val((subtotal - dis_count_value) + shippingCharges);
$('#balanceAmount').val((subtotal - dis_count_value) + shippingCharges);
}
}else if (inputElement.classList.contains('item-quantity')) {
var hasValue = false;
$('.item-discount-amount').each(function() {
if ($(this).val().trim() !== "") {
hasValue = true;
} else {
hasValue = false;
}
});
if(!hasValue){
$('#discount').trigger('change');
}
}
if (inputElement.classList.contains('book-select')) {
if ($('#discount-type').css('display') != 'none') {
var discount =$('#discount').val();
var subtotal= $('#subtotal').val();
var shippingCharges = parseInt($('#shippingCharges').val());
var last_multiple_value = 0 ;
if ($('#discount-type').val() == '%') {
last_multiple_value = (subtotal * discount) / 100;
} else {
last_multiple_value = subtotal - discount;
}
if (isNaN(shippingCharges)) {
shippingCharges =0;
}
$('#exacttotal').val(subtotal-last_multiple_value + shippingCharges);
$('#grandtotal').val(parseInt(subtotal - last_multiple_value + shippingCharges));
$('#balanceAmount').val(parseInt(subtotal - last_multiple_value + shippingCharges));
}
}
}
// Define a function to calculate the grand total
function calculateGrandTotal() {
var invoiceItems = []; // Create an empty array to store item details
// Loop through the rows of the item table to gather item details
var rows = document.querySelectorAll("#itemTable tbody tr");
rows.forEach(function(row) {
var item = {
subtotal: parseFloat(row.querySelector('input[name="amount[]"]').value) || 0,
discount_amount: parseFloat(row.querySelector('input[name="discount_amount[]"]').value) ||
0,
discount_type: row.querySelector('select[name="discount_type[]"]').value
};
invoiceItems.push(item); // Add the item to the array
});
// Now you have the invoiceItems array populated with item details
// Calculate the grand total based on the invoiceItems array
var grandTotal = 0;
var manuallyEnteredDiscount = parseFloat(document.getElementById("discount").value) || 0;
invoiceItems.forEach(function(item) {
var amount = item.subtotal;
// Check if a discount is entered for the item, and if so, don't apply it again
if (item.discount_type === '₹' && item.discount_amount > 0) {
amount += item.discount_amount; // Add the discount back to the amount
} else if (item.discount_type === '%' && item.discount_amount > 0) {
var discountValue = (amount * item.discount_amount) / 100;
amount += discountValue; // Add the discount back to the amount
}
grandTotal += amount;
});
// Add the manually entered discount to the grand total
grandTotal -= manuallyEnteredDiscount;
console.log($('#discount-type'));
// Update the grand total in the UI
var grandTotalElement = parseFloat(grandTotal.toFixed(2));
document.getElementById("exacttotal").value = grandTotalElement;
document.getElementById("grandtotal").value = Math.round(grandTotalElement);
}
</script>
<!-- JavaScript for removing a row from the table -->
<script>
// Function to remove a row from the table
function removeItem(row) {
var table = document.getElementById("itemTable").getElementsByTagName("tbody")[0];
table.removeChild(row);
calculateOverallTotals(); // Call the calculation function to update the totals
}
// Attach the removeItem function to the Remove buttons using event delegation
document.querySelector("#itemTable tbody").addEventListener("click", function(event) {
if (event.target.classList.contains("remove-item")) {
var row = event.target.closest("tr"); // Find the closest row to the clicked button
removeItem(row);
}
});
</script>
<script>
global_billarr = "";
global_billid = "";
$(document).ready(function() {
var invoice_type = "<?php echo isset($invoice_type) ? $invoice_type : ''; ?>";
if (invoice_type !== '2'){
$('#membership_id_div').hide();
}
var iid_arr = <?php echo json_encode($invoice_item_details); ?>;
var custid = "<?= isset($invoice_details['customer_id']) ? $invoice_details['customer_id'] : ""; ?>";
var inv_number = "<?= isset($invoice_details['invoice_number']) ? $invoice_details['invoice_number'] : ""; ?>";
console.log(inv_number);
//alert(inv_number);
var ship_addrid = "";
if (custid != '') {
ship_addrid = "<?= isset($invoice_details['shipping_address_id']) ? $invoice_details['shipping_address_id'] : ""; ?>";
var bill_addrid = "<?= isset($invoice_details['billing_address_id']) ? $invoice_details['billing_address_id'] : ""; ?>";
var cust_ship_arr = <?= isset($customer_shipping_arr) ? json_encode($customer_shipping_arr) : "[]"; ?>;
console.log(cust_ship_arr);
if (cust_ship_arr.length > 0) {
$.each(cust_ship_arr, function(k, v) {
$('#loadShippingDropdown').append($('<option>', {
value: v.customer_address_id,
text:v.address,
selected: (v.customer_address_id == ship_addrid) ? true : false
}));
});
}
if ((bill_addrid === "" || parseInt(bill_addrid) === 0)) {
$('#editAddressesCheckbox').prop('checked', true);
// $("#storeBillingAddress").prop("readonly", false);
$("#storeBillingAddress").prop("readonly", true);
$("#storeShippingAddress").prop("readonly", true);
}
$('#hiddenBillingAddressId').val(bill_addrid);
// get_customer_membership_details(custid);
}
if (inv_number != '') {
var numbering_arr = <?php echo json_encode($invoice_number_formatting); ?>;
var next_id_string = numbering_arr[0].next_id;
//alert('Hi');
$('#hiddenNextId').val(next_id_string).prop('readonly',true);
$("#invoiceNumber").val(inv_number).prop("readonly", true);
} else {
var numbering_arr = <?php echo json_encode($invoice_number_formatting); ?>;
console.log("numbering arr = "+numbering_arr);
var filtered_data = $.grep(numbering_arr, function(item) {
return item.id === '1';
});
var final_sno = generateSerialNumber(filtered_data);
$("#invoiceNumber").val(final_sno).prop("readonly", true);
}
var fromDateValue = "<?= isset($invoice_item_details[0]['from_subscription']) ? $invoice_item_details[0]['from_subscription'] : ""; ?>";
if (fromDateValue != '') {
fromDateValue = formatDate(fromDateValue);
updateToDateMinDate(fromDateValue);
}
function formatDate(dateString) {
const dateParts = dateString.split('-');
return `${dateParts[2]}/${dateParts[1]}/${dateParts[0]}`;
}
$("#editAddressesCheckbox").on("change", function() {
if ($(this).is(":checked")) {
$('#quick_shipping_country').attr('required',true);
// $("#storeBillingAddress").prop("readonly", false);
$("#storeBillingAddress").prop("readonly", true);
$("#storeShippingAddress").prop("readonly", true);
$('#hiddenBillingAddressId').val(0);
$('#billing_shipping_addresses_modal').modal('show');
$.ajax({
type: "GET",
url: "<?= base_url() . 'get_country' ?>",
success: function(response) {
var countries = JSON.parse(response);
// Loop through the countries array
$.each(countries, function(index, country) {
// Append an <option> element for each country
$('#quick_billing_country').append('<option value="' + country.country_short_name + '">' + country.country_name + '</option>');
$('#quick_shipping_country').append('<option value="' + country.country_short_name + '">' + country.country_name + '</option>');
}); },
error: function() {
alert("Error fetching address.");
}
});
} else {
$("#storeBillingAddress").prop("readonly", true);
$("#storeShippingAddress").prop("readonly", true);
if (global_billarr !== "") {
$("#storeBillingAddress").val(global_billarr);
$('#hiddenBillingAddressId').val(global_billid);
}
}
});
function generateSerialNumber(filtered_data) {
var next_id_string = filtered_data[0].next_id;
console.log(next_id_string);
var left_pad_string = filtered_data[0].left_pad;
// var prefix_string = String(filtered_data[0].id_formating); // don't remove
var prefix_string = <?= json_encode($financial_year); ?>;
var left_pad_numberic = parseInt(left_pad_string);
var next_id_numberic = parseInt(next_id_string);
var padded_id = next_id_string.padStart(left_pad_numberic, '0');
var serial_number = prefix_string + '-' + padded_id;
next_id_numberic++;
$("#hiddenNextId").val(next_id_numberic).prop("readonly", true);
return serial_number;
}
if (custid != '' && (ship_addrid == undefined || ship_addrid == null || ship_addrid == '0' || ship_addrid == '')) {
// $("#storeShippingAddress").prop("readonly", false);
$("#storeShippingAddress").prop("readonly", true);
console.log('ship addrid is undefined, null, 0, or empty');
}
});
// $('#customer_name').onchange(function(){
// get_customer_membership_details(custid);
// })
// Billing ajax call
function get_customer_billing_details(cust_id) {
if (cust_id == '0') {
$('#customerModal').modal('show');
}else if(cust_id != ''){
$('#editAddressesCheckbox').prop('checked', false);
// $("#storeBillingAddress").prop("readonly", false);
$("#storeBillingAddress").prop("readonly", true);
// $("#storeShippingAddress").prop("readonly", false);
$("#storeShippingAddress").prop("readonly", true);
$('#customerModal').modal('hide');
$('#cus_mobile_no').val("");
$('#cus_first_name').val("");
$('#cus_last_name').val("");
$('#cus_email').val("");
$('#baddress1').val("");$('#baddress2').val("");$('#bcountry').val("");$('#bstate').val("");$('#bcity').val("");$('#bzip').val("");
$('#saddress1').val("");$('#saddress2').val("");$('#scountry').val("");$('#sstate').val("");$('#scity').val("");$('#szip').val("");
$("#emailValidationMessage").text("");
$("#mobileValidationMessage").text("");
$('#addressCopiedAsShipping').prop('checked', false);
$('.save-invoice-customer').prop('disabled', false);
$.ajax({
type: "POST",
url: "<?= base_url() . 'get_customer_billing_details' ?>",
data: {
customer_id: cust_id
},
success: function(response) {
cs = response['data']['customer_shipping'];
cb = response['data']['customer_billing'];
$('#hiddenBillingAddressId').val('');
$("#editAddressesCheckbox").prop("checked", false);
global_billarr = "";
global_billid = "";
var customer_billing_addressDetails = [];
if (cb.length > 0) {
cb = [cb[0]];
console.log("cFAFAFAbbb",cb);
$.each(cb, function(k, v) {
var state = v.state_name ? v.state_name : v.state;
state = v.postal_code ? state +' ' + v.postal_code : state;
v.address_1 ? customer_billing_addressDetails.push(v.address_1 + " " + v.address_2) : "";
v.city ? customer_billing_addressDetails.push(v.city) : "";
state ? customer_billing_addressDetails.push(state) : "";
v.country_name ? customer_billing_addressDetails.push(v.country_name) : "";
customer_billing_id = v.customer_address_id;
$('#hidden_first_name').val(v.first_name);
$('#hidden_last_name').val(v.last_name);
});
}else{
}
global_billarr = customer_billing_addressDetails.join(', ') + ".";
global_billid = customer_billing_id;
$("#storeBillingAddress").val(global_billarr).prop("readonly", true);
$('#hiddenBillingAddressId').val(global_billid);
if (cs.length > 0) {
$('#loadShippingDropdown').empty();
$('#loadShippingDropdown').append($('<option>', {
value: "",
text: "Select an address"
}));
$.each(cs, function(k, v) {
$('#loadShippingDropdown').append($('<option>', {
value: v.customer_address_id,
text:v.first_name+','+ v.address,
}));
});
$("#storeShippingAddress").val('');
} else {
$('#loadShippingDropdown').empty();
$('#loadShippingDropdown').append($('<option>', {
value: "",
text: "Select an address"
}));
$("#editAddressesCheckbox").prop("checked", false);
// $("#storeBillingAddress").prop("readonly", false);
$("#storeBillingAddress").prop("readonly", true);
$("#storeShippingAddress").prop("readonly", true);
}
},
error: function() {
alert("Error fetching address.");
$("#editAddressesCheckbox").prop("checked", false);
// $("#storeBillingAddress").prop("readonly", false);
$("#storeBillingAddress").prop("readonly", true);
$("#storeShippingAddress").prop("readonly", true);
}
});
}
}
// shipping ajax call
function get_customer_shipping_details(ship_addr_id) {
var cust_id = $("#customerName").val();
$.ajax({
type: "POST",
url: "<?= base_url() . 'get_customer_shipping_details' ?>",
data: {
shipping_address_id: ship_addr_id,
customer_id: cust_id
},
success: function(response) {
cs = response['data']['customer_shipping'];
customer_shipping = "";
customer_shipping_addressDetails = [];
if (cs.length > 0) {
$.each(cs, function(k, v) {
// v.first_name?customer_shipping_addressDetails.push(v.first_name):'';
var state = v.state_name ? v.state_name : v.state;
state = v.postal_code ? state + ' ' + v.postal_code : state;
v.address_1 ? customer_shipping_addressDetails.push(v.address_1 + " " + v.address_2) : "";
v.city ? customer_shipping_addressDetails.push(v.city) : "";
state ? customer_shipping_addressDetails.push(state) : "";
v.country_name ? customer_shipping_addressDetails.push(v.country_name) : "";
customer_shipping_id = v.customer_address_id;
$('#hidden_first_name').val(v.first_name);
$('#hidden_last_name').val(v.last_name);
});
}
$("#storeShippingAddress").val(customer_shipping_addressDetails.join(', ') + ".").prop("readonly", true);
},
error: function() {
alert("Error fetching address.");
}
});
}
// membership ajax call
function get_customer_membership_details(cust_id) {
if (parseInt(cust_id) > 0) {
$.ajax({
type: "POST",
url: "<?= base_url() . 'get_customer_membership_details' ?>",
data: {
customer_id: cust_id
},
success: function(response) {
cm = response['data']['customer_membership'];
console.log(cm);
console.log(cm);
cm.sort(function(a, b) {
return b.is_renew - a.is_renew;
});
if (cm.length > 0) {
text1 = cm[0].is_renew >0 ? " - Renewed" : "";
text2 = cm[0].status == 0 ? " - Expried" : "";
$(".subscribedetails").show(); // Change this line to use the class selector
let messages = "Earlier Membership : <br>";
for (let i = 0; i < cm.length; i++) {
let text1 = cm[i].is_renew > 1 ? " - Renewed" : "";
let text2 = '';console.log('invoice status'+cm[i].invoice_status);
if (cm[i].invoice_status === 'Draft'){
text2 = " - Draft";
}else if(cm[i].invoice_status === 'Void'){
text2 = " - Void";
}else if(cm[i].invoice_status === 'Cancelled'){
text2 = " -Cancelled "
}
let text3 = '';
if(cm[i].invoice_status === 'Approved'){
text3 = cm[i].status == 0 ? ' - Expired ': " - Active";
}
messages += cm[i].title + "<br> ( From: " + cm[i].formatted_from_subscription + " To: " + cm[i].formatted_to_subscription + " )" + text1 + text2 + text3+ " <br>";
console.log('message - '+messages);
}
// $("#schemeName").text(message);
var invoice_type = "<?php echo isset($invoice_type) ? $invoice_type : ''; ?>";
console.log('Invoice Type is ', invoice_type);
if(invoice_type === '2'){
$('#membership_id').empty();
// $('#membership_id').prop('required',true);
$('#membership_id').append('<option value = "">Select a Existing Membership ID</option>');
for(i=0;i<cm.length;i++){
membership_id = cm[i].membership_id;
if(cm[i].renewed == null && cm[i].isactive == 1){
console.log(cm[i]);
$('#membership_id').append('<option value="' + membership_id+i + '">' +cm[i].short_code + ' - '+ membership_id+' ' +cm[i].formatted_from_subscription + " To: " + cm[i].formatted_to_subscription +'</option>');
}
}
}else{
$('#membership_id_div').hide();
}
$('#membership_id').on('change', function () {
var output = $('#membership_id').val();console.log(membership_choice);
var membership_choice = output.charAt(output.length-1);
var rawDate = cm[membership_choice].formatted_to_subscription;
var currentDate = new Date();
// Format current date as dd-mm-yy
var formattedDate = ('0' + currentDate.getDate()).slice(-2) + '-' +
('0' + (currentDate.getMonth() + 1)).slice(-2) + '-' +
currentDate.getFullYear().toString().slice(-2);
// Parse rawDate into a Date object
var rawDateParts = rawDate.split('/');
var rawDateObj = new Date(rawDateParts[2], rawDateParts[1] - 1, rawDateParts[0]);
var fsubscription, tsubscription;
if (currentDate > rawDateObj) {
// Start from current date
fsubscription = ('0' + currentDate.getDate()).slice(-2) + '/' +
('0' + (currentDate.getMonth() + 1)).slice(-2) + '/' +
currentDate.getFullYear();
var tsubscriptionDate = new Date(currentDate);
tsubscriptionDate.setFullYear(tsubscriptionDate.getFullYear() + 1);
tsubscription = ('0' + tsubscriptionDate.getDate()).slice(-2) + '/' +
('0' + (tsubscriptionDate.getMonth() + 1)).slice(-2) + '/' +
tsubscriptionDate.getFullYear();
} else {
// Start from rawDate + 1 day
rawDateObj.setDate(rawDateObj.getDate() + 1);
fsubscription = ('0' + rawDateObj.getDate()).slice(-2) + '/' +
('0' + (rawDateObj.getMonth() + 1)).slice(-2) + '/' +
rawDateObj.getFullYear();
rawDateObj.setFullYear(rawDateObj.getFullYear() + 1);
tsubscription = ('0' + rawDateObj.getDate()).slice(-2) + '/' +
('0' + (rawDateObj.getMonth() + 1)).slice(-2) + '/' +
rawDateObj.getFullYear();
}
// Update input fields
$('#fromsubcription').val(fsubscription).prop('readonly', true);
$('#tosubcription').val(tsubscription).prop('readonly', true);
$('#myForm').parsley().validate();
$('#book0').empty();
var scheme = response['data']['scheme']['short_code'];
var book_id = response['data']['scheme']['book_id']
$('#book0').append(`<option value= "${book_id}">${scheme}</option>`);
$('#book0').prop('readonly',true);
var element = $('#book0')[0]; // Get the actual DOM element (not the value)
displayBookTag(element, 0);
$('#myForm').parsley().validate();
});
if (invoice_type === '2'){
showAlert(messages.trim());
}
} else {
$(".subscribedetails").show(); // Change this line to use the class selector
let message = "No Earlier Membership found";
//$("#schemeName").text(message);
//showAlert(message)
}
},
error: function() {
alert("Error fetching address.");
}
});
}
}
// New function to create a cutom alert box,
// since the default alert box is small to display the message
function showAlert(message) {
$('#customAlertMessage').html(message);
$('#customAlertModal').modal('show');
}
</script>
<!-- bill_addr = "<?= isset($invoice_details['billing_address']) ? $invoice_details['billing_address'] : ""; ?>"; -->
<!-- if (bill_addr != '') { $("#storeBillingAddress").val(bill_addr);} -->
<script>
document.getElementById('saveapproved').addEventListener('click', function(event) {
var paymentMode = document.getElementById('paymentMode').value;
if (paymentMode !== "") {
// Get the balance amount
var balanceAmount = parseFloat(document.getElementById('balanceAmount').value) || 0;
// Replicate the balance amount value to the paid amount
document.getElementById('paidAmount').value = balanceAmount;
// Set the status field to 'Draft' before submitting
document.getElementById('status').value = 'Approved';
} else {
// Prevent the form submission
// document.getElementById('paymentMode').focus();
alert("Choose Your payment Mode ");
event.preventDefault(); // Pass the event parameter here
}
});
</script>
<script>
document.getElementById("fromsubcription").onchange = function() {
const toDateInput = document.getElementById('tosubcription');
toDateInput.value = ''; // Clear the value of the "To Subscription" field
const fromDateValue = this.value;
updateToDateMinDate(fromDateValue);
};
function updateToDateMinDate(fromDateValue) {
const toDateInput = document.getElementById('tosubcription');
toDateInput.setAttribute('data-date-start-date', fromDateValue); // Optional if you're using this attribute for something else
// Update the minimum date for the datepicker
$(toDateInput).datepicker('setStartDate', fromDateValue);
}
// function updateToDateMinDate(fromDateValue) {
// const toDateInput = document.getElementById('tosubcription');
// // Convert fromDateValue to a Date object
// const fromDate = new Date(fromDateValue);
// // Set the min attribute of 'tosubcription' input
// toDateInput.min = fromDateValue;
// // Calculate the date 1 year from the selected date
// const maxDate = new Date(fromDate);
// maxDate.setFullYear(fromDate.getFullYear() + 1);
// // Format the max date as 'YYYY-MM-DD' (the format used by the 'date' input)
// const formattedMaxDate = maxDate.toISOString().split('T')[0];
// // Set the max attribute and default value of 'tosubcription' input
// toDateInput.max = formattedMaxDate;
// toDateInput.value = formattedMaxDate;
// }
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
// Get the Due Date input element by its ID
// const dueDateInput = document.getElementById("dueDate");
// Get the current date
// const currentDate = new Date();
// Set the minimum date attribute to today's date (YYYY-MM-DD format)
// const minDate = currentDate.toISOString().split("T")[0];
// dueDateInput.setAttribute("min", minDate);
// Optional: Set the default value to today's date
});
</script>
<script>
// When the "Save as Approved" button is clicked
document.getElementById('saveApprovedButton').addEventListener('click', function() {
// Show the payment modal
const isParsleyValid = $(myForm).parsley().validate();
// Check both browser-native validity and Parsley validation
if (isParsleyValid) {
// Show the payment modal if the form is valid
$('#paymentModal').modal('show');
} else {
// Focus on the first invalid field (optional for better UX)
$(myForm).find('.parsley-error').first().focus();
}
var selectedPaymentMode = document.getElementById('paymentMode').value;
// You can now use the selected payment mode as needed
// console.log('Selected Payment Mode: ' + selectedPaymentMode);
// Close the modal
$('#paymentModal').modal('hide');
document.getElementById('paymentMode').value = "";
});
// Add event listener for the "Close" button
document.getElementById('paymentModal').addEventListener('hidden.bs.modal', function() {
// Reset the payment_method value to an empty string
document.getElementById('paymentMode').value = "";
});
</script>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
console.log("submit event");
var form = event.target;
var status = document.getElementById('status').value;
var invoice_type = document.getElementById('invoice_type').value;
if (!form.checkValidity()) {
form.reportValidity(); // Display validation error messages
event.preventDefault(); // Prevent form submission if it's not valid
this.classList.add('was-validated');
if (status == "Draft") {
alert('Please fill out all required fields correctly.');
$('#saveDraftButton').prop('disabled', false);
$('#saveApprovedButton').prop('disabled', false);
$('#saveapproved').prop('disabled', false);
}
if (status == "Approved") {
$('#saveDraftButton').prop('disabled', false);
$('#saveApprovedButton').prop('disabled', false);
$('#saveapproved').prop('disabled', false);
}
} else {
var table = document.getElementById("itemTable").getElementsByTagName("tbody")[0];
var counter = table.rows.length;
if (counter == 0) {
event.preventDefault(); // Prevent form submission if it's not valid
alert('At least one row should contain a values.');
$('#saveDraftButton').prop('disabled', false);
$('#saveApprovedButton').prop('disabled', false);
$('#saveapproved').prop('disabled', false);
} else {
if (status == "Draft") {
$('#saveDraftButton').prop('disabled', true);
$('#saveApprovedButton').prop('disabled', true);
$('#saveapproved').prop('disabled', true);
}
if (status == "Approved") {
$('#saveDraftButton').prop('disabled', true);
$('#saveApprovedButton').prop('disabled', false);
$('#saveapproved').prop('disabled', true);
}
}
}
});
</script>
<script>
function validateEmail(email) {
// Regular expression for a basic email validation
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var emailInput = document.getElementById("cus_email");
var validationMessage = document.getElementById("emailValidationMessage");
if (emailPattern.test(email)) {
validationMessage.textContent = "";
} else if (email == "") {
validationMessage.textContent = "";
} else {
validationMessage.textContent = "Invalid email address";
validationMessage.style.color = "red";
}
}
function checkExisting(inputvalue, fieldname, elementid) {
spanid = elementid == 'cus_email' ? "emailValidationMessage" : "mobileValidationMessage";
var validationMessage = document.getElementById(spanid);
$.ajax({
type: "POST",
url: "<?= base_url() . 'check_existing' ?>",
data: {
value: inputvalue,
module: 'customers',
field: fieldname
},
success: function(response) {
if (response['data']['status']) {
validationMessage.textContent = response['data']['message'];
validationMessage.style.color = "red";
document.getElementById(elementid).value = "";
} else {
validationMessage.textContent = "";
}
},
error: function() {
alert("Error occur.");
}
});
}
function restriction(event) {
var charCode = event.which || event.keyCode;
if ((charCode >= 48 && charCode <= 57)) {
return true;
} else {
event.preventDefault(); // Prevent the character from being entered
return false;
}
}
</script>
<script>
$(document).ready(function () {
$('#addCustomerForm').submit(function (e) {
e.preventDefault(); // Prevent default form submission
const cus_first_name = $("#cus_first_name").val();
const cus_last_name = $("#cus_last_name").val();
const cus_email = $("#cus_email").val();
const cus_mobile_no = $("#cus_mobile_no").val();
const baddress1 = $("#baddress1").val();
const baddress2 = $("#baddress2").val();
const bcountry = $("#bcountry").val();
const bstate = $("#bstate").val();
const bcity = $("#bcity").val();
const bzip = $("#bpincode").val();
const saddress1 = $("#saddress1").val();
const saddress2 = $("#saddress2").val();
const scountry = $("#scountry").val();
const sstate = $("#sstate").val();
const scity = $("#scity").val();
const szip = $("#spincode").val();
let missingFieldsMessage = '';
// Validate required fields
if (!cus_first_name) missingFieldsMessage += "Name Field is Required\n";
// If there are missing fields, show an alert
if (missingFieldsMessage) {
//alert(missingFieldsMessage);
return; // Stop execution
}
$('.save-invoice-customer').prop('disabled', true);
// Perform AJAX request to save data
$.ajax({
type: "POST",
url: "<?= base_url() . 'save_invoice_customer' ?>",
data: {
cus_first_name,
cus_last_name,
cus_email,
cus_mobile_no,
baddress1,
baddress2,
bcountry,
bstate,
bcity,
bzip,
saddress1,
saddress2,
scountry,
sstate,
scity,
szip
},
success: function (response) {
if (response['data']['status']) {
// alert(response['data']['message']);
// Extract response data
const customerName = response['data']['cus_name'];
const customerId = response['data']['cus_id'];
const bAddressId = response['data']['billing_addr_id'];
const sAddressId = response['data']['shipping_addr_id'];
// Append the customer to the dropdown
const newCustomerOption = $('<option>', {
value: customerId,
text: customerName,
selected: true
});
$('#customerName').append(newCustomerOption);
// Append billing address
if (bAddressId !== null) {
const formattedBillingAddress = [
baddress1 + " " + (baddress2 || ""),
bcity,
(bstate ? bstate + bzip : ""),
bcountry
]
.filter(Boolean) // Remove empty values
.join(", ");
$("#storeBillingAddress").val(formattedBillingAddress).prop("readonly", true);
$('#hiddenBillingAddressId').val(bAddressId);
}
storeShippingAddress
// Append shipping address
if (sAddressId !== null) {
const formattedShippingAddress = [
saddress1 + " " + (saddress2 || ""),
scity,
(sstate ? sstate : ""),
szip,
scountry
]
.filter(Boolean)
.join(", ");
const newShippingOption = $('<option>', {
value: sAddressId,
text: formattedShippingAddress,
selected: true
});
$('#loadShippingDropdown').append(newShippingOption);
$('#storeShippingAddress').val(formattedShippingAddress);
} else {
// Reset dropdown if no shipping address
$('#loadShippingDropdown').empty().append(
$('<option>', {
value: "",
text: "Select an address"
})
);
}
// Clear form fields
$('#addCustomerForm').trigger("reset");
$('#customerModal').modal('hide');
$('.save-invoice-customer').prop('disabled', false);
} else {
alert(response['data']['message'] || "Error occurred while saving the customer.");
$('.save-invoice-customer').prop('disabled', false);
}
},
error: function () {
alert("Error occurred while saving the customer.");
$('.save-invoice-customer').prop('disabled', false);
}
});
});
});
</script>
<script>
$('.closeCustomerModal').click(function() {
// Reset customer dropdown value
$('#customerName').val("").trigger('change');
// Optionally, reset input fields
$('#cus_first_name').val("");
$('#cus_last_name').val("");
$('#cus_email').val("");
$('#cus_mobile_no').val("");
$('#baddress1').val("");
$('#baddress2').val("");
$('#bcountry').val("");
$('#bstate').val("");
$('#bcity').val("");
$('#bzip').val("");
$('#saddress1').val("");
$('#saddress2').val("");
$('#scountry').val("");
$('#sstate').val("");
$('#scity').val("");
$('#szip').val("");
$("#emailValidationMessage").text("");
$("#mobileValidationMessage").text("");
$('#editAddressesCheckbox').prop('checked', false);
$("#addressCopiedAsShipping").prop("checked", false);
});
</script>
<script>
// JavaScript code to handle form submission and AJAX request
$(document).ready(function() {
$('#addBookForm').submit(function(e) {
var Quickadd_bookName = $("#bookName").val();
var Quickadd_bookPrice = $("#bookPrice").val();
var Quickadd_publishersCode = $("#publishers_code").val();
var isValid = true;
var errorMessage = '';
if (Quickadd_bookName === '') {
errorMessage += 'Book name\n';
isValid = false;
}
if (Quickadd_bookPrice === '') {
errorMessage += 'Book Price\n';
isValid = false;
}
if (Quickadd_publishersCode === '') {
errorMessage += 'Publisher Code\n';
isValid = false;
}
if (!isValid) {
alert("Please fill all the required fields: \n"+errorMessage);
}else{
e.preventDefault(); // Prevent default form submission
// Serialize form data
var formData = $(this).serialize();
// Send AJAX request to save the book
$.ajax({
url: '<?php echo base_url("saveBook"); ?>', // URL to your controller function
type: 'POST',
data: formData,
dataType: 'json',
success: function(response) {
console.log("Response:", response); // Log the response object
if (response.success) {
// Book saved successfully
alert(response.message);
$('#addBookModal').modal('hide');
$('#addBookForm')[0].reset();
// Append the new book to the bookData array
var newBook = {
book_id: response.book_id,
title: response.title,
price: response.price,
tax: response.tax
// Add other properties as needed
};
bookData.push(newBook);
console.log("Updated bookData:", bookData); // Log the updated bookData array
// Retrieve the index from localStorage
var addBookIndex = localStorage.getItem('add_book_index');
// Reload only the dropdown at the specified index
var dropdown = $('#itemTable tbody tr:eq(' + addBookIndex + ')').find('.book-select');
dropdown.empty(); // Clear existing options
// Add default and new book options
dropdown.append('<option value="">Select a <?= $flag_name ?></option><option value="add_new_book">+ Add New Book</option>');
bookData.forEach(function(book) {
dropdown.append('<option value="' + book.book_id + '">' + book.title + '</option>');
});
dropdown.select2(); // Reinitialize select2
// Select the newly added book in the dropdown
dropdown.val(response.book_id).trigger('change');
} else {
// Failed to save book
alert(response.message);
}
},
});
}
});
});
</script>
<script>
// JavaScript code to handle voiding invoice and submitting reason
$(document).ready(function() {
// Handle clicking on the "Void" button
$('#voidButton').click(function() {
var invoiceId = <?= json_encode(isset($invoice_details['invoice_id']) ? $invoice_details['invoice_id'] : '') ?>; $('#voidReasonModal').modal('show');
$('#submitVoidReason').data('invoiceId', invoiceId); // Set the invoice_id in the modal
});
// Handle submitting void reason
$('#submitVoidReason').click(function() {
var voidReason = $('#voidReason').val().trim(); // Trim the value to remove whitespace
var invoiceId = $(this).data('invoiceId'); // Get the invoice_id from the button data
// Check if voidReason is empty
if (voidReason === '') {
alert('Please enter a reason for voiding.');
return;
}
// Perform AJAX request to update status and reason
$.ajax({
type: 'POST',
url: '<?php echo base_url("updateInvoiceStatus"); ?>', // Adjust the URL to match your controller route
data: {
invoice_id: invoiceId,
void_reason: voidReason
},
success: function(response) {
if ('<?= $invoice_type ?>' == 1){
window.location.href = "<?php echo base_url('offline_invoice'); ?>";
}
else if ('<?= $invoice_type ?>' == 2){
window.location.href = "<?php echo base_url('subscribers_list'); ?>";
}
// Handle success response
// For example, close modal and show success message
$('#voidReasonModal').modal('hide');
// alert('Invoice voided successfully!');
// You may want to refresh the page or update the UI accordingly
},
error: function(xhr, status, error) {
// Handle error response
console.error(error);
alert('Error occurred while voiding invoice.');
}
});
});
});
</script>
<script>
function validateForm() {
const fromDateInput = document.getElementById('fromsubcription');
const toDateInput = document.getElementById('tosubcription');
const invoiceDate = document.getElementById('invoiceDate');
if (invoiceDate.value.trim() === '') {
alert('Please select a invoice date.');
return false;
}
// Check if From Subscription field is empty
if (fromDateInput.value.trim() === '') {
alert('Please select a From Subscription date.');
return false;
}
// Check if To Subscription field is empty
if (toDateInput.value.trim() === '') {
alert('Please select a To Subscription date.');
return false;
}
// Additional validation logic if needed...
return true; // Form is valid
}
$('#saveButton').click(function() {
if (validateForm()) {
var formData = $("#myForm").serialize();
$.ajax({
type: 'POST',
data: formData, // Passing serialized form data
dataType: 'json',
url: '<?php echo base_url("update_approval_subscription"); ?>',
success: function(response) {
if (response.success) {
alert(response.message);
console.log(response);
setTimeout(function() {
window.location.href = "<?php echo base_url('subscribers_list'); ?>";
}, 250);
} else {
alert(response.message);
console.log(response); // Logging the response from backend
}
},
error: function(xhr, status, error) {
console.error(error); // Logging any errors
}
});
}});
</script>
<script>
// JavaScript code to handle voiding invoice and submitting reason
$(document).ready(function() {
// Handle clicking on the "Cancel" button
$('#cancelButton').click(function() {
var invoiceIds = <?= json_encode(isset($invoice_details['invoice_id']) ? $invoice_details['invoice_id'] : '') ?>;
$('#cancelReasonModal').modal('show');
$('#cancelReasonModal').find('#cancelReason').data('invoiceIds', invoiceIds); // Set the invoice_id(s) in the modal
});
// Handle submitting cancel reason
$('#submitCancelReason').click(function() {
var cancelReason = $('#cancelReason').val();
var invoiceIds = $('#cancelReason').data('invoiceIds'); // Get the invoice_id(s) from the modal
if (cancelReason === '') {
alert('Please enter a reason for Cancelling.');
return;
}
// Perform AJAX request to update status and reason
$.ajax({
type: 'POST',
url: '<?php echo base_url("updateInvoiceCancelStatus"); ?>', // Adjust the URL to match your controller route
data: {
invoice_id: invoiceIds,
cancel_reason: cancelReason
},
success: function(response) {
// Redirect to the invoice_list page upon successful cancellation
if ('<?= $invoice_type ?>' == 1){
window.location.href = "<?php echo base_url('offline_invoice'); ?>";
}
else if ('<?= $invoice_type ?>' == 2){
window.location.href = "<?php echo base_url('subscribers_list'); ?>";
}
},
error: function(xhr, status, error) {
// Handle error response
console.error(error);
alert('Error occurred while canceling invoice.');
}
});
});
});
</script>
<script>
$("#addressCopiedAsShipping").on("change", function() {
if ($(this).is(":checked")) {
var customerAddress1 = $("#baddress1").val();
var customerAddress2 = $("#baddress2").val();
var customerCountry = $("#bcountry").val();
var customerState = $("#bstate").val();
var customerCity = $("#bcity").val();
var customerPostalCode = $("#bpincode").val();
$("#saddress1").val(customerAddress1).prop("readonly", false);
$("#saddress2").val(customerAddress2).prop("readonly", false);
$("#scountry").val(customerCountry).prop("readonly", false);
$("#sstate").val(customerState).prop("readonly", false);
$("#scity").val(customerCity).prop("readonly", false);
$("#spincode").val(customerPostalCode).prop("readonly", false);
} else {
// Clear the billing address fields when the checkbox is unchecked
$("#saddress1").val("").prop("readonly", false);
$("#saddress2").val("").prop("readonly", false);
$("#scountry").val("").prop("readonly", false);
$("#sstate").val("").prop("readonly", false);
$("#scity").val("").prop("readonly", false);
$("#spincode").val("").prop("readonly", false);
}
});
$("#addressCopiedAsShippingModel").on("change", function() {
if ($(this).is(":checked")) {
var quick_customerAddress1 = $("#quick_billing_address").val();
var quick_customerCountry = $("#quick_billing_country").val();
var quick_customerState = $("#quick_billing_state").val();
var quick_customerCity = $("#quick_billing_city").val();
var quick_customerPostalCode = $("#quick_billing_postal_code").val();
$("#quick_shipping_address").val(quick_customerAddress1).prop("readonly", false);
$("#quick_shipping_country").val(quick_customerCountry).prop("readonly", false);
$("#quick_shipping_state").val(quick_customerState).prop("readonly", false);
$("#quick_shipping_city").val(quick_customerCity).prop("readonly", false);
$("#quick_shipping_postal_code").val(quick_customerPostalCode).prop("readonly", false);
} else {
// Clear the billing address fields when the checkbox is unchecked
$("#quick_shipping_address").val("").prop("readonly", false);
$("#quick_shipping_country").val("").prop("readonly", false);
$("#quick_shipping_state").val("").prop("readonly", false);
$("#quick_shipping_city").val("").prop("readonly", false);
$("#quick_shipping_postal_code").val("").prop("readonly", false);
}
});
function submitAddress() {
$('#storeBillingAddress').val("").prop('readonly',false);
$('#storeShippingAddress').val("").prop('readonly',false);
var cus_id = $('#customer_name').val() ? $('#customer_name').val() : $('#customerName').val();
var last_name = $("#hidden_last_name").val();
var first_name = $("#hidden_first_name").val();
var QB_AddressLine = $("#quick_billing_address").val();
var QB_Country = $("#quick_billing_country").val();
var QB_State = $("#quick_billing_state").val();
var QB_City = $("#quick_billing_city").val();
var QB_PostalCode = $("#quick_billing_postal_code").val();
var QS_AddressLine = $("#quick_shipping_address").val();
var QS_Country = $("#quick_shipping_country").val();
var QS_State = $("#quick_shipping_state").val();
var QS_City = $("#quick_shipping_city").val();
var QS_PostalCode = $("#quick_shipping_postal_code").val();
var shipping_address_name = $('#shipping_name').val();
var isValid = true;
var errorMessage = 'Please fill in the following required fields:\n\n';
if (cus_id === '') {
errorMessage += 'Please Select the Customer.\n';
isValid = false;
}
if (QB_AddressLine === '') {
errorMessage += 'Billing address,';
isValid = false;
}
if (QB_Country === '') {
errorMessage += 'Billing country,';
isValid = false;
}
if (QB_City === '') {
errorMessage += 'Billing city,';
isValid = false;
}
if (QB_PostalCode === '') {
errorMessage += 'Billing postal code,\n';
isValid = false;
}
if (QS_AddressLine === '') {
errorMessage += 'Shipping address,';
isValid = false;
}
if (QS_Country === '') {
errorMessage += 'Shipping country,';
isValid = false;
}
if (QS_City === '') {
errorMessage += 'Shipping city,';
isValid = false;
}
if (QS_PostalCode === '') {
errorMessage += 'Shipping postal code.';
isValid = false;
}
if (!isValid) {
alert(errorMessage);
} else {
var formData = {
customer_id :cus_id,
last_name: last_name,
first_name: first_name,
QB_address: QB_AddressLine,
QB_country: QB_Country,
QB_state: QB_State,
QB_city: QB_City,
QB_zip: QB_PostalCode,
QS_address: QS_AddressLine,
QS_country: QS_Country,
QS_state: QS_State,
QS_city: QS_City,
QS_zip: QS_PostalCode,
shipping_name: shipping_address_name
};
console.log("Before -",formData);
$.ajax({
type: "POST",
url: "<?php echo base_url('qucik_add_addresses'); ?>",
data: formData,
success: function(response) {
console.log(response);
if (response['data']['status']) {
alert(response['data']['message']);
$('#billing_shipping_addresses_modal').modal('hide');
var customerId = response['data']['cus_id'];
var QB_AddressId = response['data']['billing_addr_id'];
var QS_AddressId = response['data']['shipping_addr_id'];
if(QB_AddressId !== null ){
var quick_billing_Address =QB_AddressLine + ','+QB_City + ',' + QB_State + ',' +QB_Country + '-' + QB_PostalCode + '.' ;
$('#storeBillingAddress').empty();
$('#storeBillingAddress').val(quick_billing_Address).prop("readonly", true);
$('#hiddenBillingAddressId').val(QB_AddressId);
}
if(QS_AddressId !== null ){
var quick_shipping_Address = QS_AddressLine + ','+QS_City + ',' + QS_State + '-' +QS_Country + '-' + QS_PostalCode + '.' ;
$('#storeShippingAddress').empty();
var new_QS_ShippingAddrOption = $('<option>', {
value: QS_AddressId,
text: shipping_address_name+','+ QS_AddressLine,
selected: true
});
$('#storeShippingAddress').val(quick_shipping_Address).prop("readonly", true);
$('#loadShippingDropdown').empty().append(new_QS_ShippingAddrOption);
}
} else {
// Handle error response
alert(response['data']['message']);
}
},
error: function() {
alert("Error occurred while saving Addresses.");
}
});
$('#storeBillingAddress').prop('readonly',true);
$('#storeShippingAddress').prop('readonly',true);
$('#editAddressesCheckbox').click();
}
}
function hideBillingShippingModel(params) {
$('#editAddressesCheckbox').click();
}
// When discount is entered (keyup event)
$('#discount').keyup(function() {
// Ensure the discount type is set (percentage or fixed amount)
if ($('#discount-type').css('display') == 'none') {
$('#discount-type').val('%');
}
$('#discount-type').show();
$('#discount-type').attr('name', 'dis_type');
// Clear individual item discount fields
$('.item-discount-amount').val('');
var discountValue = $(this).val();
var discountType = $('#discount-type').val();
// Calculate the total amount of items (subtotal)
var totalAmount = 0;
$('.item-amount').each(function() {
totalAmount += parseFloat($(this).val()) || 0; // Ensure it's a number
});
// Apply the discount based on the discount type
var discountedAmount = 0;
if (discountType == '%') {
discountedAmount = totalAmount - (totalAmount * discountValue / 100);
} else {
discountedAmount = totalAmount - discountValue;
}
// Get the shipping charges and ensure it's a valid number
var shippingCharges = parseFloat($('#shippingCharges').val()) || 0;
// Final total after adding shipping charges
var finalTotal = discountedAmount + shippingCharges;
// Update the fields with the calculated values
$('#subtotal').val(totalAmount.toFixed(2)); // Subtotal remains as the sum of item amounts
$('#exacttotal').val(finalTotal.toFixed(2)); // Final total after discount and shipping
$('#grandtotal').val(finalTotal.toFixed(2)); // Grand total
$('#balanceAmount').val(finalTotal.toFixed(2)); // Balance amount (same as final total)
});
// When the discount type is changed (percentage or fixed)
$('#discount-type').change(function() {
var discountValue = $('#discount').val();
var discountType = $(this).val();
// Calculate the total amount of items (subtotal)
var totalAmount = 0;
$('.item-amount').each(function() {
totalAmount += parseFloat($(this).val()) || 0; // Ensure it's a number
});
// Apply the discount based on the discount type
var discountedAmount = 0;
if (discountType == '%') {
discountedAmount = totalAmount - (totalAmount * discountValue / 100);
} else {
discountedAmount = totalAmount - discountValue;
}
// Get the shipping charges and ensure it's a valid number
var shippingCharges = parseFloat($('#shippingCharges').val()) || 0;
// Final total after adding shipping charges
var finalTotal = discountedAmount + shippingCharges;
// Update the fields with the calculated values
$('#subtotal').val(totalAmount.toFixed(2)); // Subtotal remains as the sum of item amounts
$('#exacttotal').val(finalTotal.toFixed(2)); // Final total after discount and shipping
$('#grandtotal').val(finalTotal.toFixed(2)); // Grand total
$('#balanceAmount').val(finalTotal.toFixed(2)); // Balance amount (same as final total)
});
// When shipping charge is updated
$('#shippingCharges').keyup(function() {
// Recalculate the final total with shipping charge
var shippingCharges = parseFloat($(this).val()) || 0;
// Recalculate the discount and apply shipping
var discountValue = $('#discount').val();
var discountType = $('#discount-type').val();
// Calculate the total amount of items (subtotal)
var totalAmount = 0;
$('.item-amount').each(function() {
totalAmount += parseFloat($(this).val()) || 0; // Ensure it's a number
});
// Apply the discount based on the discount type
var discountedAmount = 0;
if (discountType == '%') {
discountedAmount = totalAmount - (totalAmount * discountValue / 100);
} else {
discountedAmount = totalAmount - discountValue;
}
// Final total after adding shipping charges
var finalTotal = discountedAmount + shippingCharges;
// Update the fields with the recalculated values
$('#exacttotal').val(finalTotal.toFixed(2)); // Final total after discount and shipping
$('#grandtotal').val(finalTotal.toFixed(2)); // Grand total
$('#balanceAmount').val(finalTotal.toFixed(2)); // Balance amount (same as final total)
});
</script>