//$('select').select2()
//$('#loadmodal').modal('show');
function asyncAjax(formData,url){
return new Promise(function(resolve, reject) {
$.ajax({
url: url,
type: "POST",
data : formData,
success: function(data) {
resolve(data) // Resolve promise and when success
},
error: function(err) {
reject(err) // Reject the promise and go to catch()
}
});
});
}
let defaultoptionsArray = ['','customer_modal','price_add','onetimeproduct','product_modal']
async function loadcustomers(){
let customers = JSON.parse(await asyncAjax({Request: 'customerlist'},'main.php'));
customers = customers;
if(customers['success']){
let options = document.querySelectorAll('[name="customer"] >option');
if(options.length > 0){
options.forEach((option) => {
if(!defaultoptionsArray.includes(option.value)){
option.remove();
}
});
}
customers = customers['success'];
customers.forEach((customer) => {
let CustomerElement = document.querySelectorAll('select[name="customer"]');
CustomerElement.forEach((element) => {
$(element).append($("").attr("value", customer['id']).text(customer['name']))
});
});
}
}
async function loadproducts(){
let products = JSON.parse(await asyncAjax({Request: 'productlist'},'main.php'));
if(products['success']){
let options = document.querySelectorAll('.product >option');
if(options.length > 0){
options.forEach((option) => {
if(!defaultoptionsArray.includes(option.value)){
option.remove();
}
});
}
products = products['success']
products.forEach((product) => {
let name = 'product[product]';
let ProductElement = document.querySelectorAll('.product');
ProductElement.forEach((element) => {
$(element).append($("").attr("value", product['id']).
text(product['name']) )
});
});
}
}
loadcustomers();
loadproducts();
$('#loadmodalclose').click();
//Set Products On Page Load
document.querySelectorAll('.form').forEach((form) => {
if(form.id != 'InvoiceForm'){
form.style.top = document.querySelector('#InvoiceForm').getBoundingClientRect()['top'];
form.style.width = document.querySelector('#InvoiceForm').getBoundingClientRect()['width'] + 'px'
}
});
var table = $('#datatable').DataTable( {
'bSort': false,
"scrollY": "200px",
"scrollCollapse": true,
"info": true,
"paging": true,
"ajax": {
"url": "main.php",
"type": "POST",
'data' : {Request: "Logs"},
success: function(data){
populateDataTable(data)
}
}
} );
// $(window).on('load', function() {
// });
function populateDataTable(data) {
$("#datatable").DataTable().clear();
var row = 1;
$.each(data, function (index, value) {
$('#datatable').dataTable().fnAddData( [
row,
value.id,
value.Request,
value.CustomerId,
value.PaymentLink,
value.Invoice,
value.duedate,
value.created
]);
row++;
});
}
// table.buttons().container()
// .appendTo( '#example_wrapper .col-md-6:eq(0)' );
//Set Customers On Page Load
function ajaxRequest(formData,url,form){
$('#loadmodal').modal('show');
document.querySelector(form + ' #normsubmit').disabled = true
return new Promise(function(resolve, reject) {
$.ajax({
url: url,
type: "POST",
data : formData,
success: function(data) {
document.querySelector(form + ' #normsubmit').disabled = false
$('#loadmodalclose').click();
resolve(data) // Resolve promise and when success
},
error: function(err) {
document.querySelector(form + ' #normsubmit').disabled = false
reject(err) // Reject the promise and go to catch()
$('#loadmodalclose').click();
}
});
});
}
async function getPrice(obj,field = '', val = '', FormName = ''){
if(defaultoptionsArray.includes(obj.value)){
return;
}
let formData = {id: obj.value, Request: 'getprice' };
let Prices = JSON.parse(await ajaxRequest(formData,'main.php',''));
if(Prices['success']){
let element = obj.parentElement.nextElementSibling.children[0];
let options = element.childNodes;
if(options.length > 0){
options.forEach((option) => {
if(!defaultoptionsArray.includes(option.value)){
option.remove();
}
});
}
Prices = Prices['success'];
Prices.forEach((price) => {
$(element).append($("").attr("value", price['id']).
text(price['price']));
})
if(val != ''){
document.querySelector(FormName + ' #' + field).value = val;
}
}
}
//Payment Type Drop Down Event Listener
document.getElementById('payment-dropdown').addEventListener('change',(event) => {
document.querySelectorAll('form').forEach((form) => {
if(event.target.value == form.id){
form.classList.toggle('is-show');
}
else{
form.classList.remove('is-show');
}
});
});
function ResponseMsg(header,body,response,form){
document.querySelector('#ResponseModal #response').innerHTML = '';
if(response == 'success'){
document.querySelector('#ResponseModal #response-title').innerHTML = header;
document.querySelectorAll(form +' input, ' + form + ' select').forEach((formElements) => {
formElements.value = '';
});
}
else{
document.querySelector('#ResponseModal #response-title').innerHTML = 'Error';
body = document.createElement('span')
body.setAttribute('class','danger');
body.innerHTML = 'There was a problem with your request';
}
document.querySelector('#ResponseModal #response').appendChild(body) ;
$("#ResponseModal").modal('show');
}
async function Invoice(){
let formData ={customer : document.querySelector('#InvoiceForm #customer').value,
CustomerName : document.querySelector('#InvoiceForm #customer').selectedOptions[0].text,
description : document.querySelector('#InvoiceForm #description').value,
duedate : document.querySelector('#InvoiceForm #due').value,
Request : 'invoice'};
document.querySelectorAll('#InvoiceForm table tbody tr td').forEach((element) => {
let childElement = element.childNodes;
childElement.forEach((child) => {
if(child.tagName == 'INPUT' || child.tagName == 'SELECT'){
let name = child.name;
let value = child.value;
formData[name] = value;
}
})
});
let Invoice = JSON.parse(await ajaxRequest(formData,'main.php','#InvoiceForm'));
if(Invoice['success']){
let element = document.createElement('a');
element.setAttribute('href',Invoice['success']['URL']);
element.setAttribute('target','_blank');
element.setAttribute('class','btn btn-secondary');
element.innerText = 'Click To Open';
//element.innerHTML = 'Your Invoice has been created successfully.'
ResponseMsg('INVOICE', element,'success','#InvoiceForm')
resetTable('#InvoiceForm');
}
else{
ResponseMsg('INVOICE', Invoice['error'],'error','#InvoiceForm')
}
}
async function addcustomer(){
let formData = {name: document.querySelector('#CustomerForm [name="customer_name"]').value,
email:document.querySelector('#CustomerForm [name="customer_email"]').value,
Request: 'addcustomer'}
let customer = JSON.parse(await ajaxRequest(formData,'main.php','#CustomerForm'));
if(customer['success']){
$('#addcustomer button')[0].click();
let element = document.createElement('h5');
element.innerHTML = 'Customer has been added successfully.'
ResponseMsg('CUSTOMER', element,'success','#CustomerForm');
let customers = await loadcustomers();
let form = '#' + document.querySelector('#payment-dropdown').value;
document.querySelector(form + ' [name="customer"]').value = customer['success'];
}
else{
ResponseMsg('CUSTOMER', PaymentIntent['error'],'error','#CustomerForm');
}
}
async function paymentIntent(){
let formData ={FirstName : document.querySelector('#payment-det #FirstName').value,
LastName : document.querySelector('#payment-det #LastName').value,
Email : document.querySelector('#payment-det #Email').value,
Phone : document.querySelector('#payment-det #Phone').value,
Amount : document.querySelector('#payment-det #Amount').value,
Description : document.querySelector('#payment-det #description').value,
Request : 'paymentIntent'}
let PaymentIntent = JSON.parse(await ajaxRequest(formData,'main.php','#payment-det'));
if(PaymentIntent['success']){
//document.querySelector('#payment-det button').remove();
initialize(PaymentIntent['success']);
checkStatus(PaymentIntent['success']);
}
else{
ResponseMsg('MANUAL PAYMENT', PaymentIntent['error'],'error','#payment-det');
}
}
async function paymentlink(){
let formData ={
Request : 'paymentlink'}
document.querySelectorAll('#paymentlink table tbody tr td').forEach((element) => {
let childElement = element.childNodes;
childElement.forEach((child) => {
if(child.tagName == 'INPUT' || child.tagName == 'SELECT'){
let name = child.name;
let value = child.value;
formData[name] = value;
}
})
})
let PaymentLink = JSON.parse(await ajaxRequest(formData,'main.php','#paymentlink'));
if(PaymentLink['success']){
let element = document.createElement('a');
element.setAttribute('href',PaymentLink['success']);
element.setAttribute('target','_blank');
element.setAttribute('class','btn btn-secondary');
element.innerText = 'Click To Open';
ResponseMsg('PAYMENT LINK', element,'success','#paymentlink');
resetTable('#paymentlink');
}
else{
ResponseMsg('PAYMENT LINK', PaymentLink['error'],'error','#paymentlink');
}
}
function customermodal(obj){
if(obj.value == 'customer_modal'){
$('#addcustomer').modal('show');
}
}
function pricemodal(obj){
if(obj.value == 'price_add'){
$('#tempproduct').modal('show');
}
}
function openModal(obj){
if(obj.value == 'customer_modal'){
$('#addcustomer').modal('show');
}
else if(obj.value == 'price_add' || obj.value == 'onetimeproduct' || obj.value == 'product_modal'){
$('#tempproduct').modal('show');
if(obj.value == 'price_add'){
document.querySelector('#tempproduct [name="description"]').value = obj.parentElement.previousElementSibling.children[0].selectedOptions[0].text;
}
document.querySelector('#tempproduct [name="field"]').value = obj.name;
}
}
async function productModalChanges(){
let form = '#' + document.querySelector('#payment-dropdown').value;
let field = ' [name = "' + document.querySelector('#tempproduct [name="field"]').value + '"]';
let selectedoption = document.querySelector(form + ' ' + field).value
let price = document.querySelector('#tempproduct [name="price"]').value;
let description = document.querySelector('#tempproduct [name="description"]').value;
if(selectedoption == 'price_add'){
if(price != ''){
$('#tempproduct button')[0].click();
document.querySelector('#tempprice button').click();
let productfield = document.querySelector(field).parentElement.previousElementSibling.children[0].name;
$(form + ' [name="'+productfield + '"]').append($("").attr("value",description).text(description));
document.querySelector(form + ' [name="'+productfield + '"]').value = description;
$(form + field).append($("").attr("value",'$' + price).text('$' +price));
document.querySelector(form + field).value = '$' +price;
}
}
else if(selectedoption == 'onetimeproduct'){
if(price != ''){
$('#tempproduct button')[0].click();
let pricefield = document.querySelector(field).parentElement.nextElementSibling.children[0].name;
$(form + ' [name="'+pricefield + '"]').append($("").attr("value",'$' + price).text('$' +price));
document.querySelector(form + ' [name="'+pricefield + '"]').value = '$' +price;
$(form + field).append($("").attr("value",description).text(description));
document.querySelector(form + field).value = description;
}
}
else if(selectedoption == 'product_modal'){
let formData = {name: document.querySelector('#tempproduct [name="description"]').value,
price:document.querySelector('#tempproduct [name="price"]').value,
Request: 'addproduct'}
let product = JSON.parse(await ajaxRequest(formData,'main.php','#ProductForm'));
if(product['success']){
$('#tempproduct button')[0].click();
let element = document.createElement('h5');
element.innerHTML = 'Product has been added successfully.'
ResponseMsg('PRODUCT', element,'success','#ProductForm');
let pricefield = document.querySelector(field).parentElement.nextElementSibling.children[0].name;
let products = await loadproducts();
let form = '#' + document.querySelector('#payment-dropdown').value;
document.querySelector(form + field).value = product['success']['product'];
let event = new Event('change');
// Dispatch it.
document.querySelector(form + field).dispatchEvent(event);
console.log(form + ' [name="' + pricefield +'"]')
setTimeout(() => {
document.querySelector(form + ' [name="' + pricefield +'"]').value = product['success']['price'];
}, 500);
}
else{
ResponseMsg('PRODUCT', PaymentIntent['error'],'error','#ProductForm');
}
}
}
//Patterns for test
let numberpattern = /\d+/;
let phonepattern = /^\+92\d{10}$/;
let emailpattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
let namepattern = /^[a-zA-Z ]+$/ ;
//Element focus out validation
document.querySelectorAll('form input, form select').forEach((element) => {
element.addEventListener('focusout', (event) => {
if (event.target.className.includes('req') == true && event.target.value == '') {
addFieldError(event.target, 'Please Fill this field');
}
else if (event.target.className.includes('int') == true && numberpattern.test(event.target.value) != true) {
addFieldError(event.target, 'Please Enter Valid Number');
}
else if (event.target.className.includes('name') == true && namepattern.test(event.target.value) == false) {
addFieldError(event.target, 'Please Enter Valid Name');
}
else if (event.target.className.includes('email') == true && emailpattern.test(event.target.value) != true) {
addFieldError(event.target, 'Please Enter Valid Email');
}
else {
if (event.target.nextElementSibling) {
event.target.nextElementSibling.remove();
}
}
})
});
//Submit Button click validation
document.querySelectorAll('form #normsubmit').forEach((form) => {
form.addEventListener('click', (event) => {
event.preventDefault();
let FormElement = '#' + event.target.parentElement.parentElement.parentElement.parentElement.id;
let elementsCount = 0;
document.querySelectorAll(FormElement + ' input, ' + FormElement + ' select').forEach((element) => {
if (element.className.includes('req') == true && element.value == '') {
addFieldError(element, 'Please Fill this field');
elementsCount = elementsCount + 1;
}
else if (element.className.includes('int') == true && numberpattern.test(element.value) != true){
addFieldError(element,'Please Enter Valid Number');
elementsCount = elementsCount + 1;
}
else if (element.className.includes('name') == true && namepattern.test(element.value) == false) {
addFieldError(element, 'Please Enter Valid Name');
elementsCount = elementsCount + 1;
}
else if (element.className.includes('email') == true && emailpattern.test(element.value) != true){
addFieldError(element, 'Please Enter Valid Email');
elementsCount = elementsCount + 1;
}
else {
if (element.nextElementSibling) {
element.nextElementSibling.remove();
elementsCount = elementsCount - 1;
}
}
});
if (elementsCount <= 0) {
FormsClick(FormElement);
}
});
});
function addFieldError(element,spanContent){
if(element.nextElementSibling){
element.nextElementSibling.remove();
}
let spanelement = document.createElement('span');
spanelement.setAttribute('class','text-danger');
spanelement.innerHTML = spanContent;
element.after(spanelement);
}
function FormsClick(FormName){
if(FormName == '#InvoiceForm'){
return Invoice();
}
else if (FormName == '#paymentlink'){
return paymentlink();
}
else if (FormName == '#payment-det'){
return paymentIntent();
}
else if (FormName == '#CustomerForm'){
return addcustomer();
}
}
function DuplicateRow(obj){
let newRow = obj.parentElement.parentElement.cloneNode(true);
console.log(newRow.childNodes)
newRow.childNodes.forEach((td) => {
if(td.tagName == 'TD'){
td.childNodes.forEach((element) => {
if(element.tagName == 'INPUT' || element.tagName == 'SELECT'){
let elementnamearray = element.name.split('[');
let tablename = elementnamearray[0];
let fieldname = elementnamearray[2].split(']')[0];
let index = +elementnamearray[1].split(']')[0] + +1;
element.name = tablename + '[' + index + '][' + fieldname + ']';
}
});
}
});
obj.parentElement.parentElement.after(newRow);
}
function resetTable(FormName){
let table = document.querySelectorAll(FormName + ' table tbody tr');
let i = 0;
if(table.length > 1){
table.forEach((tr) => {
if(i > 0){
tr.remove();
}
i= i+1;
})
}
}
function removeparams(){
window.location.href = window.location.href.split('?')[0]
}