/home/ejrndhmu/tokobiolink.com/package_checkout.php
<?php
session_start();
require_once 'config/database.php';
require_once 'includes/functions.php';
// Ambil ID paket dari URL
$packageId = intval($_GET['id'] ?? 0);
if ($packageId <= 0) {
die('ID paket tidak valid');
}
// Ambil data paket
$package = getResellerPackageById($packageId);
if (!$package) {
die('Paket tidak ditemukan atau tidak aktif');
}
// Ambil data reseller
$reseller = getUserById($package['reseller_id']);
if (!$reseller || $reseller['role'] !== 'reseller') {
die('Reseller tidak ditemukan');
}
// Ambil metode pembayaran reseller yang aktif
$paymentAccounts = [];
try {
$paymentAccounts = getResellerPaymentAccounts($package['reseller_id']);
} catch (Exception $e) {
error_log("Error getting reseller payment accounts: " . $e->getMessage());
}
// Check if user is already logged in
$currentUser = null;
$isLoggedIn = false;
if (isset($_SESSION['user_id'])) {
$currentUser = getUserById($_SESSION['user_id']);
if ($currentUser && $currentUser['status'] === 'active') {
$isLoggedIn = true;
}
}
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$customerName = trim($_POST['customer_name'] ?? '');
$customerEmail = trim($_POST['customer_email'] ?? '');
$customerPhone = trim($_POST['customer_phone'] ?? '');
$customerPassword = trim($_POST['customer_password'] ?? '');
$paymentAccountId = intval($_POST['payment_account_id'] ?? 0);
// Validasi
$errors = [];
if (empty($customerName)) $errors[] = 'Nama lengkap harus diisi';
if (empty($customerEmail) || !filter_var($customerEmail, FILTER_VALIDATE_EMAIL)) $errors[] = 'Email tidak valid';
if (empty($customerPhone)) $errors[] = 'Nomor WhatsApp harus diisi';
if (empty($customerPassword) || strlen($customerPassword) < 6) $errors[] = 'Password minimal 6 karakter';
if ($paymentAccountId <= 0) $errors[] = 'Pilih metode pembayaran';
// Cek apakah email sudah terdaftar (kecuali jika user sudah login dengan email yang sama)
if (empty($errors)) {
$existingUser = getUserByEmail($customerEmail);
if ($existingUser && (!$isLoggedIn || $existingUser['id'] !== $currentUser['id'])) {
$errors['email_exists'] = 'Email ini sudah terdaftar. <a href="login.php" class="text-blue-600 hover:underline font-medium">Login di sini</a> atau gunakan email lain.';
}
// Cek apakah ada pesanan pending dengan email yang sama
try {
$db = new Database();
$db->query("SELECT id FROM reseller_orders WHERE customer_email = ? AND status IN ('pending', 'paid')");
$db->bind(1, $customerEmail);
$pendingOrder = $db->single();
if ($pendingOrder) {
$errors[] = 'Anda masih memiliki pesanan yang belum selesai dengan email ini.';
}
} catch (Exception $e) {
error_log("Error checking pending orders: " . $e->getMessage());
}
}
if (empty($errors)) {
$orderData = [
'reseller_id' => $package['reseller_id'],
'package_id' => $packageId,
'customer_name' => $customerName,
'customer_email' => $customerEmail,
'customer_phone' => $customerPhone,
'customer_password' => $customerPassword,
'total_amount' => $package['price'],
'payment_account_id' => $paymentAccountId
];
$result = createResellerOrder($orderData);
if ($result['success']) {
// Sinkronisasi ke Mailketing untuk customer baru
require_once 'includes/mailketing.php';
$mailketingSettings = getMailketingSettings();
if ($mailketingSettings && $mailketingSettings['auto_sync'] == '1') {
try {
$userData = [
'email' => $customerEmail,
'full_name' => $customerName,
'username' => $customerEmail, // Use email as username for package checkout
'phone' => $customerPhone,
'mobile' => $customerPhone,
'role' => 'customer',
'status' => 'pending' // Status pending untuk customer yang baru checkout
];
syncUserToMailketing($userData);
error_log("Customer from package checkout synced to Mailketing: {$customerEmail}");
} catch (Exception $e) {
error_log("Failed to sync package checkout customer to Mailketing: " . $e->getMessage());
}
}
// Send email notification if enabled
if (getSetting('email_notifications_enabled') == '1' && getSetting('email_checkout_notifications') == '1') {
try {
require_once 'includes/email.php';
// Prepare email data
$siteName = getSetting('site_name') ?: 'Sistem Reseller';
$orderDate = date('d/m/Y H:i');
$emailData = [
'customer_name' => $customerName,
'customer_email' => $customerEmail,
'order_number' => $result['order_number'],
'reseller_name' => $reseller['full_name'],
'package_name' => $package['name'],
'package_price' => 'Rp ' . number_format($package['price'], 0, ',', '.'),
'order_date' => $orderDate,
'site_name' => $siteName
];
// Send email to customer using Mailketing API
$customerEmailSent = sendMailketingCheckoutNotification($customerEmail, $emailData);
// Send notification to admin using Mailketing API
$adminEmailSent = sendMailketingAdminOrderNotification($emailData);
if ($customerEmailSent) {
error_log("Checkout notification sent to customer: {$customerEmail}");
}
if ($adminEmailSent) {
error_log("Admin notification sent for order: {$result['order_number']}");
}
$resellerSubject = 'Order Baru dari Customer - ' . $customerName;
$resellerMessage = "Order baru dari customer:\n\n";
$resellerMessage .= "Customer: {$customerName} ({$customerEmail})\n";
$resellerMessage .= "Paket: {$package['name']}\n";
$resellerMessage .= "Harga: Rp " . number_format($package['price'], 0, ',', '.') . "\n";
$resellerMessage .= "Tanggal: {$orderDate}\n\n";
$resellerMessage .= "Silakan login ke panel reseller untuk mengaktifkan paket customer.";
sendMailketingEmail($reseller['email'], $resellerSubject, $resellerMessage, $emailData);
} catch (Exception $e) {
error_log('Error sending checkout notification email: ' . $e->getMessage());
}
}
// Redirect ke halaman invoice
header('Location: package_invoice.php?order=' . $result['order_number']);
exit;
} else {
$errors[] = $result['message'];
}
}
}
// Decode features dan product access
$features = json_decode($package['features'] ?? '[]', true) ?: [];
$productAccess = json_decode($package['product_access'] ?? '[]', true) ?: [];
// Ambil nama produk
$productNames = [];
if (!empty($productAccess)) {
try {
$db = new Database();
$placeholders = str_repeat('?,', count($productAccess) - 1) . '?';
$db->query("SELECT name FROM products WHERE id IN ($placeholders) AND status = 'active'");
foreach ($productAccess as $index => $productId) {
$db->bind($index + 1, $productId);
}
$products = $db->resultset();
$productNames = array_column($products, 'name');
} catch (Exception $e) {
error_log("Error getting product names: " . $e->getMessage());
}
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Checkout - <?= htmlspecialchars($package['name']) ?></title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<?php
// Add Meta Pixel for checkout tracking
if ($package && $package['reseller_id']) {
echo getMetaPixelCode($package['reseller_id'], 'checkout');
}
?>
</head>
<body class="bg-gray-50">
<div class="min-h-screen py-8">
<div class="max-w-4xl mx-auto px-4">
<!-- Header -->
<div class="text-center mb-8">
</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
<!-- Package Info -->
<div class="bg-white rounded-lg shadow-md p-6">
<h2 class="text-xl font-semibold text-gray-800 mb-4">
<i class="fas fa-box-open text-blue-500 mr-2"></i>
Detail Paket
</h2>
<?php if (!empty($package['banner_url'])): ?>
<div class="mb-6">
<img src="<?= htmlspecialchars($package['banner_url']) ?>"
alt="Banner <?= htmlspecialchars($package['name']) ?>"
class="w-full h-48 object-contain rounded-lg border border-gray-200 bg-gray-50"
onerror="this.style.display='none'">
</div>
<?php endif; ?>
<div class="space-y-4">
<div>
<h3 class="text-lg font-medium text-gray-800"><?= htmlspecialchars($package['name']) ?></h3>
<p class="text-gray-600 mt-1"><?= htmlspecialchars($package['description']) ?></p>
</div>
<div class="flex justify-between items-center py-2 border-t">
<span class="text-gray-600">Harga:</span>
<span class="text-2xl font-bold text-blue-600">Rp <?= number_format($package['price'], 0, ',', '.') ?></span>
</div>
<div class="flex justify-between items-center py-2">
<span class="text-gray-600">Durasi:</span>
<span class="font-medium"><?= $package['duration_days'] ?> hari</span>
</div>
<?php if (!empty($features)): ?>
<div class="py-2">
<h4 class="font-medium text-gray-800 mb-2">Fitur Paket:</h4>
<ul class="space-y-1">
<?php foreach ($features as $feature): ?>
<li class="flex items-center text-sm text-gray-600">
<i class="fas fa-check text-green-500 mr-2"></i>
<?= htmlspecialchars($feature) ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if (!empty($productNames)): ?>
<div class="py-2">
<h4 class="font-medium text-gray-800 mb-2">Akses Produk:</h4>
<ul class="space-y-1">
<?php foreach ($productNames as $productName): ?>
<li class="flex items-center text-sm text-gray-600">
<i class="fas fa-download text-blue-500 mr-2"></i>
<?= htmlspecialchars($productName) ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
</div>
</div>
<!-- Checkout Form -->
<div class="bg-white rounded-lg shadow-md p-6">
<!-- Toggle Buttons -->
<?php if (!$isLoggedIn): ?>
<div class="flex mb-6">
<button type="button" id="toggleRegister" class="flex-1 py-2 px-4 text-center font-medium rounded-l-lg bg-blue-600 text-white">
Daftar Baru
</button>
<button type="button" id="toggleLogin" class="flex-1 py-2 px-4 text-center font-medium rounded-r-lg bg-gray-200 text-gray-700 hover:bg-gray-300">
Login
</button>
</div>
<?php else: ?>
<div class="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg mb-6">
<div class="flex items-center">
<i class="fas fa-user-check mr-2"></i>
<span class="font-medium">Login sebagai: <?= htmlspecialchars($currentUser['full_name']) ?> (<?= htmlspecialchars($currentUser['email']) ?>)</span>
</div>
<div class="mt-2">
<button type="button" onclick="logoutUser()" class="text-sm text-green-600 hover:underline bg-transparent border-none cursor-pointer">Logout</button>
</div>
</div>
<?php endif; ?>
<!-- Login Form -->
<?php if (!$isLoggedIn): ?>
<div id="loginForm" class="hidden">
<h3 class="text-lg font-semibold text-gray-800 mb-4 text-center">Masuk dengan Akun Anda</h3>
<form id="loginFormElement" method="POST" class="space-y-4">
<div>
<label for="login_username" class="block text-sm font-medium text-gray-700 mb-1">Email/Username *</label>
<input type="text" id="login_username" name="username"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required>
</div>
<div>
<label for="login_password" class="block text-sm font-medium text-gray-700 mb-1">Password *</label>
<input type="password" id="login_password" name="password"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required>
</div>
<div class="pt-4">
<button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg transition duration-200">
<i class="fas fa-sign-in-alt mr-2"></i>
Masuk
</button>
</div>
</form>
<div class="mt-4 text-center">
<p class="text-sm text-gray-600">
<a href="#" onclick="forgotPassword()" class="text-blue-600 hover:underline font-medium">Lupa Password?</a>
</p>
</div>
</div>
<!-- Forgot Password Modal -->
<div id="forgotPasswordModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center">
<div class="bg-white rounded-lg p-6 w-full max-w-md mx-4">
<div class="flex justify-between items-center mb-4">
<h3 class="text-lg font-semibold text-gray-800">Reset Password</h3>
<button type="button" onclick="closeForgotPasswordModal()" class="text-gray-400 hover:text-gray-600">
<i class="fas fa-times"></i>
</button>
</div>
<form id="forgotPasswordForm" class="space-y-4">
<div>
<label for="forgot_email" class="block text-sm font-medium text-gray-700 mb-1">Email *</label>
<input type="email" id="forgot_email" name="email"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
placeholder="Masukkan email Anda" required>
</div>
<div class="pt-4">
<button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg transition duration-200">
<i class="fas fa-paper-plane mr-2"></i>
Kirim Password Baru
</button>
</div>
</form>
<div id="forgotPasswordMessage" class="mt-4 hidden"></div>
</div>
</div>
<!-- Register Form -->
<div id="registerFormContainer">
<h2 class="text-xl font-semibold text-gray-800 mb-4">
<i class="fas fa-user text-green-500 mr-2"></i>
Daftar Akun Baru
</h2>
<?php if (!empty($errors)): ?>
<div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-4">
<ul class="list-disc list-inside space-y-1">
<?php foreach ($errors as $key => $error): ?>
<li>
<?php if ($key === 'email_exists'): ?>
<?= $error ?>
<?php else: ?>
<?= htmlspecialchars($error) ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="" class="space-y-4">
<div>
<label for="customer_name" class="block text-sm font-medium text-gray-700 mb-1">Nama Lengkap *</label>
<input type="text" id="customer_name" name="customer_name"
value="<?= htmlspecialchars($_POST['customer_name'] ?? '') ?>"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required>
</div>
<div>
<label for="customer_email" class="block text-sm font-medium text-gray-700 mb-1">Email *</label>
<input type="email" id="customer_email" name="customer_email"
value="<?= htmlspecialchars($_POST['customer_email'] ?? '') ?>"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required>
</div>
<div>
<label for="customer_phone" class="block text-sm font-medium text-gray-700 mb-1">Nomor WhatsApp *</label>
<input type="tel" id="customer_phone" name="customer_phone"
value="<?= htmlspecialchars($_POST['customer_phone'] ?? '') ?>"
placeholder="628xxxxxxxxx"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required>
</div>
<div>
<label for="customer_password" class="block text-sm font-medium text-gray-700 mb-1">Password Akun *</label>
<input type="password" id="customer_password" name="customer_password"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
minlength="6" required>
<p class="text-xs text-gray-500 mt-1">Password untuk login ke akun Anda (minimal 6 karakter)</p>
</div>
<div>
<label for="payment_account_id" class="block text-sm font-medium text-gray-700 mb-1">Metode Pembayaran *</label>
<select id="payment_account_id" name="payment_account_id"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required>
<option value="">Pilih metode pembayaran</option>
<?php foreach ($paymentAccounts as $account): ?>
<option value="<?= $account['id'] ?>"
<?= (isset($_POST['payment_account_id']) && $_POST['payment_account_id'] == $account['id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($account['account_name']) ?> - <?= htmlspecialchars($account['account_number']) ?>
<?= $account['bank_name'] ? ' (' . htmlspecialchars($account['bank_name']) . ')' : '' ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="pt-4">
<button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg transition duration-200">
<i class="fas fa-shopping-cart mr-2"></i>
Buat Pesanan - Rp <?= number_format($package['price'], 0, ',', '.') ?>
</button>
</div>
</form>
<div class="mt-4 text-center">
</div>
<div class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
<p class="text-xs text-yellow-800">
<i class="fas fa-info-circle mr-1"></i>
<strong>Catatan:</strong> Setelah melakukan pemesanan, Anda akan diarahkan ke halaman invoice untuk melakukan pembayaran. Akun Anda akan diaktifkan setelah pembayaran dikonfirmasi oleh reseller.
</p>
</div>
</div>
<?php else: ?>
<!-- Checkout Form for Logged In User -->
<div id="loggedInCheckoutForm">
<h2 class="text-xl font-semibold text-gray-800 mb-4">
<i class="fas fa-shopping-cart text-blue-500 mr-2"></i>
Checkout Paket Langganan
</h2>
<?php if (!empty($errors)): ?>
<div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-4">
<ul class="list-disc list-inside space-y-1">
<?php foreach ($errors as $error): ?>
<li>
<?php if (is_array($error)): ?>
<?= htmlspecialchars($error[0]) ?>
<?php else: ?>
<?= htmlspecialchars($error) ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="" class="space-y-4">
<!-- Hidden fields for logged in user -->
<input type="hidden" name="customer_name" value="<?= htmlspecialchars($currentUser['full_name']) ?>">
<input type="hidden" name="customer_email" value="<?= htmlspecialchars($currentUser['email']) ?>">
<input type="hidden" name="customer_phone" value="<?= htmlspecialchars($currentUser['whatsapp_number'] ?? '') ?>">
<!-- Display user info -->
<div class="bg-gray-50 p-4 rounded-lg">
<h3 class="font-medium text-gray-800 mb-2">Detail Pelanggan:</h3>
<p class="text-sm text-gray-600">Nama: <?= htmlspecialchars($currentUser['full_name']) ?></p>
<p class="text-sm text-gray-600">Email: <?= htmlspecialchars($currentUser['email']) ?></p>
<?php if (!empty($currentUser['whatsapp_number'])): ?>
<p class="text-sm text-gray-600">WhatsApp: <?= htmlspecialchars($currentUser['whatsapp_number']) ?></p>
<?php endif; ?>
</div>
<!-- Phone number if not set -->
<?php if (empty($currentUser['whatsapp_number'])): ?>
<div>
<label for="customer_phone" class="block text-sm font-medium text-gray-700 mb-1">Nomor WhatsApp *</label>
<input type="tel" id="customer_phone" name="customer_phone"
value="<?= htmlspecialchars($_POST['customer_phone'] ?? '') ?>"
placeholder="628xxxxxxxxx"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required>
</div>
<?php endif; ?>
<div>
<label for="payment_account_id" class="block text-sm font-medium text-gray-700 mb-1">Metode Pembayaran *</label>
<select id="payment_account_id" name="payment_account_id"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required>
<option value="">Pilih metode pembayaran</option>
<?php foreach ($paymentAccounts as $account): ?>
<option value="<?= $account['id'] ?>"
<?= (isset($_POST['payment_account_id']) && $_POST['payment_account_id'] == $account['id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($account['account_name']) ?> - <?= htmlspecialchars($account['account_number']) ?>
<?= $account['bank_name'] ? ' (' . htmlspecialchars($account['bank_name']) . ')' : '' ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="pt-4">
<button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg transition duration-200">
<i class="fas fa-shopping-cart mr-2"></i>
Buat Pesanan - Rp <?= number_format($package['price'], 0, ',', '.') ?>
</button>
</div>
</form>
<div class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
<p class="text-xs text-green-800">
<i class="fas fa-shield-alt mr-1"></i>
<strong>Transaksi Anda Aman</strong>
</p>
</div>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Get toggle buttons (only if user is not logged in)
const toggleLogin = document.getElementById('toggleLogin');
const toggleRegister = document.getElementById('toggleRegister');
// Only initialize toggle functionality if buttons exist (user not logged in)
if (toggleLogin && toggleRegister) {
// Functions to show/hide forms
function showLoginForm() {
document.getElementById('loginForm').classList.remove('hidden');
document.getElementById('registerFormContainer').classList.add('hidden');
// Update button styles
toggleLogin.classList.remove('bg-gray-200', 'text-gray-700');
toggleLogin.classList.add('bg-blue-600', 'text-white');
toggleRegister.classList.remove('bg-blue-600', 'text-white');
toggleRegister.classList.add('bg-gray-200', 'text-gray-700');
}
function showRegisterForm() {
document.getElementById('registerFormContainer').classList.remove('hidden');
document.getElementById('loginForm').classList.add('hidden');
// Update button styles
toggleRegister.classList.remove('bg-gray-200', 'text-gray-700');
toggleRegister.classList.add('bg-blue-600', 'text-white');
toggleLogin.classList.remove('bg-blue-600', 'text-white');
toggleLogin.classList.add('bg-gray-200', 'text-gray-700');
}
// Initialize forms visibility
showRegisterForm(); // Default to register form
// Add event listeners
toggleLogin.addEventListener('click', showLoginForm);
toggleRegister.addEventListener('click', showRegisterForm);
// Handle login link in error messages
document.addEventListener('click', function(e) {
if (e.target.matches('a[href="login.php"]')) {
e.preventDefault();
// Show login form instead of redirecting
showLoginForm();
// Scroll to login form
document.getElementById('loginForm').scrollIntoView({ behavior: 'smooth' });
// Focus on username input
setTimeout(() => {
const usernameInput = document.querySelector('#loginForm input[name="username"]');
if (usernameInput) {
usernameInput.focus();
}
}, 300);
}
});
// Handle login form submission via AJAX
const loginFormElement = document.getElementById('loginFormElement');
if (loginFormElement) {
loginFormElement.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
formData.append('ajax_login', '1');
// Show loading state
const submitBtn = this.querySelector('button[type="submit"]');
const originalText = submitBtn.textContent;
submitBtn.textContent = 'Memproses...';
submitBtn.disabled = true;
fetch('login.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Login successful, reload page to show logged in state
window.location.reload();
} else {
// Show error message
let errorDiv = document.querySelector('#loginFormElement .error-message');
if (!errorDiv) {
errorDiv = document.createElement('div');
errorDiv.className = 'error-message bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-4';
this.insertBefore(errorDiv, this.firstChild);
}
errorDiv.textContent = data.message || 'Login gagal. Silakan coba lagi.';
// Reset button
submitBtn.textContent = originalText;
submitBtn.disabled = false;
}
})
.catch(error => {
console.error('Login error:', error);
// Reset button
submitBtn.textContent = originalText;
submitBtn.disabled = false;
});
});
}
} // End of if (toggleLogin && toggleRegister)
});
// Function to logout user
function logoutUser() {
fetch('config/logout.php', {
method: 'GET'
})
.then(() => {
// Reload page to show initial form state
window.location.reload();
})
.catch(error => {
console.error('Logout error:', error);
// Still reload page even if there's an error
window.location.reload();
});
}
// Function to handle forgot password
function forgotPassword() {
document.getElementById('forgotPasswordModal').classList.remove('hidden');
}
// Function to close forgot password modal
function closeForgotPasswordModal() {
document.getElementById('forgotPasswordModal').classList.add('hidden');
document.getElementById('forgotPasswordForm').reset();
document.getElementById('forgotPasswordMessage').classList.add('hidden');
}
// Handle forgot password form submission
document.addEventListener('DOMContentLoaded', function() {
const forgotPasswordForm = document.getElementById('forgotPasswordForm');
if (forgotPasswordForm) {
forgotPasswordForm.addEventListener('submit', function(e) {
e.preventDefault();
const email = document.getElementById('forgot_email').value.trim();
const messageDiv = document.getElementById('forgotPasswordMessage');
const submitBtn = this.querySelector('button[type="submit"]');
const originalText = submitBtn.innerHTML;
// Show loading state
submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Mengirim...';
submitBtn.disabled = true;
fetch('forgot_password.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'email=' + encodeURIComponent(email)
})
.then(response => response.json())
.then(data => {
messageDiv.className = 'mt-4 p-3 rounded-lg ' +
(data.success ? 'bg-green-50 border border-green-200 text-green-700' : 'bg-red-50 border border-red-200 text-red-700');
messageDiv.textContent = data.message;
messageDiv.classList.remove('hidden');
if (data.success) {
setTimeout(() => {
closeForgotPasswordModal();
}, 3000);
}
// Reset button
submitBtn.innerHTML = originalText;
submitBtn.disabled = false;
})
.catch(error => {
console.error('Forgot password error:', error);
messageDiv.className = 'mt-4 p-3 rounded-lg bg-red-50 border border-red-200 text-red-700';
messageDiv.textContent = 'Terjadi kesalahan. Silakan coba lagi.';
messageDiv.classList.remove('hidden');
// Reset button
submitBtn.innerHTML = originalText;
submitBtn.disabled = false;
});
});
}
});
</script>
</body>
</html>