TIF_NGANJUK_E41212020/checkout/index.php

675 lines
30 KiB
PHP

<?php include '../template/template1.php'; ?>
<?php include '../template/header.php'; ?>
<?php
if (!isset($_SESSION['status_login']) || !$_SESSION['status_login']) {
echo "<script>
Swal.fire({
icon: 'warning',
title: 'Akses Ditolak!',
text: 'Harap login terlebih dahulu.',
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
window.location='/login';
}
});
</script>";
exit;
}
$id_pembeli = intval($_SESSION['id_pembeli']);
$query_pembeli = mysqli_query($conn, "SELECT * FROM pembeli WHERE id_pembeli = '$id_pembeli'");
$pembeli = mysqli_fetch_assoc($query_pembeli);
$alamat_pengiriman = htmlspecialchars($pembeli['alamat']);
$saldo_pembeli = isset($pembeli['saldo']) ? number_format($pembeli['saldo'], 0, ',', '.') : '0';
$query = mysqli_query($conn, "SELECT cart.id_cart, cart.id_produk, cart.jumlah, cart.potong, produk.nama_produk, produk.harga_jual
FROM cart
JOIN produk ON cart.id_produk = produk.id_produk
WHERE cart.id_pembeli = '$id_pembeli'");
$keranjang = [];
$total_harga = 0;
while ($row = mysqli_fetch_assoc($query)) {
$keranjang[] = $row;
$total_harga += $row['harga_jual'] * $row['jumlah'];
}
if (empty($keranjang)) {
echo "<script>
Swal.fire({
icon: 'info',
title: 'Keranjang Kosong!',
text: 'Silakan tambahkan produk ke keranjang sebelum checkout.',
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
window.location='/produk';
}
});
</script>";
exit;
}
?>
<section id="checkout" class="checkout section">
<div class="container">
<div class="section-title mt-4" data-aos="fade-up">
<h2>Checkout</h2>
<p>Silakan selesaikan pembayaran Anda.</p>
</div>
<form id="checkout-form" action="proses_checkout.php" method="POST">
<div class="row">
<div class="col-lg-8">
<div class="card shadow-sm">
<div style="background-color: #FFA836;" class="card-header text-white">
<h5 class="mb-0 text-white">Produk yang Dibeli</h5>
</div>
<div class="card-body table-responsive">
<table class="table table-bordered text-center">
<thead class="bg-light">
<tr>
<th>Produk</th>
<th>Jumlah</th>
<th>Potongan</th>
<th>Harga</th>
<th>Total Harga</th>
</tr>
</thead>
<tbody>
<?php foreach ($keranjang as $item): ?>
<tr>
<td><?= htmlspecialchars($item['nama_produk']); ?></td>
<td><?= intval($item['jumlah']); ?></td>
<td><?= intval($item['potong']); ?> potong</td>
<td>Rp<?= number_format($item['harga_jual'], 0, ',', '.'); ?></td>
<td>Rp<?= number_format($item['harga_jual'] * $item['jumlah'], 0, ',', '.'); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card shadow-sm">
<div style="background-color: #FFA836;" class="card-header text-white">
<h5 class="mb-0 text-white">Informasi Pembayaran</h5>
</div>
<div class="card-body">
<div class="mb-3">
<button type="button" class="btn btn-info w-100" data-bs-toggle="modal" data-bs-target="#shippingScheduleModal">
<i class="fas fa-truck"></i> Jadwal Pengiriman
</button>
</div>
<div class="form-group mb-3">
<label for="alamat"><strong>Alamat Pengiriman</strong></label>
<div class="input-group">
<!-- Form tampilan (readonly) -->
<div id="alamatDisplay" class="w-100">
<div class="form-control bg-light" style="min-height: 100px;"><?= $alamat_pengiriman; ?></div>
<button type="button" class="btn btn-primary mt-2" id="editAlamatBtn">
<i class="fas fa-edit text-white"></i> Ubah Alamat
</button>
</div>
<!-- Form edit (hidden by default) -->
<div id="alamatEdit" class="w-100" style="display: none;">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Nama Jalan</label>
<input type="text" id="alamat_jalan" class="form-control" required>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>RT</label>
<input type="text" id="rt" class="form-control" required>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>RW</label>
<input type="text" id="rw" class="form-control" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Kecamatan</label>
<select id="kecamatan" class="form-control" required>
<option value="">Pilih Kecamatan</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Desa/Kelurahan</label>
<select id="desa" class="form-control" required>
<option value="">Pilih Desa/Kelurahan</option>
</select>
</div>
</div>
</div>
<input type="hidden" id="nama_kecamatan">
<input type="hidden" id="alamatInput" name="alamat" value="<?= $alamat_pengiriman; ?>">
<div class="mt-2">
<button type="button" class="btn btn-success btn-sm" id="saveAlamatBtn">
<i class="fas fa-save"></i> Simpan
</button>
<button type="button" class="btn btn-danger btn-sm" id="cancelAlamatBtn">
<i class="fas fa-times"></i> Batal
</button>
</div>
</div>
</div>
</div>
<div class="form-group mb-3">
<label for="metode_pembayaran"><strong>Metode Pembayaran</strong></label>
<select id="metode_pembayaran" name="metode_pembayaran" class="form-control" required onchange="toggleQRIS()">
<option value="SALDO">SALDO - Rp<?= $saldo_pembeli; ?></option>
<option value="QRIS">QRIS - Manual Checking</option>
<option value="COD">COD - Bayar di Tempat</option>
</select>
</div>
<div id="qris-section" style="display: none; text-align: center;">
<p>Silakan scan QRIS untuk pembayaran:</p>
<img src="<?= $base_url; ?>/checkout/qris/qris_dana.png" alt="QRIS Code" class="img-fluid" style="max-width: 250px;">
<p><strong>Total: Rp<?= number_format($total_harga, 0, ',', '.'); ?></strong></p>
</div>
<div class="form-group mb-3">
<label><strong>Total Harga Produk</strong></label>
<input type="text" id="total_harga_produk" class="form-control" value="Rp<?= number_format($total_harga, 0, ',', '.'); ?>" readonly>
</div>
<div class="form-group mb-3">
<label><strong>Ongkos Kirim</strong></label>
<input type="text" id="ongkos_kirim" name="ongkos_kirim" class="form-control" readonly>
</div>
<div id="shippingInfo" class="mt-2 small text-muted">
<!-- Perhitungan real-time akan ditampilkan di sini -->
</div>
<div class="form-group mb-3">
<label><strong>Total Pembayaran</strong></label>
<input type="text" id="total_pembayaran" name="total_pembayaran" class="form-control" readonly>
</div>
<button type="submit" style="background-color: #FFA836;" class="btn w-100 text-white" onclick="return confirmCheckout(event)">Proses Pembayaran</button>
</div>
</div>
</div>
</div>
</form>
</div>
</section>
<!-- Shipping Schedule Modal -->
<div class="modal fade" id="shippingScheduleModal" tabindex="-1" aria-labelledby="shippingScheduleModalLabel" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content" style="max-height: 80vh;">
<div class="modal-header" style="background-color: #FFA836;">
<h5 class="modal-title text-white" id="shippingScheduleModalLabel">Informasi Pengiriman</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" style="overflow-y: auto; max-height: calc(80vh - 120px);">
<!-- Jadwal Pengiriman -->
<h6 class="mb-3"><i class="fas fa-clock"></i> Jadwal Pengiriman</h6>
<div class="table-responsive mb-4">
<table class="table table-bordered">
<thead class="table-light sticky-top bg-light">
<tr>
<th>Waktu Keberangkatan</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>06:00 WIB</td>
<td><span class="badge bg-success">Tersedia</span></td>
</tr>
<tr>
<td>08:00 WIB</td>
<td><span class="badge bg-success">Tersedia</span></td>
</tr>
<tr>
<td>10:00 WIB</td>
<td><span class="badge bg-success">Tersedia</span></td>
</tr>
<tr>
<td>12:00 WIB</td>
<td><span class="badge bg-success">Tersedia</span></td>
</tr>
</tbody>
</table>
</div>
<!-- Informasi Ongkos Kirim -->
<h6 class="mb-3"><i class="fas fa-truck"></i> Informasi Ongkos Kirim</h6>
<div class="table-responsive">
<table class="table table-bordered">
<thead class="table-light sticky-top bg-light">
<tr>
<th>Total Belanja</th>
<th>Dalam Kec. Nganjuk</th>
<th>Luar Kec. Nganjuk</th>
</tr>
</thead>
<tbody>
<tr>
<td>< Rp 50.000</td>
<td class="text-success">Gratis</td>
<td>Rp 5.000</td>
</tr>
<tr>
<td>Rp 50.000 - Rp 200.000</td>
<td>Rp 3.000</td>
<td>Rp 7.000</td>
</tr>
<tr>
<td>Rp 200.000 - Rp 500.000</td>
<td>Rp 5.000</td>
<td>Rp 10.000</td>
</tr>
<tr>
<td>≥ Rp 500.000</td>
<td colspan="2" class="text-center">Rp 12.000</td>
</tr>
</tbody>
</table>
</div>
<div class="alert alert-info mt-3">
<i class="fas fa-info-circle"></i> Pengiriman akan dilakukan sesuai dengan jadwal pengiriman, apabila pesanan diatas jam 11 maka akan dikirim pada esok hari.
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
</div>
</div>
</div>
</div>
<script>
function confirmCheckout(event) {
event.preventDefault();
const alamat = document.getElementById("alamatInput").value.trim();
Swal.fire({
title: 'Konfirmasi Alamat Pengiriman',
html: `
<div class="text-start">
<p>Mohon periksa kembali alamat pengiriman Anda:</p>
<div class="alert alert-info">
<strong>Alamat:</strong><br>
${alamat}
</div>
<p>Apakah alamat pengiriman sudah sesuai?</p>
</div>
`,
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#FFA836',
cancelButtonColor: '#d33',
confirmButtonText: 'Ya, Alamat Sudah Sesuai',
cancelButtonText: 'Ubah Alamat'
}).then((result) => {
if (result.isConfirmed) {
document.getElementById('checkout-form').submit();
} else {
// Trigger edit address button click
document.getElementById('editAlamatBtn').click();
}
});
return false;
}
function toggleQRIS() {
const metode = document.getElementById("metode_pembayaran").value;
document.getElementById("qris-section").style.display = metode === "QRIS" ? "block" : "none";
}
// Function to check shipping schedule availability
function updateShippingSchedule() {
const now = new Date();
const currentHour = now.getHours();
const currentMinute = now.getMinutes();
const currentTime = currentHour + (currentMinute / 60);
const schedules = [
{ time: 6, element: document.querySelector('tr:nth-child(1) .badge') },
{ time: 8, element: document.querySelector('tr:nth-child(2) .badge') },
{ time: 10, element: document.querySelector('tr:nth-child(3) .badge') },
{ time: 12, element: document.querySelector('tr:nth-child(4) .badge') }
];
schedules.forEach(schedule => {
if (currentTime >= (schedule.time - 0.5)) {
schedule.element.className = 'badge bg-danger';
schedule.element.textContent = 'Tidak Tersedia';
} else {
schedule.element.className = 'badge bg-success';
schedule.element.textContent = 'Tersedia';
}
});
}
// Address editing functionality
document.addEventListener("DOMContentLoaded", function() {
const alamatDisplay = document.getElementById("alamatDisplay");
const alamatEdit = document.getElementById("alamatEdit");
const alamatInput = document.getElementById("alamatInput");
const editAlamatBtn = document.getElementById("editAlamatBtn");
const saveAlamatBtn = document.getElementById("saveAlamatBtn");
const cancelAlamatBtn = document.getElementById("cancelAlamatBtn");
let originalAlamat = alamatInput.value;
editAlamatBtn.addEventListener("click", function() {
alamatDisplay.style.display = 'none';
alamatEdit.style.display = 'block';
alamatInput.focus();
});
saveAlamatBtn.addEventListener("click", function() {
const jalan = document.getElementById('alamat_jalan').value.trim();
const rt = document.getElementById('rt').value.trim();
const rw = document.getElementById('rw').value.trim();
const kecamatan = $('#kecamatan option:selected').text();
const desa = $('#desa option:selected').text();
if (!jalan || !rt || !rw || !kecamatan || !desa) {
Swal.fire({
icon: 'error',
title: 'Gagal!',
text: 'Semua field alamat harus diisi!',
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
});
return;
}
// Format address
const formattedAddress = `${jalan}, RT ${rt}/RW ${rw}, ${kecamatan}, ${desa}`;
alamatInput.value = formattedAddress;
// Continue with existing save functionality
const newAlamat = formattedAddress;
if (newAlamat === '') {
Swal.fire({
icon: 'error',
title: 'Gagal!',
text: 'Alamat tidak boleh kosong!',
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
});
return;
}
// Disable buttons while saving
saveAlamatBtn.disabled = true;
cancelAlamatBtn.disabled = true;
// Save to database using AJAX
fetch('update_alamat.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
alamat: newAlamat
})
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (data.success) {
// Update display with new address
alamatDisplay.querySelector('.form-control').textContent = newAlamat;
originalAlamat = newAlamat;
// Switch back to display mode
alamatDisplay.style.display = 'block';
alamatEdit.style.display = 'none';
// Update shipping cost and total
updateTotalPayment();
Swal.fire({
icon: 'success',
title: 'Berhasil!',
text: data.message,
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
});
} else {
throw new Error(data.message || 'Gagal menyimpan alamat');
}
})
.catch(error => {
Swal.fire({
icon: 'error',
title: 'Gagal!',
text: error.message,
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
});
})
.finally(() => {
// Re-enable buttons
saveAlamatBtn.disabled = false;
cancelAlamatBtn.disabled = false;
});
});
cancelAlamatBtn.addEventListener("click", function() {
alamatInput.value = originalAlamat;
alamatDisplay.style.display = 'block';
alamatEdit.style.display = 'none';
});
// Show modal automatically when page loads
var shippingModal = new bootstrap.Modal(document.getElementById('shippingScheduleModal'));
shippingModal.show();
// Update shipping schedule status
updateShippingSchedule();
// Update status every minute
setInterval(updateShippingSchedule, 60000);
// Initial calculation of shipping cost
updateTotalPayment();
});
async function calculateShippingCost(totalHarga, alamat) {
try {
const response = await fetch('calculate_shipping.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
total_harga: totalHarga,
alamat: alamat
})
});
if (!response.ok) {
throw new Error('Gagal menghitung ongkos kirim');
}
const data = await response.json();
if (!data.success) {
throw new Error(data.message || 'Gagal menghitung ongkos kirim');
}
return data.ongkos_kirim;
} catch (error) {
console.error('Shipping error:', error);
Swal.fire({
icon: 'error',
title: 'Gagal!',
text: error.message,
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
});
return 0;
}
}
async function updateTotalPayment() {
const totalHargaProduk = <?= $total_harga; ?>;
const alamat = document.getElementById("alamatInput").value.trim();
if (alamat === '') {
document.getElementById("ongkos_kirim").value = "Rp0";
document.getElementById("total_pembayaran").value = "Rp" + parseFloat(totalHargaProduk).toLocaleString('id-ID');
return;
}
try {
const ongkir = await calculateShippingCost(parseFloat(totalHargaProduk), alamat);
const totalBayar = parseFloat(totalHargaProduk) + parseFloat(ongkir);
// Update shipping cost display
document.getElementById("ongkos_kirim").value = "Rp" + parseFloat(ongkir).toLocaleString('id-ID');
document.getElementById("total_pembayaran").value = "Rp" + parseFloat(totalBayar).toLocaleString('id-ID');
// Update QRIS total if visible
if (document.getElementById("qris-section").style.display === "block") {
document.querySelector("#qris-section strong").textContent = "Total: Rp" + parseFloat(totalBayar).toLocaleString('id-ID');
}
// Update shipping info with current calculation
const isNganjuk = alamat.toLowerCase().includes('nganjuk');
let shippingDetail = '';
if (totalHargaProduk < 50000) {
shippingDetail = isNganjuk ?
'Gratis (dalam Nganjuk)' :
'Rp 5.000 (luar Nganjuk)';
} else if (totalHargaProduk >= 50000 && totalHargaProduk < 200000) {
shippingDetail = isNganjuk ?
'Rp 3.000 (dalam Nganjuk)' :
'Rp 5.000 (luar Nganjuk)';
} else if (totalHargaProduk >= 200000 && totalHargaProduk < 500000) {
shippingDetail = isNganjuk ?
'Rp 5.000 (dalam Nganjuk)' :
'Rp 7.000 (luar Nganjuk)';
} else {
shippingDetail = 'Rp 10.000 (semua daerah)';
}
// Add current calculation to shipping info
const currentInfo = document.createElement('div');
currentInfo.className = 'alert alert-success mt-2 mb-0';
currentInfo.innerHTML = `
<i class="fas fa-truck"></i> Perhitungan Ongkos Kirim Anda:
<ul class="mb-0 mt-1">
<li>Total Belanja: Rp ${parseFloat(totalHargaProduk).toLocaleString('id-ID')}</li>
<li>Lokasi: ${isNganjuk ? 'Dalam Nganjuk' : 'Luar Nganjuk'}</li>
<li>Ongkos Kirim: ${shippingDetail}</li>
</ul>
`;
// Remove previous calculation if exists
const oldInfo = document.querySelector('.alert-success');
if (oldInfo) oldInfo.remove();
// Add new calculation
document.getElementById('shippingInfo').appendChild(currentInfo);
} catch (error) {
console.error('Error updating total:', error);
}
}
// Add this at the beginning of your script section
$(document).ready(function() {
// Load kecamatan data
$.getJSON("https://ibnux.github.io/data-indonesia/kecamatan/3518.json", function(data) {
var options = '<option value="">Pilih Kecamatan</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.id + '" data-nama="' + val.nama + '">' + val.nama + '</option>';
});
$("#kecamatan").html(options);
});
// Handle kecamatan change
$('#kecamatan').change(function() {
var kecamatanId = $(this).val();
var namaKecamatan = $("#kecamatan option:selected").attr("data-nama");
$('#nama_kecamatan').val(namaKecamatan);
if(kecamatanId) {
$.getJSON("https://ibnux.github.io/data-indonesia/kelurahan/" + kecamatanId + ".json", function(data) {
var options = '<option value="">Pilih Desa/Kelurahan</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.nama + '">' + val.nama + '</option>';
});
$("#desa").html(options);
});
} else {
$("#desa").html('<option value="">Pilih Desa/Kelurahan</option>');
}
});
// Parse existing address when editing
editAlamatBtn.addEventListener("click", function() {
const fullAddress = alamatInput.value;
const addressParts = fullAddress.split(', ');
if (addressParts.length >= 4) {
// Extract street
document.getElementById('alamat_jalan').value = addressParts[0];
// Extract RT/RW
const rtRw = addressParts[1].split('/');
if (rtRw.length === 2) {
document.getElementById('rt').value = rtRw[0].replace('RT ', '');
document.getElementById('rw').value = rtRw[1].replace('RW ', '');
}
// Set kecamatan
const kecamatan = addressParts[2];
$('#kecamatan option').each(function() {
if ($(this).text() === kecamatan) {
$(this).prop('selected', true);
$('#kecamatan').trigger('change');
}
});
// Set desa after a short delay to allow desa options to load
setTimeout(() => {
const desa = addressParts[3];
$('#desa option').each(function() {
if ($(this).text() === desa) {
$(this).prop('selected', true);
}
});
}, 500);
}
});
});
</script>
<?php include '../template/footer.php'; ?>
<?php include '../template/template2.php'; ?>