the_mechanic/app/Views/invoice_form.php
venba-Inspriron-3558 78ba1fc582 CHANGE_Client Invoice
2025-11-13 15:28:52 +05:30

1831 lines
86 KiB
PHP
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php include('layout/header.php'); ?>
<style>
.fixed-dropdown-container {
/* position: fixed; */
/* top: 50px; Adjust as needed */
/* left: 50px; Adjust as needed */
width: 300px; /* Adjust as needed */
}
.form-control{
padding: 5px !important;
}
</style>
<style>
.select2-container--default .select2-results__option--highlighted[aria-selected]{
color:#ffffff;
background: #526dee!important;
}
.select2-container .select2-selection--single{
height: 36px;
border:1px solid #ced4da;
}
.select2-container--default .select2-selection--single .select2-selection__rendered{
line-height: 36px;
}
.select2-container--default .select2-selection--single .select2-selection__arrow{
top:4px;
}
.select2-container .select2-selection--multiple .select2-selection__choice{
padding: 5px 7px 5px 0 !important;
color: #000000;
}
.select2-container--default .select2-results__option{
border-bottom: 1px solid #dddddd;
}
.select2-container--default .select2-results__option[aria-selected=true]{
color: #000000;
background-color: #3efba4;
font-weight: 500;
border-bottom: 1px solid #747474;
}
</style>
<?php $status = $invoice['status'] ?? 'Draft'; ?>
<div class="row">
<div class="col-12">
<div class="page-title-box page-title-box-alt">
<h4 class="page-title"><?php echo $page_name?></h4>
<div class="page-title-right">
<a href="<?= base_url() . "invoices"; ?>" class="btn btn-secondary waves-effect">Cancel</a>
<ol class="breadcrumb m-0">
</li>
<!-- <li class="breadcrumb-item"><a href="javascript: void(0);">Tables</a></li>
<li class="breadcrumb-item active">Datatables</li> -->
</ol>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<form action="<?= base_url() . "invoices/save"; ?>" method="post" style="line-height:0.5;" id="invoicesForm">
<!-- 1st row -->
<div class="form-row">
<!-- invoice_id for add(empty) and edit(has value) -->
<input type="hidden" id="invoice_id" name="invoice_id" value="<?= isset($invoice['invoice_id']) ? $invoice['invoice_id'] : '' ?>" readonly>
<!-- type -->
<div class="form-group col-md-4">
<label for="type" class="col-form-label">Service Type<span class="text-danger">*</span></label>
<select class="form-control type-select " name="type" id="type" data-toggle="select2" required>
<option value="" <?= (isset($invoice['type']) && $invoice['type'] == '') ? 'selected' : '' ?>>Select Service Type</option>
<option value="General" <?= (isset($invoice['type']) && $invoice['type'] == "General") ?'selected' : '' ?>>General</option>
<option value="Complaints" <?= (isset($invoice['type']) && $invoice['type'] == "Complaints") ? 'selected' : '' ?>>Complaints</option>
</select>
</div>
<!-- vehicle_id and vehicle_reg_number as dropdown-->
<div class="form-group col-md-4">
<label for="vehicle_id" class="col-form-label">Vehicle<span
class="text-danger">*</span></label>
<?= isset($invoice['vehicle_id']) ? '' : '<i type="button" class="fe-plus-circle" id="addVehicleModalButton" style="font-size: 18px;" data-toggle="modal" data-target="#addVehicleModal" title="Add Vehicle"></i>' ?>
<select class="form-control vehicle-select SelExample" name="vehicle_id" id="vehicle_id"
<?= isset($invoice['vehicle_id']) ? 'disabled' : 'required="true"' ?>>
<?= isset($invoice['vehicle_id']) ? '' : '<option value="">Select a vehicle</option>' ?>
<?php foreach ($vehicle as $value) : ?>
<?php if ((int)$value["isactive"] === 1) : ?>
<option value="<?= $value["vehicle_id"] ?>"
<?= isset($invoice['vehicle_id']) && $invoice['vehicle_id'] == $value["vehicle_id"] ? 'selected' : '' ?>>
<?= $value["reg_no"]?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<!-- make and model as readonly-->
<div class="form-group col-md-4">
<label for="makeAndModel" class="col-form-label">Make and Model</label>
<input type="text" class="form-control" id="makeAndModel" readonly>
</div>
</div>
<!-- 2nd row -->
<div class="form-row">
<!-- client_name and client_id -->
<div class="form-group col-md-4">
<label for="client_id" class="col-form-label">Client Name<span
class="text-danger"></span></label>
<input type="text" class="form-control" name="client_name" placeholder="Client"
value="<?= isset($invoice['client_name']) ? $invoice['client_name'] : '' ?>" readonly>
<input type="hidden" id="client_id" name="client_id" value="<?= isset($invoice['client_id']) ? $invoice['client_id'] : '' ?>" readonly>
</div>
<!-- mobile_no and email -->
<div class="form-group col-md-4">
<label for="mobile_no" class="col-form-label">Mobile No<span
class="text-danger">*</span></label>
<input type="text" class="form-control" name="mobile_no" placeholder="Mobile"
value="<?= isset($invoice['mobile_no']) ? $invoice['mobile_no'] : '' ?>" maxlength="16"
minlength="6" onkeypress="return onlyNumbers(event)" readonly>
<input type="hidden" class="form-control" name="email" value="<?= isset($invoice['email']) ? $invoice['email'] : '' ?>" readonly>
</div>
<!-- status -->
<div class="form-group col-md-4">
<label for="status" class="col-form-label">Status
<?php if (isset($invoice['status']) && $invoice['status'] !== ''): ?>
<?php echo "( ". $invoice['status']." )"; ?>
<?php endif; ?></label>
<select class="form-control status-select status_class_for_change" name="status" data-toggle="select2" >
<?php if (isset($invoice['status'])): ?>
<?php if ($invoice['status'] === 'Cancelled'): ?>
<option value="Draft" <?= $invoice['status'] === 'Draft' ? 'selected' : '' ?> >Draft </option>
<option value="Approved" <?= $invoice['status'] === 'Approved' ? 'selected' : '' ?>>Approved</option>
<?php else: ?>
<option value>Select Status</option>
<option value="Approved" <?= $invoice['status'] === 'Approved' ? 'selected' : '' ?>>Approved</option>
<option value="Cancelled" <?= $invoice['status'] === 'Cancelled' ? 'selected' : '' ?>>Cancelled</option>
<?php endif; ?>
<?php else: ?>
<option value="Draft" selected>Draft</option>
<?php endif; ?>
</select>
</div>
<!-- mode of payment based on status -->
<?php if (isset($invoice['status']) && $invoice['status'] !== ''): ?>
<div class="form-group col-md-4" id="mode_of_payment_parent_div_id" <?= $invoice['status'] === 'Approved' ? '' : 'style="display:none;"' ?>>
<label for="mode_of_payment" class="col-form-label">Mode Of Payment<span class="text-danger">*</span>
<select class="form-control" name="mode_of_payment" id="mode_of_payment" >
<option value>Select Mode Of Payment</option>
<option value="online" <?= $invoice['mode_of_payment'] === 'online' ? 'selected' : '' ?> >Online</option>
<option value="cash" <?= $invoice['mode_of_payment'] === 'cash' ? 'selected' : '' ?>>Cash</option>
</select>
</div>
<?php endif; ?>
</div>
<!-- 3rd row -->
<div class="form-row">
<div class="form-group col-md-3">
<label for="Address" class="col-form-label">Address<span class="text-danger"></span></label>
<textarea class="form-control" name="billing_address" placeholder="Address"><?= isset($invoice['billing_address']) ? $invoice['billing_address'] : '' ?></textarea>
</div>
<div class="form-group col-md-3">
<label for="city" class="col-form-label">City<span
class="text-danger"></span></label>
<input type="text" class="form-control" name="city" placeholder="City"
value="<?= isset($invoice['billing_city']) ? $invoice['billing_city'] : 'Chennai' ?>">
</div>
<div class="form-group col-md-3">
<label for="status" class="col-form-label">State<span
class="text-danger"></span></label>
<input type="text" class="form-control" name="state" placeholder="State"
value="<?= isset($invoice['billing_state']) ? $invoice['billing_state'] : 'Tamil Nadu' ?>">
</div>
<div class="form-group col-md-3">
<label for="postalcode" class="col-form-label">Pin Code<span
class="text-danger"></span></label>
<input type="text" class="form-control" name="postalcode" placeholder="Pin Code"
value="<?= isset($invoice['billing_postal_code']) ? $invoice['billing_postal_code'] : '' ?>"
maxlength="6" minlength="6">
<input type="hidden" class="form-control" name="country" value="<?= isset($invoice['billing_country']) ? $invoice['billing_country'] : '' ?>" readonly>
</div>
<!-- <div class="form-group col-md-4" style="display: flex;align-items: center; gap: 8px;">
<input class="form-check-input" type="checkbox" name="update_client_address" style=" margin: 0;">
<label class="form-check-label" for="flexCheckDefault" style=" margin: 0;padding-left: 20px;">
Update client address
</label>
</div> -->
</div>
<div class="form-row" id="itemTableContainer">
<div class="form-group col-md-12">
<h4>Item Details</h4>
<br />
<table class="table table-bordered" id="itemTable">
<thead>
<tr>
<th>Item Details</th>
<th>Rate</th>
<th>Qty</th>
<th>Amt</th>
<th>Tax</th>
<th>Tax Amt</th>
<!-- <th>Labour Amt</th> -->
<!-- <th style="text-align: center !important" colspan="2">Discount</th> -->
<th>Tot Amt</th>
<th hidden></th>
<th></th>
</tr>
</thead>
<tbody>
<!-- Dynamically add rows for item details -->
<?php if (isset($invoice_child) && !empty($invoice_child)) : ?>
<?php foreach ($invoice_child as $ic) :
if ($ic['isactive'] == 1) : ?>
<tr>
<td style="width:30%;" class="fixed-dropdown-container">
<select class="form-control book-select SelExample" name="item_details[]"
required data-toggle="select2" id="" style="width: 249px !important;" onchange="addProductNamesId(this)" <?= $status !== 'Draft'? 'disabled' : '' ?>>
<option value="">Select a Product</option>
<option value="add_new_product">+ Add New Product</option>
<?php foreach ($product as $value) : ?>
<?php if ($value['per'] == 'ml') {
$value_ml = ' ('.$value['ml'].$value['per'].')';
} else {
$value_ml = '';
}
?>
<?php if ((int)$value["isactive"] === 1) : ?>
<option value="<?= $value["product_id"] ?>"
<?= isset($ic['product_id']) && $ic['product_id'] == $value["product_id"] ? 'selected' : '' ?>>
<?= $value["product_name"].$value_ml; ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</td>
<td style="width:12%;">
<input type="text" class="form-control item-rate" name="unit-price[]"
value="<?= isset($ic['net_price']) ? $ic['net_price'] : '' ?>" <?= $status !== 'Draft' ? 'readonly' : '' ?>>
</td>
<td style="width:10%;">
<input type="number" class="form-control item-quantity" name="quantity[]"
min="1"
value="<?= isset($ic['qty']) ? $ic['qty'] : '1' ?>" onchange="updateThirdColumnValue(this); updateTaxAmount(this)" onkeydown="return false;" <?= $status !== 'Draft' ? 'readonly' : '' ?>>
</td>
<td style="width:14%;">
<?php if (isset($ic['net_price']) && isset($ic['qty'])) {
$result = $ic['net_price'] * $ic['qty'] ;
echo '<input type="text" class="form-control item-result" value="' . $result . '" readonly>';
} ?>
</td>
<td style="width:8%;">
<input type="text" class="form-control item-tax" name="item-tax[]"
value="<?= isset($ic['tax']) ? $ic['tax'] : '' ?>" onchange="updateTaxAmount(this)" readonly>
</td>
<td style="width:13%;">
<?php if (isset($ic['tax']) && isset($result) ) {
$tax_amount= $result * $ic['tax'] / 100;
} else {
$tax_amount=0 ;
}
?>
<input type="text" class="form-control tax-amount" name="tax-amount[]" value="<?= number_format($tax_amount,2); ?>" readonly>
</td>
<!--<td style="width:10%;">
<select class="form-control item-discount-type" name="discount_type[]">
<option value="₹" <?= isset($ic['discount_type']) && $ic['discount_type'] == '₹' ? 'selected' : '' ?>>₹</option>
<option value="%" <?= isset($ic['discount_type']) && $ic['discount_type'] == '%' ? 'selected' : '' ?>>%</option>
</select>
</td> -->
<!-- <td style="width:10%;">
<input type="number" class="form-control item-labour" min="0" name="labour[]" value="<?= isset($ic['labour_cost']) ? $ic['labour_cost'] : 0 ?>">
</td> -->
<td style="width:13%;">
<input type="text" class="form-control item-amount" name="amount[]"
value="<?= isset($ic['amount']) ? $ic['amount'] : '' ?>" <?= $status !== 'Draft' ? 'readonly' : '' ?>>
</td>
<td hidden><input type="hidden"
value="<?= isset($ic['invoice_child_id']) ? $ic['invoice_child_id'] : '' ?>"
name="invoice_child_id[]"></td>
<td style="width:7%;">
<?php if ($status === 'Draft'): ?>
<center><i class="fa fa-trash remove-item"></i></center>
<?php endif; ?>
</td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
<!-- You can add more rows as needed using JavaScript -->
</tbody>
</table>
<div class="form-group text-right m-b-0">
<!-- Show the "Add More Item" button only if invoice_type is not 1 -->
<?php if ($status === 'Draft') : ?>
<a class="btn" id="addItem">
<h4><i class="fa fa-plus" aria-hidden="true"></i> Add Product</h4>
</a>
<?php endif; ?>
</div>
</div>
</div>
<div class="form-row">
<div class="offset-md-7 col-md-5 card">
<div class="card-body">
<h4>Calculation</h4>
<div class="form-group">
<label for="subtotal">Subtotal</label>
<input type="text" class="form-control" id="subtotal" name="sub_total"
value="<?= isset($invoice['subtotal']) ? $invoice['subtotal'] : '' ?>" readonly>
</div>
<div class="form-group">
<label for="invoicetax">Tax Amount<span id=""></span></label>
<input type="text" class="form-control" id="invoicetax" name="invoice_tax" readonly
value="<?= isset($invoice['tax']) ? $invoice['tax'] : '' ?>">
</div>
<div class="form-group">
<label for="grandtotal">Total Amount</label>
<input type="text" class="form-control" id="grandtotal" name="grand_total" readonly
value="<?= isset($invoice['total']) ? $invoice['total'] : '' ?>">
</div>
<div class="form-group">
<label for="discount">Discount Amount</label>
<input type="number" class="form-control" id="discount" name="discount" onchange="calculateBalance()" min="0" value="<?= isset($invoice['discount']) ? $invoice['discount'] : '' ?>" >
</div>
<div class="form-group">
<label for="advance">Paid Advance</label>
<input type="number" class="form-control" id="paid_advance" name="paid_advance" onchange="calculateBalance()" min="0" value="<?= isset($invoice['paid_advance']) ? $invoice['paid_advance'] : '0.00' ?>" >
</div>
<div class="form-group">
<label for="balance">Balance Amount</label>
<input type="text" class="form-control" id="balance" readonly >
</div>
</div>
</div>
</div>
<h4 class="header-title">Terms & Condition :</h4><br>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputPassword4" class="col-form-label">Terms & Condition</label>
<textarea class="form-control" name="terms_condition" placeholder="Terms & Condition"><?= isset($invoice['terms_condition']) ? $invoice['terms_condition'] : 'Please check the products properly before purchase. Products once sold cannot be returned.' ?></textarea>
</div>
</div>
<?php if (!isset($invoice['status']) || $invoice['status'] !== 'Approved') : ?>
<button type="submit" id="editaddbutton" class="btn btn-primary" style="float:right;">Submit</button>
<?php endif; ?>
</form>
</div>
</div>
</div>
</div>
<?php include('layout/footer.php'); ?>
</div>
<div class="modal fade" id="addVehicleModal" tabindex="-1" role="dialog" aria-labelledby="addVehicleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addVehicleModalLabel">Add New Vehicle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-row">
<div class="form-group col-md-6">
<!-- <div class="form-group"> -->
<label for="inputPassword4" class="col-form-label">Make</label>
<select class="form-control SelExample" name="make" id="make"
<?= isset($vehicle['make']) ? '' : 'required' ?>>
<?= isset($vehicle['make']) ? '' : '<option value="">Select a Make</option>' ?>
<?php foreach ($makeData as $value) : ?>
<?php if ((int)$value["isactive"] === 1) : ?>
<option value="<?= $value["make_id"] ?>"
<?= isset($vehicle['make']) && $vehicle['make'] == $value["make_id"] ? 'selected' : '' ?>>
<?= $value["make"]; ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-6">
<label for="inputPassword4" class="col-form-label">Model</label>
<select class="form-control SelExample" name="model" id="model"
<?= isset($vehicle['model']) ? '' : 'required' ?>>
<?php if (isset($vehicle["model_name"])) : ?>
<option value="<?= $vehicle["model"] ?>">
<?= $vehicle["model_name"]; ?>
</option>
<?php endif; ?>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputPassword4" class="col-form-label">Reg Number</label>
<input type="text" class="form-control" name="reg_no" id="reg_no" placeholder="Reg Number"
value="<?= isset($vehicle['reg_no']) ? $vehicle['reg_no'] : '' ?>" required>
</div>
</div>
<div class="form-row">
<input type="text" value="select" id="formType" hidden>
<div class="form-group col-md-12 select">
<label for="clientName">Client Name</label>
<i type="button" class="fe-user-plus" id="createClient" style="font-size: 18px;"></i>
<select class="form-control cleint-select SelExample" id="clientName" required>
<option value="">Select a Client</option>
<?php foreach ($client as $value) : ?>
<option data-id="<?= $value["mobile_no"] .' - '. $value["client_name"]; ?>"
value="<?= $value["client_id"] ?>">
<?= $value["client_name"]; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-12 select">
<label for="clientMobile">Mobile</label>
<input type="text" class="form-control" id="clientMobile" placeholder="Enter mobile number"
maxlength="16" minlength="6" onkeypress="return onlyNumbers(event)" required>
</div>
<div class="form-group col-md-12 create" style="display:none;">
<label for="create-clientName">Client Name</label>
<i type="button" class="fe-user-check" id="selectClient" style="font-size: 18px;"></i>
<input type="text" class="form-control" id="create-clientName"
placeholder="Enter client name" required>
</div>
<div class="form-group col-md-6 create" style="display:none;">
<label for="create-clientMobile">Mobile</label>
<input type="text" class="form-control" id="create-clientMobile"
placeholder="Enter mobile number" maxlength="16" minlength="6"
onkeypress="return onlyNumbers(event)" required>
</div>
<div class="form-group col-md-6 create" style="display:none;">
<label for="create-clientType">Client Type</label>
<select class="form-control status-select" id="create-clientType" required>
<option value="">Select a Type</option>
<option value="Direct">Direct</option>
<option value="Mechanic">Mechanic</option>
<option value="Exp">Exp</option>
</select>
</div>
</div>
</form>
</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="saveVehcileBtn">Save Vehicle</button>
</div>
</div>
</div>
</div>
<!-- Add Product Modal -->
<!-- <div class="modal fade" id="addProductModal" tabindex="-1" role="dialog" aria-labelledby="addProductModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addProductModalLabel">Add Product</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">Save</button>
</div>
</form>
</div>
</div>
</div> -->
<!-- ADD PRODUCT MODAL -->
<div class="modal fade" id="addProductModal" tabindex="-1" role="dialog" aria-labelledby="addProductModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addProductModalLabel">Add Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<form id="quickproductForm" method="post" action="<?= base_url('quick_add') ?>">
<div class="modal-body">
<!-- PRODUCT DETAILS -->
<h5 class="header-title">Product Details :</h5>
<div class="form-row">
<div class="form-group col-md-6">
<label for="cubic_centimeter_id" class="col-form-label">Capacity in Cubic Centimeter (C.C.)<span class="text-danger">*</span></label>
<select class="form-control SelExample" id="CCselect" name="cubic_centimeter_id[]" required multiple>
<option value="">Select a Capacity (in C.C.)</option>
<?php foreach ($capacity as $value): ?>
<option value="<?= $value['id'] ?>"><?= $value['value'] ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-6">
<label for="product_name" class="col-form-label">Product Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" name="product_name" placeholder="Product Name" required>
</div>
</div>
<!-- PRICING -->
<h5 class="header-title mt-3">Pricing Information :</h5>
<div class="form-row">
<div class="form-group col-md-4">
<label class="product_total_amount">Unit Price (Including Tax)<span class="text-danger">*</span></label>
<input type="number" step="0.01" class="form-control" name="product_total_amount" required>
</div>
<div class="form-group col-md-4">
<label class="product_tax">Tax<span class="text-danger">*</span></label>
<select class="form-control" name="product_tax" required>
<!-- <option value="">Select Tax</option> -->
<option value="18">18%</option>
<option value="28">28%</option>
</select>
</div>
<div class="form-group col-md-4">
<label class="product_unit_price">Unit Price<span class="text-danger">*</span></label>
<input type="text" class="form-control" name="product_unit_price" required readonly>
</div>
</div>
<!-- STOCK INFO -->
<h5 class="header-title mt-3">Stock Information :</h5>
<div class="form-row">
<div class="form-group col-md-3">
<label class="col-form-label">Unit of Measurement<span class="text-danger">*</span></label>
<select class="form-control" id="product_per" name="product_per" required>
<!-- <option value="">Select</option> -->
<option value="Nos" selected>No's</option>
<option value="ml">ML</option>
<option value="litre">Litre</option>
<option value="barrel">Barrel</option>
<option value="box">Box</option>
</select>
</div>
<div class="form-group col-md-3" id="ml_div" hidden >
<label class="product_ml">ML<span class="text-danger">*</span></label>
<select name="product_ml" id="product_ml" class="form-control SelExample select2-hidden-accessible" <?= (isset($products['per']) && $products['per'] == 'ml') ? 'required' : '' ?>>
<option value>Select ML</option>
<?php
$selectedValue = isset($products['ml']) ? $products['ml'] : 0;
for ($i = 25; $i <= 950; $i += 25) {
$selected = ($selectedValue == $i) ? 'selected' : '';
echo "<option value=\"$i\" $selected>$i</option>";
}
?>
</select>
</div>
<div class="form-group col-md-3" id="product_box_div" hidden >
<label class="col-form-label">No Of Box<span class="text-danger">*</span></label>
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')" name="product_box" id="product_box" class="form-control" value="<?= isset($products['box']) ? $products['box'] : '' ?>" <?= (isset($products['per']) && $products['per'] == 'box') ? 'required' : '' ?>>
</div>
<div class="form-group col-md-3" id="product_qty_per_box_div" hidden >
<label class="col-form-label">Qty In Box<span class="text-danger">*</span></label>
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')" name="product_qty_per_box" id="product_qty_per_box" class="form-control" value="<?= isset($products['qty_per_box']) ? $products['qty_per_box'] : '' ?>" <?= (isset($products['per']) && $products['per'] == 'box') ? 'required' : '' ?>>
</div>
<div class="form-group col-md-3" id="product_barrel_div" hidden >
<label class="col-form-label">No Of Barrel<span class="text-danger">*</span></label>
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')" name="product_barrel" id="product_barrel" class="form-control" value="<?= isset($products['barrel']) ? $products['barrel'] : '' ?>" <?= (isset($products['per']) && $products['per'] == 'barrel') ? 'required' : '' ?>>
</div>
<div class="form-group col-md-3" id="product_ltr_per_barrel_div" hidden >
<label class="col-form-label">Liters In Barrel<span class="text-danger">*</span></label>
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')" name="product_ltr_per_barrel" id="product_ltr_per_barrel" class="form-control" value="<?= isset($products['ltr_per_barrel']) ? $products['ltr_per_barrel'] : '' ?>" <?= (isset($products['per']) && $products['per'] == 'barrel') ? 'required' : '' ?>>
</div>
<div class="form-group col-md-3">
<label class="col-form-label">Qty in Stock<span class="text-danger">*</span></label>
<input type="text" class="form-control" name="product_qty_stock" id="product_qty_stock" required>
</div>
</div>
<!-- Additional -->
<h5 class="header-title mt-3">Additional Information :</h5>
<div class="form-row">
<div class="form-group col-md-6">
<label for="PCselect" class="col-form-label">Product Category</label>
<select class="form-control SelExample" id="PCselect" name="product_category">
<option value="">Select Category</option>
<?php foreach ($productcategory as $category): ?>
<?php if ((int)$category['isactive'] == 1): ?>
<option value="<?= $category['product_category_name'] ?>">
<?= $category['product_category_name']; ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-6">
<label for="product_manufacturer" class="col-form-label">Manufacturer</label>
<select class="form-control SelExample" id="product_manufacturer" name="product_manufacturer">
<option value="">Select a Manufacturer</option>
<?php foreach ($manufacturers as $value): ?>
<option value="<?= $value['manufacturer_id'] ?>">
<?= $value['manufacturer_name'] ?>
</option>
<?php endforeach; ?>
</select>
</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">Submit</button>
</div>
</form>
</div>
</div>
</div>
<?php $product_json = json_encode($product); ?>
<script>
productarray = [];
var products = <?php echo $product_json; ?>; // declare globally, only once
$(document).ready(function() {
// Event listener for vehicle selection change
$('.vehicle-select').change(function() {
var vehicleId = $(this).val();
console.log(":)",vehicleId);
$('input[id="makeAndModel"],input[name="client_id"], input[name="client_name"], textarea[name="billing_address"], input[name="city"], input[name="state"], input[name="country"], input[name="mobile_no"], input[name="email"], input[name="postalcode"]').val('');
if (vehicleId !== '') {
// Find the selected vehicle
var selectedVehicle = vehicles.find(function(vehicle) {
return vehicle.vehicle_id == vehicleId;
});
// Extract makeId and modelId from the selected vehicle
var makeId = selectedVehicle.make;
var modelId = selectedVehicle.model;
// Fetch make and model information
fetchMakeAndModel(makeId, modelId);
}
});
// Edit scenario: Populate make and model based on stored vehicle ID
var storedVehicleId = "<?php echo isset($invoice['vehicle_id']) ? $invoice['vehicle_id'] : ''; ?>";
if (storedVehicleId !== '') {
// Find the selected vehicle from the vehicles array
var selectedVehicle = vehicles.find(function(vehicle) {
return vehicle.vehicle_id == storedVehicleId;
});
// Extract makeId and modelId from the selected vehicle
var makeId = selectedVehicle.make;
var modelId = selectedVehicle.model;
// Fetch make and model information
fetchMakeAndModel(makeId, modelId);
}
});
$(document).ready(function() {
function validateProductAdded() {
var rowCount = $('#itemTable tbody tr').length;
if (rowCount < 1) {
toastr.warning("Please add at least one product.");
// alert("Please add at least one product.");
return false;
}
return true;
}
// Event listener for form submission
$('form').submit(function() {
return validateProductAdded();
});
// Function to calculate amount based on rate and quantity
function calculateAmount(row) {
// Retrieve CGST and SGST values from the database for the selected product
var productId = $(row).find('select[name="item_details[]"]').val();
var product = products.find(function(item) {
return item.product_id == productId;
});
var cgst = parseFloat(product.cgst);
var sgst = parseFloat(product.sgst);
var tax = cgst + sgst;
$(row).find('.item-tax').val(tax);
var rate = $(row).find('.item-rate').val();
var quantity = $(row).find('.item-quantity').val();
// var labour = $(row).find('.item-labour').val();
var amount = rate * quantity;
var taxamount = amount * tax / 100;
$(row).find('.tax-amount').val(parseFloat(taxamount).toFixed(2));
var finalamt = amount + taxamount;
// var finalamt = amount + taxamount + labour;
$(row).find('.item-amount').val(parseFloat(finalamt).toFixed(2));
}
function calculateTotalAmount(row) {
// Retrieve CGST and SGST values from the database for the selected product
var productId = $(row).find('select[name="item_details[]"]').val();
var product = products.find(function(item) {
return item.product_id == productId;
});
var cgst = parseFloat(product.cgst);
var sgst = parseFloat(product.sgst);
var tax = cgst + sgst;
var quantity = $(row).find('.item-quantity').val();
var final_amount = $(row).find('.item-amount').val();
// var labour_amount = $(row).find('.item-labour').val();
var taxRate = tax/100;
// console.log(taxRate);
var amt = final_amount/((1+taxRate));
// var with_lbr_amt = amt-labour_amount;
$(row).find('.item-result').val(parseFloat(amt).toFixed(2));
// $(row).find('.item-result').val(parseFloat(with_lbr_amt).toFixed(2));
var taxAmount = final_amount-amt;
// console.log(taxAmount);
$(row).find('.tax-amount').val(parseFloat(taxAmount).toFixed(2));
var rate = amt / quantity;
// console.log(rate);
$(row).find('.item-rate').val(parseFloat(rate).toFixed(2));
}
$('#quickproductForm').on('submit', function(e) {
e.preventDefault();
let formValid = true;
let firstInvalidField = null;
// Loop through all required fields
// $('#quickproductForm [required]').each(function() {
// const $field = $(this);
// const value = $field.val().trim();
// const label = $field.closest('.form-group').find('label').text().replace('*', '').trim();
// if (value === '') {
// toastr.warning(label + ' is required');
// formValid = false;
// firstInvalidField = firstInvalidField || $field;
// return false; // break loop
// }
// });
$('#quickproductForm [required]').each(function() {
const $field = $(this);
let value = $field.val();
// If multiple select → val() is an array
if (Array.isArray(value)) {
if (value.length === 0) value = '';
}
// If single value → make sure it's a string
if (typeof value === 'string') {
value = value.trim();
}
const label = $field.closest('.form-group').find('label').text().replace('*', '').trim();
if (value === '') {
toastr.warning(label + ' is required');
formValid = false;
firstInvalidField = firstInvalidField || $field;
return false; // break loop
}
});
// Focus first invalid field
if (!formValid) {
if (firstInvalidField) firstInvalidField.focus();
return;
}
// Disable button immediately
const $submitBtn = $('#quickproductForm button[type="submit"]');
$submitBtn.prop('disabled', true);
// If validation passes → submit via AJAX
$.ajax({
url: '<?= base_url("quick_add") ?>',
type: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
toastr.success(response.message);
$('#quickproductForm')[0].reset(); // Reset form safely
$('#quickproductForm select').val('').trigger('change');
$('#addProductModal').modal('hide');
products.push(response.data);
// Add new option to table dropdown
var value_ml = response.data.per === 'ml' ? ' (' + response.data.ml + response.data.per + ')' : '';
var displayText = response.data.product_name + value_ml;
var newOption = $('<option>', {
'data-id': response.data.product_name,
'value': response.data.product_id,
'text': displayText,
'selected': true
});
var addproductIndex = localStorage.getItem('add_product_index');
var $dropdown = addproductIndex !== null
? $('#itemTable tbody tr').eq(addproductIndex).find('.book-select')
: $('#itemTable tbody tr:last .book-select');
if ($dropdown.length) {
$dropdown.append(newOption);
$dropdown.val(response.data.product_id).trigger('change');
localStorage.removeItem('add_product_index');
try {
addProductNamesId($dropdown[0]);
} catch (err) {
console.error('Error in addProductNamesId:', err);
}
}
} else {
toastr.error(response.message);
}
},
error: function(xhr, status, error) {
console.error('AJAX Error:', error);
toastr.error('Something went wrong! Try again.');
},
complete: function() {
$submitBtn.prop('disabled', false);
}
});
});
// Event listener for product selection
$(document).on('change', 'select[name="item_details[]"]', function() {
var productId = $(this).val();
console.log('Selected productId:', productId);
console.log('Products array:', products); // ✅ this will now show the updated array
var product = products.find(item => item.product_id == productId || item.product_id == parseInt(productId));
var quantity = $(this).closest('tr').find('.item-quantity').val(1);
// if(productId == 0){
// $(this).closest('tr').find('.item-quantity').prop('readonly', true);
// $(this).closest('tr').find('.item-amount').prop('readonly', false);
// }
var cgst = parseInt(product.cgst);
var sgst = parseInt(product.sgst);
var totalTax = cgst + sgst;
var total_tax_amount = product.unit_price * totalTax / 100;
var total_tax_amount = parseFloat(total_tax_amount).toFixed(2);
// console.log("product.qty_stock : ",product.qty_stock);
// $(this).closest('tr').find('.item-quantity').attr('max', product.qty_stock);
// Gowtham TL told to me => Dont restrict the max quantity based on the products available quantity.
// Access unit price from product and set it as rate
var unitPrice = parseFloat(product.unit_price).toFixed(2);
$(this).closest('tr').find('.item-rate').val(unitPrice);
$(this).closest('tr').find('.item-result').val(unitPrice);
$(this).closest('tr').find('.tax-amount').val(total_tax_amount);
// Calculate amount and update amount input field
calculateAmount($(this).closest('tr'));
updateCalculations();
});
$(document).on('keyup', '.item-amount', function()
{
// var total_amount = $(this).val();
// var totalTax = $(this).closest('tr').find('.item-tax').val();
// var unitPrice = total_amount / parseFloat((totalTax / 100) + 1);
// var unitPrice = parseFloat(unitPrice).toFixed(2);
// var taxAmt = total_amount - unitPrice;
// var taxAmt = parseFloat(taxAmt).toFixed(2)
// $(this).closest('tr').find('.tax-amount').val(taxAmt);
// $(this).closest('tr').find('.item-rate').val(unitPrice);
// $(this).closest('tr').find('.item-result').val(unitPrice);
calculateTotalAmount($(this).closest('tr'));
updateCalculations();
});
// Event listener for quantity change
$(document).on('input', '.item-quantity', function() {
calculateAmount($(this).closest('tr'));
updateCalculations(); // Added for updating calculations when quantity changes
});
// Function to calculate subtotal
function calculateSubtotal() {
var subtotal = 0;
$('.item-amount').each(function() {
// subtotal += parseFloat($(this).val()) || 0;
var value1 = $(this).val();
var qty = $(this).parent().parent().find('.item-quantity').val();
var rate = $(this).parent().parent().find('.item-rate').val();
// console.log(value1);
// console.log(value2);
subtotal += qty * rate;
});
return subtotal;
}
// Function to calculate total tax
function calculateTax() {
var tax = 0;
$('.item-tax').each(function() {
var taxPercentage = parseFloat($(this).val()) || 0;
// console.log(taxPercentage);
var amount = parseFloat($(this).closest('tr').find('.item-amount').val()) || 0;
// console.log(amount);
var qty = parseFloat($(this).closest('tr').find('.item-quantity').val()) || 0;
// console.log(qty);
var rate = parseFloat($(this).closest('tr').find('.item-rate').val()) || 0;
var taxamount = rate * qty;
// console.log(taxamount);
var taxValue = (taxPercentage / 100) * taxamount; // Convert percentage to absolute value
tax += taxValue;
});
return tax;
}
// Function to calculate total discount
// function calculateDiscount() {
// var totalDiscount = 0;
// $('.item-discount-amount').each(function(index, element) {
// var discountAmount = parseFloat($(element).val()) || 0;
// var discountType = $(element).closest('tr').find('.item-discount-type').val();
// if (discountType === '%') {
// var rate = $(element).closest('tr').find('.item-rate').val();
// var quantity = $(element).closest('tr').find('.item-quantity').val();
// var amount = rate * quantity;
// discountAmount = amount * discountAmount / 100;
// }
// totalDiscount += discountAmount;
// });
// return totalDiscount;
// }
// Function to calculate total
function calculateTotal() {
var subtotal = calculateSubtotal();
var total_tax_amount = $('#invoicetax').val();
// console.log(total_tax_amount + parseInt(subtotal));
var total = parseFloat(total_tax_amount) + parseFloat(subtotal);
// return total;
return Math.round(total);
}
// Update subtotal, tax, and total
function updateCalculations() {
$('#subtotal').val(calculateSubtotal().toFixed(2));
$('#invoicetax').val(calculateTax().toFixed(2));
// $('#discount').val(calculateDiscount().toFixed(2));
$('#grandtotal').val(calculateTotal().toFixed(2));
calculateBalance();
}
// Event listener for discount change
$(document).on('input', '.item-discount-amount, .item-discount-type', function() {
updateCalculations();
});
// Calculate initial values on page load
updateCalculations();
// Event listener for "Add More Item" button
$('#addItem').click(function() {
selected_pr = [];
$('tr .form-control.book-select.SelExample.select2-hidden-accessible').each(function() {
var rowProductid = $(this).val();
selected_pr.push(rowProductid);
});
console.log(productarray);
if(productarray == 'No Product'){
toastr.warning("First Add the Product!");
}else if (productarray.length > 0) {
var newRow = '<tr>' +
`<td style="width:30%" class="fixed-dropdown-container">
<select class="form-control book-select SelExample" name="item_details[]" required data-toggle="select2" style="width: 2px !important;" onchange="addProductNamesId(this)">
<option value="">Select a Product</option>
<option value="add_new_product">+ Add New Product</option>`;
for (var i = 0; i < productarray.length; i++) {
var product = productarray[i];
// console.log("product",product);
var value_ml ='';
if (product.per == 'ml') {
value_ml = " ("+product.ml+product.per+")";
}
var product = productarray[i];
if(!selected_pr.includes(product.product_id))
{
newRow += '<option value="' + product.product_id + '" >' + product.product_name + value_ml +
'</option>';
}
}
newRow += '</select></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-rate" name="unit-price[]" /></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="1" max="" name="quantity[]" onchange="updateThirdColumnValue(this); updateTaxAmount(this)" onkeydown="return false;" /></td>' +
'<td style="width:14%;"><input type="text" class="form-control item-result" readonly /></td>' +
'<td style="width:8%;"><input type="text" class="form-control item-tax" name="item-tax[]" readonly /></td>' +
'<td style="width:13%;"><input type="text" class="form-control tax-amount" name="tax-amount[]" readonly /></td>' +
'<td style="width:13%;"><input type="text" class="form-control item-amount" name="amount[]" /></td>' +
'<td hidden><input type="hidden"></td>' +
'<td><center><i class="fa fa-trash remove-item"></i></center></td>' +
'</tr>';
$('#itemTable tbody').append(newRow);
$('#discount').val(0);
$('#paid_advance').val(0);
initializeSelect2();
updateCalculations();
initializeRowCalculations(newRow);
}else{
toastr.warning("First Choose the Vehicle!");
}
});
// Event listener for removing item
$(document).on('click', '.remove-item', function() {
$(this).closest('tr').remove();
updateCalculations(); // Added for updating calculations when an item is removed
});
});
function initializeRowCalculations(row) {
calculateAmount(row);
updateCalculations();
}
// Event listener for removing item
// Event listener for removing item
$(document).on('click', '.remove-item', function() {
var InvoiceChildId = $(this).closest('tr').find('input[name="invoice_child_id[]"]').val();
// AJAX request to delete the invoice child
$.ajax({
url: '<?php echo base_url()."invoices/delete/child"?>',
method: 'POST',
data: {
invoice_child_id: InvoiceChildId
},
success: function(response) {
// Check if the deletion was successful
if (response.success) {
// If successful, remove the row from the table
$(this).closest('tr').remove();
updateCalculations(); // Update calculations after removing the row
calculateBalance();
} else {
// If not successful, display an error message
// alert('Error occurred while deleting the item.');
}
},
error: function(xhr, status, error) {
console.error('Error occurred while deleting the item:', error);
}
});
});
$(document).ready(function() {
// Event listener for customer selection change
$('.vehicle-select').change(function() {
$('tbody').empty();
var vehicleId = $(this).val();
if (vehicleId !== '') {
// Find the selected client in the client data
var selectedClient = vehicles.find(function(vehicle) {
return vehicle.vehicle_id == vehicleId;
});
console.log(selectedClient);
$('input[name="client_id"]').val(selectedClient.client_id);
$('input[name="client_name"]').val(selectedClient.client_name);
// $('input[name="billing_address"]').val(selectedClient.address);
$('textarea[name="billing_address"]').val(selectedClient.address);
$('input[name="city"]').val(selectedClient.city);
$('input[name="state"]').val(selectedClient.state);
$('input[name="country"]').val(selectedClient.country);
$('input[name="mobile_no"]').val(selectedClient.mobile_no);
$('input[name="email"]').val(selectedClient.email);
$('input[name="postalcode"]').val(selectedClient.postal_code);
}
});
});
</script>
<script>
$(document).ready(function() {
// Event listener for customer selection change
$('.cleint-select').change(function() {
var clientId = $(this).val();
// console.log(vehicleId);
if (clientId !== '') {
// Find the selected client in the client data
var selectedClients = clients.find(function(client) {
return client.client_id == clientId;
});
// Populate the billing address, city, state, country, and postal code fields
$('input[id="clientMobile"]').val(selectedClients.mobile_no);
$('input[id="clientEmail"]').val(selectedClients.email);
}
});
});
</script>
<script>
// Define the clients array and populate it with data
var vehicles = <?php echo json_encode($vehicle); ?>;
var clients = <?php echo json_encode($client); ?>;
</script>
<script>
function onlyNumbers(event) {
var charcode;
charcode = event.which || event.keyCode;
if (charcode >= 48 && charcode <= 57) return true;
return false;
}
</script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script>
$(document).ready(function() {
// Initialize select2
$(".SelExample").select2({
// dropdownParent: $('.fixed-dropdown-container')
});
});
function initializeSelect2() {
$('.SelExample').select2({
// dropdownParent: $('.fixed-dropdown-container'),
width: '150px'
});
}
</script>
<script>
$(document).ready(function() {
// AJAX request to save client
$('#saveVehcileBtn').click(function() {
var formType = $('#formType').val();
console.log(formType);
var reg_no = $('#reg_no').val();
var model = $('#model').val();
var make = $('#make').val();
var clientName = $('#clientName').val();
var clientMobile = $('#clientMobile').val();
var createclientName = $('#create-clientName').val();
var createclientMobile = $('#create-clientMobile').val();
var createclientType = $('#create-clientType').val();
if (formType == 'select') {
var ifStatementCondition ="clientName !== '' && clientMobile !== '' && reg_no !== '' && model !== '' && make !== ''";
} else {
var ifStatementCondition ="createclientName !== '' && createclientMobile !== '' && createclientType !== '' && reg_no !== '' && model !== '' && make !== ''";
}
const button = $('#saveVehcileBtn');
button.prop('disabled', true).text('Processing...');
if (reg_no) {
$.ajax({
url: '<?= base_url("checkRegisterNo") ?>', // URL to your controller method for fetching models
type: 'POST',
dataType: 'json',
data: { register_number: reg_no },
success: function(response) {
if (response) {
$('#reg_no').val("");
toastr.warning("Register Number Already Added!");
button.prop('disabled', false).text('Save Vehicle');
}else{
if (eval(ifStatementCondition)) {
// Send AJAX request to save the client
$.ajax({
url: '<?php echo base_url().'save_vehicle'?>', // URL to your save_client method
method: 'POST',
data: {
client_id: clientName,
mobile_no: clientMobile,
reg_no: reg_no,
model: model,
make: make,
createclientName: createclientName,
createclientMobile: createclientMobile,
createclientType: createclientType,
formType: formType,
},
success: function(response) {
if (response.success && response.code == 200 ) {
toastr.success("Vehicle saved successfully!");
localStorage.setItem('vehicle_id',response.vehicle_id);
$('#addVehicleModal').modal('hide');
window.location.reload();
}else if (response.success && response.code == 404 ) {
$('#'+response.field).val("");
toastr.warning(response.message);
button.prop('disabled', false).text('Save Vehicle');
}else {
toastr.warning("Failed to save vehicle. Please try again");
button.prop('disabled', false).text('Save Vehicle');
}
},
error: function(xhr, status, error) {
console.error('Error occurred while saving vehicle:', error);
toastr.warning("Failed to save vehicle. Please try again");
button.prop('disabled', false).text('Save Vehicle');
}
});
} else {
toastr.warning("Please Fill All Data");
button.prop('disabled', false).text('Save Vehicle');
}
}
},
error: function(xhr, status, error) {
console.error(error); // Log any errors to the console
button.prop('disabled', false).text('Save Vehicle');
}
});
}
});
});
</script>
<script>
$(".SelExample").select2({
// dropdownParent: $('.fixed-dropdown-container')
});
// Event listener for change in make select dropdown
$("#make").on('change', function() {
var selected_makes = $(this).val(); // Get an array of selected make IDs
// AJAX request to fetch models based on selected make IDs
$.ajax({
url: '<?= base_url("fetch_models") ?>', // URL to your controller method for fetching models
type: 'POST',
dataType: 'json',
data: {
selected_makes: [selected_makes]
},
success: function(response) {
// Clear existing options in model select dropdown
$("#model").empty();
$("#model").append('<option value=""> Select a Model </option>');
// Populate model select dropdown with fetched models
$.each(response, function(index, model) {
$("#model").append('<option value="' + model.model_id + '">' + model
.model_name + '</option>');
});
// Refresh select2 to reflect changes
$("#model").trigger('change');
},
error: function(xhr, status, error) {
console.error(error); // Log any errors to the console
}
});
});
document.getElementById('reg_no').addEventListener('input', function(event) {
var inputText = event.target.value;
event.target.value = inputText.toUpperCase();
});
</script>
<script>
$(document).on('click', '#createClient', function() {
$('.create').show();
$('.select').hide();
$('#formType').val('create');
$('#clientName').val('');
// $('.select2-selection__rendered').html('');
$('#clientMobile').val('');
});
$(document).on('click', '#selectClient', function() {
$('.select').show();
$('.create').hide();
$('#formType').val('select');
$('#create-clientName').val('');
$('#create-clientMobile').val('');
$('#create-clientType').val('');
});
</script>
<style>
.select2-container--default .select2-results__option--highlighted[aria-selected] {
color: #ffffff;
background: #526dee !important;
}
.select2-container .select2-selection--single {
height: 36px;
border: 1px solid #ced4da;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
line-height: 36px;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
top: 4px;
}
</style>
<script>
// Assuming you have an edit button with an ID 'editButton'
$('#editaddbutton').click(function() {
// Enable the vendor dropdown
$('#vehicle_id').prop('disabled', false);
});
$('.status_class_for_change').change(function (params) {
if($(this).val() === 'Approved'){
$('#mode_of_payment_parent_div_id').css('display','');
$('#mode_of_payment').prop('required','required');
}else{
$('#mode_of_payment_parent_div_id').css('display','none');
$('#mode_of_payment').removeAttr('required');
}
})
</script>
<script>
function updateThirdColumnValue(input) {
const itemRate = parseFloat(input.parentNode.previousElementSibling.querySelector('.item-rate').value);
const quantity = parseFloat(input.value);
const result = itemRate * quantity;
finalValue = parseFloat(result).toFixed(2)
input.parentNode.nextElementSibling.querySelector('.item-result').value = finalValue;
// After updating the third column, also update tax amount
//updateTaxAmount(input);
}
function updateTaxAmount(input) {
const row = input.closest('tr');
const itemResult = parseFloat(row.querySelector('.item-result').value);
const taxValue = parseFloat(row.querySelector('.item-tax').value);
const taxAmount = itemResult * taxValue / 100;
row.querySelector('[name="tax-amount[]"]').value = parseFloat(taxAmount).toFixed(2); // Ensure two decimal places
}
$(window).on('load', function() {
var vehicle_id = localStorage.getItem('vehicle_id');
if (vehicle_id) {
$('#vehicle_id').val(vehicle_id).trigger('change');
localStorage.removeItem('vehicle_id');
$('input[id="makeAndModel"], input[name="client_id"], input[name="client_name"], textarea[name="billing_address"], input[name="city"], input[name="state"], input[name="country"], input[name="mobile_no"], input[name="email"], input[name="postalcode"]').val('');
// Find the selected vehicle details
var selectedVehicle = vehicles.find(function(vehicle) {
return vehicle.vehicle_id == vehicle_id;
});
if (selectedVehicle) {
var makeId = selectedVehicle.make;
var modelId = selectedVehicle.model;
fetchMakeAndModel(makeId, modelId);
// Fill client & vehicle info fields
$('input[name="client_id"]').val(selectedVehicle.client_id);
$('input[name="client_name"]').val(selectedVehicle.client_name);
$('textarea[name="billing_address"]').val(selectedVehicle.address);
// $('input[name="billing_address"]').val(selectedClient.address);
$('input[name="city"]').val(selectedVehicle.city);
$('input[name="state"]').val(selectedVehicle.state);
$('input[name="country"]').val(selectedVehicle.country);
$('input[name="mobile_no"]').val(selectedVehicle.mobile_no);
$('input[name="email"]').val(selectedVehicle.email);
$('input[name="postalcode"]').val(selectedVehicle.postal_code);
} else {
console.warn("⚠️ Vehicle not found in 'vehicles' list for ID:", vehicle_id);
}
}
});
function fetchMakeAndModel(makeId, modelId) {
// Make sure makeId and modelId are valid
if (makeId !== '' && modelId !== '') {
// Perform AJAX request to fetch product information
$.ajax({
url: '<?php echo base_url().'invoices/products'?>', // Replace with the actual backend endpoint
method: 'POST', // or 'GET' based on your server implementation
dataType: 'json',
data: {
make_id: makeId,
model_id: modelId,
general: 1
},
success: function(response) {
// console.log(response);
// Populate make and model in the input field
var makeAndModel = response.makeName + ' - ' + response.modelName;
$('#makeAndModel').val(makeAndModel);
if(response.product.length){
productarray = response.product;
}else{
productarray = "No Product";
}
},
error: function(xhr, status, error) {
// Handle error
console.error('Error fetching product information:', error);
}
});
} else {
productarray = [];
console.error('Make ID or Model ID not found for the selected vehicle');
}
}
</script>
<!-- script for set the product name id -->
<script>
function addProductNamesId(selectElement) {
if (!selectElement) return; // safety
if (selectElement.value === "add_new_product") {
// $('#addProductModal').modal('show');
// var rowIndex = $(this).closest('tr').index(); // get row index
// localStorage.setItem('add_product_index', rowIndex);
// $(selectElement).val(''); // reset dropdown to empty
$(selectElement).select2('close');
$(selectElement).val('').trigger('change.select2');
var rowIndex = $(selectElement).closest('tr').index();
localStorage.setItem('add_product_index', rowIndex);
$('#addProductModal').modal('show');
$('.select2-container--open').removeClass('select2-container--open');
}
}
// Prevent multiple submissions by disabling the button on first click
document.querySelector('#invoicesForm').addEventListener('submit', function (e) {
const submitButton = this.querySelector('button[type="submit"]');
submitButton.disabled = true; // Disable the button
submitButton.textContent = 'Processing...'; // Optional: Show loading text
});
$(document).ready(function() {
function unitPriceReverseCalculation() {
var taxVal = $("select[name='product_tax']").val();
var total_amount = parseFloat($("input[name='product_total_amount']").val());
if (isNaN(total_amount) || total_amount <= 0) {
$("input[name='product_unit_price']").val('');
return;
}
if (taxVal === '' || isNaN(parseFloat(taxVal))) {
$("input[name='product_unit_price']").val(total_amount.toFixed(2));
toastr.warning('Please select Tax', 'Warning');
return;
}
var tax = parseFloat(taxVal);
var unitPrice = total_amount / ((tax / 100) + 1);
$("input[name='product_unit_price']").val(unitPrice.toFixed(2));
}
$("input[name='product_total_amount'], select[name='product_tax']").on('change keyup', function() {
unitPriceReverseCalculation();
});
// When Rate is edited, recalculate Amount and Tax Amount in the same row
$(document).on('keyup', '.item-rate', function () {
updateAmountAndTax(this);
});
function updateAmountAndTax(input) {
const row = $(input).closest('tr');
const rate = parseFloat($(input).val()) || 0;
const qty = parseFloat(row.find('.item-quantity').val()) || 0;
const tax = parseFloat(row.find('.item-tax').val()) || 0;
// Calculate Amount (Rate x Qty)
const amount = rate * qty;
row.find('.item-result').val(amount.toFixed(2));
// Calculate Tax Amount
const taxAmount = amount * (tax / 100);
row.find('.tax-amount').val(taxAmount.toFixed(2));
// Calculate Total Amount
const totalAmount = amount + taxAmount;
row.find('.item-amount').val(totalAmount.toFixed(2));
// Optionally trigger a summary update (like subtotal, grand total, etc.)
updateGrandTotal();
}
function updateGrandTotal() {
let grandTotal = 0;
$('.item-amount').each(function () {
const val = parseFloat($(this).val()) || 0;
grandTotal += val;
});
$('input[name="total_amount"]').val(grandTotal.toFixed(2));
}
$('#product_per').change(function () {
if ($(this).val() == 'ml')
{
hide_box();
hide_barrel();
show_ml();
resetStockDetails();
}
else if($(this).val() == 'box')
{
hide_ml();
hide_barrel();
show_box();
resetStockDetails();
}
else if($(this).val() == 'barrel')
{
hide_ml();
hide_box();
show_barrel();
resetStockDetails();
}
else
{
hide_box();
hide_barrel();
hide_ml();
resetStockDetails();
}
});
function hide_box()
{
$('#product_box_div').attr('hidden', 'hidden');
$('#product_box').removeAttr('required');
$('#product_qty_per_box_div').attr('hidden', 'hidden');
$('#product_qty_per_box').removeAttr('required');
}
function hide_barrel()
{
$('#product_barrel_div').attr('hidden', 'hidden');
$('#product_barrel').removeAttr('required');
$('#product_ltr_per_barrel_div').attr('hidden', 'hidden');
$('#product_ltr_per_barrel').removeAttr('required');
}
function hide_ml()
{
$('#product_ml_div').attr('hidden', 'hidden');
$('#product_ml').removeAttr('required');
}
function show_box()
{
$('#product_box_div').removeAttr('hidden');
$('#product_box').attr('required','required');
$('#product_qty_per_box_div').removeAttr('hidden');
$('#product_qty_per_box').attr('required','required');
}
function show_barrel()
{
$('#product_barrel_div').removeAttr('hidden');
$('#product_barrel').attr('required','required');
$('#product_ltr_per_barrel_div').removeAttr('hidden');
$('#product_ltr_per_barrel').attr('required','required');
}
function show_ml()
{
$('#product_ml_div').removeAttr('hidden');
$('#product_ml').attr('required','required');
}
function resetStockDetails()
{
$('#product_ml').val(null).trigger('change');
$('#product_barrel').val('');
$('#product_ltr_per_barrel').val('');
$('#product_box').val('');
$('#product_qty_per_box').val('');
$('#product_qty_stock').val('');
}
$('#product_box, #product_qty_per_box').on('keyup', function() {
var box = parseFloat($('#product_box').val()) || 0;
var qtyPerBox = parseFloat($('#product_qty_per_box').val()) || 0;
console.log(`b : ${box} qpb : ${qtyPerBox} `);
// if (!isNaN(box) && !isNaN(qtyPerBox) && box !== '' && qtyPerBox !== '') {
if (box > 0 && qtyPerBox > 0) {
var qtyInStock = box * qtyPerBox;
console.log(`calc : ${qtyInStock}`);
$('#product_qty_stock').val(qtyInStock);
} else {
console.log(`mt : ${qtyInStock}`);
$('#product_qty_stock').val('');
}
});
$('#product_barrel, #product_ltr_per_barrel').on('keyup', function() {
var barrel = parseFloat($('#product_barrel').val()) || 0;
var ltrPerBarrel = parseFloat($('#product_ltr_per_barrel').val()) || 0;
console.log(`b : ${barrel},lpb : ${ltrPerBarrel}`);
// if (!isNaN(barrel) && !isNaN(ltrPerBarrel) && barrel !== '' && ltrPerBarrel !== '') {
if (barrel > 0 && ltrPerBarrel > 0) {
var qtyInStock = barrel * ltrPerBarrel;
console.log(`calc : ${qtyInStock}`);
$('#product_qty_stock').val(qtyInStock);
} else {
console.log(`mt : ${qtyInStock}`);
$('#product_qty_stock').val('');
}
});
});
</script>
<script>
function calculateBalance() {
var total = parseFloat($('#grandtotal').val()) || 0;
var discount = parseFloat($('#discount').val()) || 0;
var advance = parseFloat($('#paid_advance').val()) || 0;
// Ensure discount or advance not negative
if (discount < 0) discount = 0;
if (advance < 0) advance = 0;
// If total of discount + advance exceeds total, fix it
if (discount + advance > total) {
var excess = (discount + advance) - total;
// Determine which field caused the excess (the last changed one)
// We can check active element
var lastChanged = document.activeElement.id;
if (lastChanged === 'discount') {
discount = total - advance;
$('#discount').val(discount.toFixed(2));
} else if (lastChanged === 'paid_advance') {
advance = total - discount;
$('#paid_advance').val(advance.toFixed(2));
} else {
// If unknown, just cap both
if (discount > total) discount = total;
if (advance > total - discount) advance = total - discount;
$('#discount').val(discount.toFixed(2));
$('#paid_advance').val(advance.toFixed(2));
}
}
// Calculate balance
var balance = total - (discount + advance);
if (balance < 0) balance = 0;
// Update fields
$('#discount').val(discount.toFixed(2));
$('#paid_advance').val(advance.toFixed(2));
$('#balance').val(balance.toFixed(2));
}
</script>