edit/delete vendor address

This commit is contained in:
Staycie 2024-04-08 18:24:45 +08:00
parent fd40d3bb34
commit 6cf3efad4b
1 changed files with 582 additions and 162 deletions

View File

@ -56,11 +56,36 @@ if ($_SESSION["userId"] <> "") {
<link rel="stylesheet" href="assets/css/style2.css" />
<link rel="stylesheet" href="assets/css/responsive.css" />
<!-- FONTAWESOME -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<!-- Background css -->
<link rel="stylesheet" id="bg-switcher-css" href="assets/css/backgrounds/bg-4.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@latest/dist/css/select2.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@latest/dist/js/select2.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<style>
#edit_modal .cover-upload:after{
background-color: orange;
}
.ec-user-account .ec-vendor-block-bg {
width: 100%;
height: 200px;
background-image: none;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-blend-mode: overlay;
background-color: rgba(0, 0, 0, 0.6);
border-radius: 5px;
}
#editDelete:hover i{
color: #ffaa00;
cursor: pointer;
}
</style>
</head>
<body class="shop_page">
@ -280,7 +305,8 @@ if ($_SESSION["userId"] <> "") {
<!-- <?php var_dump($vendorData) ?> -->
<?php foreach ($vendorLoginIdjson['results'] as $vendor_index => $vendor) { ?>
<?php foreach ($vendor['address'] as $address_index => $address) { ?>
<div class="card mb-3">
<!-- added id -->
<div class="card mb-3" id="form-check-<?php echo $address_index ?>">
<div class="card-body">
<div class="selectCon">
<div class="selectWrap" style="display: flex; justify-content: center; align-items: center; width: 50%;">
@ -290,7 +316,7 @@ if ($_SESSION["userId"] <> "") {
</label>
</div>
<div class="selectWrap" style="display: flex; justify-content: center; align-items: center; width: 50%;">
<div class="selectWrap" style="display: flex; justify-content: center; align-items: center; width: 50%; margin-left:-20px;">
<input type="radio" style="padding-left: 0px !important; margin: 0px 0px !important;" name="selectedShippingAddress[<?php echo $vendor_index; ?>]" id="shipping_address_<?php echo $vendor_index; ?>_<?php echo $address_index; ?>" value="<?php echo $vendor_index; ?>_<?php echo $address_index; ?>" class="form-check-input" onchange="updateAddressShipping('<?php echo $vendor['_id']; ?>', <?php echo $address_index; ?>, true)" <?php echo $address["shipping"] ? 'checked' : ''; ?>>
<label class="form-check-label" style="margin: 0px 10px !important;" for="shipping_address_<?php echo $vendor_index; ?>_<?php echo $address_index; ?>">
Shipping Address
@ -299,9 +325,25 @@ if ($_SESSION["userId"] <> "") {
</div>
<!-- Stacy modified this block of code -->
<div class="container">
<div class="row">
<div class="col-md-12 mx-auto"> <!-- Adjust the column size as needed -->
<div id="editDelete" style="display:flex; float:right; width:20px; margin-right:-10px;" >
<?php
$address['id'] =$address_index;
$jsonAddress = json_encode($address)?>
<a href="javascript:0" data-bs-toggle="modal" data-value=' <?php echo $jsonAddress; ?>' data-bs-target="#thirdModal">
<i class="fa-regular fa-pen-to-square" style="font-size:15px; float:right;"></i></a>
<!-- <i class="fa-regular fa-trash-can" style="font-size:15px; float:right;"></i> -->
</div>
<div id="editDelete" style="display:flex; float:right; width:20px; margin-top:20px; margin-right:-20px; margin-top:30px;">
<!-- <i class="fa-solid fa-pen" style="font-size:15px; float:right;"></i></a> -->
<i onclick="deleteAddress('<?php echo $vendor['_id']; ?>', <?php echo $address_index; ?>, true)"
class="fa-regular fa-trash-can" style="font-size:15px; float:right;"></i>
</div>
<label class="form-check-label" for="address_<?php echo $vendor_index; ?>_<?php echo $address_index; ?>">
<?php echo $address['first_name']; ?> <?php echo $address['last_name']; ?><br>
<?php echo $address['address_1']; ?> <?php echo $address['address_2']; ?>
@ -309,6 +351,7 @@ if ($_SESSION["userId"] <> "") {
<?php echo $address['province']; ?> <?php echo $address['country']; ?><br>
Phone: <?php echo $address['phone']; ?>
</label>
</div>
</div>
</div>
@ -323,6 +366,7 @@ if ($_SESSION["userId"] <> "") {
</div>
</div>
<!-- secondModal -->
<div class="modal fade" id="secondModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-sm" role="document" style="max-width: 800px;">
<div class="modal-content">
@ -379,13 +423,99 @@ if ($_SESSION["userId"] <> "") {
</div>
</div>
<!-- Stacy added thirdModal -->
<div class="modal fade" id="thirdModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-sm" role="document" style="max-width: 800px;">
<div class="modal-content">
<div class="modal-body" style="overflow-y: auto; max-height: 90vh;">
<form>
<div class="form-group">
<label for="addressFirstName" class="text-dark font-weight-medium pt-3 mb-2">First Name</label>
<input type="text" class="form-control"
id="addressFirstName2"
value="<?php echo $address['first_name']; ?>">
<!-- <label for="addressFirstName" class="text-dark font-weight-medium pt-3 mb-2">First Name</label>-->
<input type="hidden" class="form-control" id="addressId" >
</div>
<div class="form-group">
<label for="addressLastName" class="text-dark font-weight-medium pt-3 mb-2">Last Name</label>
<input type="text" class="form-control" id="addressLastName2" value="<?php echo $address['last_name']; ?>">
<!-- <label for="addressLastName" class="text-dark font-weight-medium pt-3 mb-2">Last Name</label>
<input type="text" class="form-control" id="addressLastName"> -->
</div>
<div class="form-group">
<label for="addressContact" class="text-dark font-weight-medium pt-3 mb-2">Contact Number</label>
<input type="text" class="form-control" id="addressContact2" value="<?php echo $address['phone']; ?>">
<!-- <label for="addressContact" class="text-dark font-weight-medium pt-3 mb-2">Contact Number</label>
<input type="number" class="form-control" id="addressContact"> -->
</div>
<div class="form-group">
<label for="addressBuilding" class="text-dark font-weight-medium pt-3 mb-2">Building,Number</label>
<input type="text" class="form-control" id="addressBuilding2" value="<?php echo $address['address_1']; ?>">
<!-- <label for="addressBuilding" class="text-dark font-weight-medium pt-3 mb-2"> Building,Number </label>
<input type="text" class="form-control" id="addressBuilding"> -->
</div>
<div class="form-group">
<label for="addressStreet" class="text-dark font-weight-medium pt-3 mb-2">Street </label>
<input type="text" class="form-control" id="addressStreet2" value="<?php echo $address['address_2']; ?>">
<!-- <label for="addressStreet" class="text-dark font-weight-medium pt-3 mb-2"> Street </label>
<input type="text" class="form-control" id="addressStreet"> -->
</div>
<div class="form-group">
<label for="provinceSelect2">Province</label>
<select class="form-select" id="provinceSelect2">
<option id="provinceSelect2Opt" value="<?php echo $address['province']; ?>" >Select Province</option>
</select>
<!-- <label for="provinceSelect">Province</label>
<select class="form-select" id="provinceSelect">
<option value="" disabled selected hidden>Select Province</option>
</select> -->
</div>
<div class="form-group">
<label for="citySelect2">Municipality/City</label>
<select class="form-select" id="citySelect2" required>
<option value="" id="citySelect2Opt" selected hidden>Select Municipality/City</option>
</select>
</div>
<div class="form-group">
<label for="barangaySelect2">Barangay</label>
<select class="form-select" id="barangaySelect2" required>
<option value="" id="barangaySelect2Opt" selected hidden>Select Barangay</option>
</select>
</div>
<div class="form-group">
<label for="addressCountry2" class="text-dark font-weight-medium pt-3 mb-2">Country</label>
<input type="text" class="form-control" id="addressCountry2">
</div>
<button type="button" class="btn btn-primary" id="submitBtn2">Submit</button>
</form>
</div>
</div>
</div>
</div>
<!-- Bank -->
<div class="modal fade" id="vendorBankModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-sm" role="document" style="max-width: 800px;">
<div class="modal-content">
<div class="modal-body" style="overflow-y: auto; max-height: 90vh;">
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#secondBankModal">Add New Bank</button>
<!-- Display a list of addresses and let the user choose -->
<!-- Display a list of banks and let the user choose -->
<form id="BankForm">
<!-- <?php var_dump($vendorData) ?> -->
<?php foreach ($vendorLoginIdjson['results'] as $vendor_index => $vendor) { ?>
@ -495,6 +625,208 @@ if ($_SESSION["userId"] <> "") {
});
}
</script>
<script>
// function for deleting address
const vendorid = `<?php echo $_SESSION["LoggedInVendorId"]; ?>`;
function deleteAddress(vendorid, addressIndex) {
fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/vendors/' + vendorid)
.then(response => response.json())
.then(data => {
let existingAddresses = data.address || [];
if (addressIndex >= 0 && addressIndex < existingAddresses.length) {
existingAddresses.splice(addressIndex, 1);
fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/vendors/' + vendorid, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
address: existingAddresses
}),
})
.then(response => {
if (response.ok) {
location.reload();
// filter the delete action
document.getElementById('form-check-' + addressIndex).remove();
} else {
console.error('Failed to submit data');
alert('Failed to submit data');
}
})
.catch(error => {
console.error('Error:', error);
alert('Error submitting data');
});
} else {
console.log("Invalid address index.");
}
})
.catch(error => {
console.error('Error:', error);
alert('Error fetching vendor data');
});
}
</script>
<script>
// added for thirdModal
$('#thirdModal').on('shown.bs.modal', function (event) {
var jsonString = $(event.relatedTarget).data('value');
var jsonObject = JSON.parse(jsonString);
console.log(jsonObject)
// document.getElementById("addressFirstName2").value('mmmm');
// $('#addressFirstName2').setAttribute('value','My default value');
// shows inputed data by the vendor
document.querySelector('input[id="addressFirstName2"]').value = jsonObject.first_name;
document.querySelector('input[id="addressLastName2"]').value = jsonObject.last_name;
document.querySelector('input[id="addressContact2"]').value = jsonObject.phone;
document.querySelector('input[id="addressBuilding2"]').value = jsonObject.address_1;
document.querySelector('input[id="addressStreet2"]').value = jsonObject.address_2;
document.querySelector('option[id="provinceSelect2Opt"]').text = jsonObject.province;
document.querySelector('option[id="provinceSelect2Opt"]').value = jsonObject.province;
document.querySelector('option[id="citySelect2Opt"]').text = jsonObject.city;
document.querySelector('option[id="citySelect2Opt"]').value = jsonObject.city;
document.querySelector('option[id="barangaySelect2Opt"]').text = jsonObject.barangay;
document.querySelector('option[id="barangaySelect2Opt"]').value = jsonObject.barangay;
document.querySelector('input[id="addressCountry2"]').value = jsonObject.country;
document.querySelector('input[id="addressId"]').value = jsonObject.id;
console.log('id ' + jsonObject.id)
const provinceSelect = $('#provinceSelect2'); // Use jQuery to select the element
const citySelect = $('#citySelect2'); // Use jQuery to select the element
const barangaySelect = $('#barangaySelect2'); // Use jQuery to select the element
// Initialize Select2 on the provinceSelect, citySelect, and barangaySelect elements
provinceSelect.select2({
dropdownParent: $('#thirdModal'),
containerCssClass: 'select2-zindex-high' // Optional, add a custom class for styling
});
citySelect.select2({
dropdownParent: $('#thirdModal'),
containerCssClass: 'select2-zindex-high' // Optional, add a custom class for styling
});
barangaySelect.select2({
dropdownParent: $('#thirdModal'),
containerCssClass: 'select2-zindex-high' // Optional, add a custom class for styling
});
// Fetch provinces data
fetch('https://psgc.gitlab.io/api/provinces')
.then(response => {
if (response.ok) {
return response.json();
} else {
console.error('Failed to fetch provinces');
throw new Error('Failed to fetch provinces');
}
})
.then(provincesData => {
// Iterate through the provinces data and add options
provincesData.forEach(province => {
const option = new Option(province.name, province.code);
provinceSelect.append(option);
});
// Add an extra option manually
const extraOption = new Option('Metro Manila', '130000000');
provinceSelect.append(extraOption);
// Add event listener to provinceSelect
provinceSelect.on('change', function() {
// Clear existing options in citySelect and barangaySelect
citySelect.html('<option value="" disabled selected hidden>Select City</option>');
barangaySelect.html('<option value="" disabled selected hidden>Select Barangay</option>');
// Fetch and update cities/municipalities based on the selected province
updateCities();
});
})
.catch(error => {
console.error('Error:', error);
});
// Function to update city/municipality options based on the selected province
function updateCities() {
const selectedProvinceCode = provinceSelect.val(); // Use val() to get the selected value with Select2
if (selectedProvinceCode) {
let citiesEndpoint;
if (selectedProvinceCode === '130000000') {
// Check if Metro Manila is selected
citiesEndpoint = 'https://psgc.gitlab.io/api/regions/130000000/cities-municipalities/';
} else {
citiesEndpoint = `https://psgc.gitlab.io/api/provinces/${selectedProvinceCode}/cities-municipalities/`;
}
fetch(citiesEndpoint)
.then(response => {
if (response.ok) {
return response.json();
} else {
console.error('Failed to fetch cities/municipalities');
throw new Error('Failed to fetch cities/municipalities');
}
})
.then(citiesData => {
// Iterate through the cities data and add options
citiesData.forEach(city => {
const option = new Option(city.name, city.code);
citySelect.append(option);
});
})
.catch(error => {
console.error('Error:', error);
});
}
}
// Add event listener to citySelect
citySelect.on('change', function() {
// Clear existing options in barangaySelect
barangaySelect.html('<option value="" disabled selected hidden>Select Barangay</option>');
// Fetch and update barangays based on the selected city/municipality
const selectedCityCode = citySelect.val();
if (selectedCityCode) {
fetch(`https://psgc.gitlab.io/api/cities-municipalities/${selectedCityCode}/barangays/`)
.then(response => {
if (response.ok) {
return response.json();
} else {
console.error('Failed to fetch barangays');
throw new Error('Failed to fetch barangays');
}
})
.then(barangaysData => {
// Iterate through the barangays data and add options
barangaysData.forEach(barangay => {
const option = new Option(barangay.name, barangay.code);
barangaySelect.append(option);
});
})
.catch(error => {
console.error('Error:', error);
});
}
});
// document.querySelector('input[id="addressFirstName2"]').value = jsonObject.last_name;
});
</script>
<script>
const vendorid = `<?php echo $_SESSION["LoggedInVendorId"]; ?>`;
document.addEventListener('DOMContentLoaded', function() {
@ -606,6 +938,7 @@ if ($_SESSION["userId"] <> "") {
$('#submitBtn').on('click', function() {
console.log('clickkkkkkkk')
fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/vendors/' + vendorid)
.then(response => response.json())
.then(data => {
@ -663,6 +996,93 @@ if ($_SESSION["userId"] <> "") {
});
// Added function for editing the address
$('#submitBtn2').on('click', function() {
// function updateAddress(){
// Retrieve existing addresses from the API
// fetch('https://api.obanana.shop/api/v1/customers/65482e8d209ff8d348bd30fd')
fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/vendors/' + vendorid)
.then(response => response.json())
.then(data => {
// Get the existing addresses array
const existingAddresses = data.address || [];
// Get the new address details
const firstName = $('#addressFirstName2').val();
const lastName = $('#addressLastName2').val();
const contact = $('#addressContact2').val();
const buildingNumber = $('#addressBuilding2').val();
const street = $('#addressStreet2').val();
const province = $('#provinceSelect2 :selected').text();
const city = $('#citySelect2 :selected').text();
const barangay = $('#barangaySelect2 :selected').text();
const country = $('#addressCountry2').val();
const id = $('#addressId').val();
console.log('clickkkkkkkk'+ id)
// Create a new address object
const newAddress = {
first_name: firstName,
last_name: lastName,
phone: contact,
address_1: buildingNumber,
address_2: street,
city: city,
province: province,
barangay: barangay,
country: country,
};
// Add the new address to the existing addresses
// existingAddresses.push(newAddress);
// var newAddresses= existingAddresses.filter((e,i)=>i!==id)
let existingAddress = existingAddresses
existingAddress[id]={
first_name: firstName,
last_name: lastName,
phone: contact,
address_1: buildingNumber,
address_2: street,
city: city,
province: province,
barangay: barangay,
country: country,
};
console.log( existingAddress[id])
// Make a PATCH request to update the addresses array
return fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/vendors/' + vendorid, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
address: existingAddress
}),
});
})
.then(response => {
if (response.ok) {
// Handle success (e.g., show a success message)
location.reload();
} else {
// Handle error
console.error('Failed to submit data');
alert('Failed to submit data');
}
})
.catch(error => {
// Handle network or other errors
console.error('Error:', error);
alert('Error submitting data');
});
});
$('#submitBankBtn').on('click', function() {
fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/vendors/' + vendorid)
@ -754,7 +1174,7 @@ if ($_SESSION["userId"] <> "") {
if (!updateResponse.ok) {
throw new Error(`Failed to update address: ${updateResponse.status}`);
}
console.log(`Address updated successfully for customer ${vendorid}`);
console.log(`Address updated successfully for vendor ${vendorid}`);
} catch (error) {
console.error('Error updating address:', error.message);
}
@ -771,7 +1191,7 @@ if ($_SESSION["userId"] <> "") {
});
if (!response.ok) {
throw new Error(`Failed to fetch customer data: ${response.status}`);
throw new Error(`Failed to fetch vendor data: ${response.status}`);
}
// console.log(customerId + " ." + addressIndex + "." +isBilling + "." + isShipping)
const vendorsData = await response.json();
@ -828,7 +1248,7 @@ if ($_SESSION["userId"] <> "") {
sProvinceElement.textContent = vendorsData.address[addressIndex].province;
sCountryElement.textContent = vendorsData.address[addressIndex].country;
}
console.log(`Address updated successfully for customer ${vendorid}`);
console.log(`Address updated successfully for vendor ${vendorid}`);
} catch (error) {
console.error('Error updating address:', error.message);
}
@ -937,188 +1357,188 @@ if ($_SESSION["userId"] <> "") {
</div>
<script>
function uploadVendorProfileImage() {
var vendorid = '<?php echo $_SESSION["LoggedInVendorId"] ?>';
var file = document.getElementById('imageUpload').files[0];
if (file) {
const reader = new FileReader();
var vendorid = '<?php echo $_SESSION["LoggedInVendorId"] ?>';
var file = document.getElementById('imageUpload').files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const maxWidth = 1200;
const maxHeight = 1000;
const aspectRatio = img.width / img.height;
let newWidth = img.width;
let newHeight = img.height;
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const maxWidth = 1200;
const maxHeight = 1000;
const aspectRatio = img.width / img.height;
let newWidth = img.width;
let newHeight = img.height;
if (img.width > maxWidth) {
newWidth = maxWidth;
newHeight = newWidth / aspectRatio;
}
if (img.width > maxWidth) {
newWidth = maxWidth;
newHeight = newWidth / aspectRatio;
}
if (newHeight > maxHeight) {
newHeight = maxHeight;
newWidth = newHeight * aspectRatio;
}
if (newHeight > maxHeight) {
newHeight = maxHeight;
newWidth = newHeight * aspectRatio;
}
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(img, 0, 0, newWidth, newHeight);
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(img, 0, 0, newWidth, newHeight);
canvas.toBlob((blob) => {
const resizedFile = new File([blob], file.name, {
type: 'image/jpeg'
});
canvas.toBlob((blob) => {
const resizedFile = new File([blob], file.name, {
type: 'image/jpeg'
});
var formData = new FormData();
formData.append('image_id', vendorid);
formData.append('category', 'vendor');
formData.append('image', resizedFile);
var formData = new FormData();
formData.append('image_id', vendorid);
formData.append('category', 'vendor');
formData.append('image', resizedFile);
fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/upload_image', {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
return response.json();
} else {
console.error('File upload failed');
throw new Error('File upload failed');
}
})
.then(result => {
const filename = encodeURI(result.filename);
fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/upload_image', {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
return response.json();
} else {
console.error('File upload failed');
throw new Error('File upload failed');
}
})
.then(result => {
const filename = encodeURI(result.filename);
const payload = {
vendor_image: `https://<?php echo $_SESSION["data_endpoint"]; ?>/images/storage/vendor_uploads/${filename}`,
};
const payload = {
vendor_image: `https://<?php echo $_SESSION["data_endpoint"]; ?>/images/storage/vendor_uploads/${filename}`,
};
console.log('Payload:', payload);
console.log('Payload:', payload);
return fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/vendors/' + vendorid, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
})
.then(secondResponse => {
if (secondResponse.ok) {
console.log('Second request successful');
location.reload();
} else {
console.error('Second request failed');
}
})
.catch(error => {
console.error('Error during fetch:', error);
});
}, 'image/jpeg');
};
return fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/vendors/' + vendorid, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
})
.then(secondResponse => {
if (secondResponse.ok) {
console.log('Second request successful');
location.reload();
} else {
console.error('Second request failed');
}
})
.catch(error => {
console.error('Error during fetch:', error);
});
}, 'image/jpeg');
};
img.src = event.target.result;
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
}
}
reader.readAsDataURL(file);
}
}
function uploadProfileBanner() {
var vendorid = '<?php echo $_SESSION["LoggedInVendorId"] ?>';
var file = document.getElementById('thumbUpload01').files[0];
if (file) {
const reader = new FileReader();
function uploadProfileBanner() {
var vendorid = '<?php echo $_SESSION["LoggedInVendorId"] ?>';
var file = document.getElementById('thumbUpload01').files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const maxWidth = 1200;
const maxHeight = 1000;
const aspectRatio = img.width / img.height;
let newWidth = img.width;
let newHeight = img.height;
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const maxWidth = 1200;
const maxHeight = 1000;
const aspectRatio = img.width / img.height;
let newWidth = img.width;
let newHeight = img.height;
if (img.width > maxWidth) {
newWidth = maxWidth;
newHeight = newWidth / aspectRatio;
}
if (img.width > maxWidth) {
newWidth = maxWidth;
newHeight = newWidth / aspectRatio;
}
if (newHeight > maxHeight) {
newHeight = maxHeight;
newWidth = newHeight * aspectRatio;
}
if (newHeight > maxHeight) {
newHeight = maxHeight;
newWidth = newHeight * aspectRatio;
}
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(img, 0, 0, newWidth, newHeight);
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(img, 0, 0, newWidth, newHeight);
canvas.toBlob((blob) => {
const resizedFile = new File([blob], file.name, {
type: 'image/jpeg'
});
canvas.toBlob((blob) => {
const resizedFile = new File([blob], file.name, {
type: 'image/jpeg'
});
var formData = new FormData();
formData.append('image_id', vendorid + '_banner');
formData.append('category', 'vendor');
formData.append('image', resizedFile);
var formData = new FormData();
formData.append('image_id', vendorid + '_banner');
formData.append('category', 'vendor');
formData.append('image', resizedFile);
fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/upload_image', {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
return response.json();
} else {
console.error('File upload failed');
throw new Error('File upload failed');
}
})
.then(result => {
const filename = encodeURI(result.filename);
// const filename = result.filename;
fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/upload_image', {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
return response.json();
} else {
console.error('File upload failed');
throw new Error('File upload failed');
}
})
.then(result => {
const filename = encodeURI(result.filename);
// const filename = result.filename;
const payload = {
vendor_banner: `https://<?php echo $_SESSION["data_endpoint"]; ?>/images/storage/vendor_uploads/${filename}`,
const payload = {
vendor_banner: `https://<?php echo $_SESSION["data_endpoint"]; ?>/images/storage/vendor_uploads/${filename}`,
};
};
console.log('Payload:', payload);
console.log('Payload:', payload);
return fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/vendors/' + vendorid, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
})
.then(secondResponse => {
if (secondResponse.ok) {
console.log('Second request successful');
location.reload();
} else {
console.error('Second request failed');
}
})
.catch(error => {
console.error('Error during fetch:', error);
});
}, 'image/jpeg');
};
return fetch('https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/vendors/' + vendorid, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
})
.then(secondResponse => {
if (secondResponse.ok) {
console.log('Second request successful');
location.reload();
} else {
console.error('Second request failed');
}
})
.catch(error => {
console.error('Error during fetch:', error);
});
}, 'image/jpeg');
};
img.src = event.target.result;
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
}
}
reader.readAsDataURL(file);
}
}
</script>
<div class="ec-vendor-upload-detail">