<?php
require_once '../includes/config.php';
$pageTitle = "Checkout";

// Check if user is logged in
if (!isUserLoggedIn()) {
    // Save intended destination
    $_SESSION['redirect_after_login'] = SITE_URL . 'checkout/';
    redirect(SITE_URL . 'user/login.php');
}

// Check if cart is empty
if (!isset($_SESSION['cart']) || empty($_SESSION['cart'])) {
    $_SESSION['cart_message'] = "Keranjang belanja Anda kosong. Silakan tambahkan produk ke keranjang terlebih dahulu.";
    redirect(SITE_URL . 'cart/');
}

// Get user information
try {
    $conn = connectDB();
    $user_id = $_SESSION['user_id'];
    
    $stmt = $conn->prepare("SELECT * FROM users WHERE user_id = :user_id");
    $stmt->bindParam(':user_id', $user_id);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Calculate cart total
    $cartItems = array();
    $totalAmount = 0;
    
    foreach ($_SESSION['cart'] as $product_id => $quantity) {
        $stmt = $conn->prepare("SELECT * FROM products WHERE product_id = :product_id");
        $stmt->bindParam(':product_id', $product_id);
        $stmt->execute();
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($product) {
            $subtotal = $quantity * $product['price'];
            $cartItems[] = array(
                'product_id' => $product_id,
                'name' => $product['name'],
                'price' => $product['price'],
                'quantity' => $quantity,
                'subtotal' => $subtotal,
                'stock' => $product['stock']
            );
            
            $totalAmount += $subtotal;
        }
    }
} catch (PDOException $e) {
    $error = "Error: " . $e->getMessage();
}

// Process checkout form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name']);
    $address = sanitize($_POST['address']);
    $phone = sanitize($_POST['phone']);
    $notes = isset($_POST['notes']) ? sanitize($_POST['notes']) : '';
    $delivery_method = isset($_POST['delivery_method']) ? sanitize($_POST['delivery_method']) : 'regular';
    $payment_method = isset($_POST['payment_method']) ? sanitize($_POST['payment_method']) : 'transfer';
    
    // Calculate shipping cost
    $shipping_cost = 10000; // Default regular shipping
    if ($delivery_method === 'gojek' || $delivery_method === 'grab') {
        $shipping_cost = 15000;
    }
    
    // Final total with shipping (no additional fee for COD)
    $finalTotal = $totalAmount + $shipping_cost;
    
    // Validate input
    $errors = array();
    
    if (empty($name)) {
        $errors[] = "Nama penerima harus diisi";
    }
    
    if (empty($address)) {
        $errors[] = "Alamat pengiriman harus diisi";
    }
    
    if (empty($phone)) {
        $errors[] = "Nomor telepon harus diisi";
    }
    
    if (empty($errors)) {
        try {
            $conn->beginTransaction();
            
            // Create order
            $stmt = $conn->prepare("INSERT INTO orders (user_id, total_amount, status, shipping_method, payment_method, created_at) 
                                   VALUES (:user_id, :total_amount, 'pending', :shipping_method, :payment_method, NOW())");
            $stmt->bindParam(':user_id', $user_id);
            $stmt->bindParam(':total_amount', $finalTotal);
            $stmt->bindParam(':shipping_method', $delivery_method);
            $stmt->bindParam(':payment_method', $payment_method);
            $stmt->execute();
            
            $order_id = $conn->lastInsertId();
            
            // Add order items
            foreach ($cartItems as $item) {
                $stmt = $conn->prepare("INSERT INTO order_items (order_id, product_id, quantity, price) 
                                       VALUES (:order_id, :product_id, :quantity, :price)");
                $stmt->bindParam(':order_id', $order_id);
                $stmt->bindParam(':product_id', $item['product_id']);
                $stmt->bindParam(':quantity', $item['quantity']);
                $stmt->bindParam(':price', $item['price']);
                $stmt->execute();
                
                // Update product stock
                $new_stock = $item['stock'] - $item['quantity'];
                $stmt = $conn->prepare("UPDATE products SET stock = :stock WHERE product_id = :product_id");
                $stmt->bindParam(':stock', $new_stock);
                $stmt->bindParam(':product_id', $item['product_id']);
                $stmt->execute();
            }
            
            // Update user info if needed
            if ($user['address'] != $address || $user['phone'] != $phone) {
                $stmt = $conn->prepare("UPDATE users SET address = :address, phone = :phone WHERE user_id = :user_id");
                $stmt->bindParam(':address', $address);
                $stmt->bindParam(':phone', $phone);
                $stmt->bindParam(':user_id', $user_id);
                $stmt->execute();
            }
            
            $conn->commit();
            
            // Clear cart
            $_SESSION['cart'] = array();
            
            // Redirect to success page
            $_SESSION['order_id'] = $order_id;
            redirect(SITE_URL . 'checkout/success.php');
            
        } catch (PDOException $e) {
            $conn->rollBack();
            $error = "Error: " . $e->getMessage();
        }
    }
}

include '../includes/header.php';
?>

<div class="checkout-page">
    <h1>Checkout</h1>
    
    <?php if (isset($error)): ?>
        <div class="error"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <?php if (isset($errors) && !empty($errors)): ?>
        <div class="error">
            <ul>
                <?php foreach ($errors as $err): ?>
                    <li><?php echo $err; ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>
    
    <div class="checkout-container">
        <div class="checkout-form">
            <h2>Data Pengiriman</h2>
            <form action="index.php" method="post" id="checkout-form">
                <div class="form-group">
                    <label for="name">Nama Penerima:</label>
                    <input type="text" id="name" name="name" value="<?php echo $user['name'] ?? ''; ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="address">Alamat Pengiriman:</label>
                    <textarea id="address" name="address" required><?php echo $user['address'] ?? ''; ?></textarea>
                </div>
                
                <div class="form-group">
                    <label for="phone">Nomor Telepon:</label>
                    <input type="text" id="phone" name="phone" value="<?php echo $user['phone'] ?? ''; ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="notes">Catatan Pesanan (opsional):</label>
                    <textarea id="notes" name="notes"></textarea>
                </div>
                
                <div class="form-group delivery-method">
                    <label>Metode Pengiriman:</label>
                    <div class="delivery-options">
                        <label class="delivery-option">
                            <input type="radio" name="delivery_method" value="regular" checked>
                            <span class="delivery-label">Reguler</span>
                            <span class="delivery-price">Rp 10.000</span>
                        </label>
                        <label class="delivery-option">
                            <input type="radio" name="delivery_method" value="gojek">
                            <div class="delivery-logo">
                                <i class="fas fa-motorcycle"></i> GoSend
                            </div>
                            <span class="delivery-label">Gojek</span>
                            <span class="delivery-price">Rp 15.000</span>
                        </label>
                        <label class="delivery-option">
                            <input type="radio" name="delivery_method" value="grab">
                            <div class="delivery-logo">
                                <i class="fas fa-motorcycle"></i> GrabExpress
                            </div>
                            <span class="delivery-label">Grab</span>
                            <span class="delivery-price">Rp 15.000</span>
                        </label>
                    </div>
                </div>
                
                <div class="form-group payment-method">
                    <label>Metode Pembayaran:</label>
                    <div class="payment-options">
                        <label class="payment-option">
                            <input type="radio" name="payment_method" value="transfer" checked>
                            <span>Transfer Bank</span>
                        </label>
                        <label class="payment-option">
                            <input type="radio" name="payment_method" value="cod">
                            <span>Bayar di Tempat (COD)</span>
                            <span class="payment-note">Tanpa biaya tambahan</span>
                        </label>
                    </div>
                </div>
                
                <!-- Tombol dipindahkan ke bagian ringkasan pesanan -->
            </form>
        </div>
        
        <div class="order-summary">
            <h2>Ringkasan Pesanan</h2>
            <div class="cart-items">
                <?php foreach ($cartItems as $item): ?>
                    <div class="summary-item">
                        <div class="item-name">
                            <?php echo $item['name']; ?> x <?php echo $item['quantity']; ?>
                        </div>
                        <div class="item-price">
                            Rp <?php echo number_format($item['subtotal'], 0, ',', '.'); ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <div class="summary-subtotal">
                <div class="subtotal-label">Subtotal:</div>
                <div class="subtotal-amount">Rp <?php echo number_format($totalAmount, 0, ',', '.'); ?></div>
            </div>
            
            <div class="summary-shipping">
                <div class="shipping-label">Biaya Pengiriman: <span id="shipping-method">Reguler</span></div>
                <div class="shipping-amount">Rp <span id="shipping-cost">10.000</span></div>
            </div>
            
            <div class="summary-total">
                <div class="total-label">Total Pembayaran:</div>
                <div class="total-amount">Rp <span id="total-with-shipping"><?php echo number_format($totalAmount + 10000, 0, ',', '.'); ?></span></div>
            </div>
            
            <!-- Tombol Buat Pesanan ditambahkan di sini -->
            <button type="submit" form="checkout-form" class="btn checkout-btn">Buat Pesanan</button>
        </div>
    </div>
</div>

<style>
.delivery-method {
    margin-bottom: 20px;
}

.delivery-options {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-top: 10px;
}

.delivery-option {
    display: flex;
    align-items: center;
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
}

.delivery-option:hover {
    border-color: var(--primary-color);
    background-color: rgba(76, 175, 80, 0.05);
}

.delivery-option input[type="radio"] {
    margin-right: 12px;
}

.delivery-logo {
    display: flex;
    align-items: center;
    margin-right: 8px;
    font-weight: 500;
    color: #333;
}

.delivery-logo i {
    margin-right: 5px;
    font-size: 16px;
    color: var(--primary-color);
}

.delivery-label {
    flex-grow: 1;
}

.delivery-price {
    font-weight: 600;
    color: var(--accent-color);
}

.delivery-option input[type="radio"]:checked + .delivery-label {
    font-weight: 600;
}

.delivery-option.selected {
    border-color: var(--primary-color);
    background-color: rgba(76, 175, 80, 0.05);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.summary-subtotal,
.summary-shipping {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px dashed #ddd;
}

.summary-subtotal {
    margin-top: 15px;
}

.summary-total {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 2px solid #ddd;
}

.payment-options {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-top: 10px;
}

.payment-option {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
}

.payment-option:hover {
    border-color: var(--primary-color);
    background-color: rgba(76, 175, 80, 0.05);
}

.payment-option input[type="radio"] {
    margin-right: 12px;
}

.payment-option.selected {
    border-color: var(--primary-color);
    background-color: rgba(76, 175, 80, 0.05);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.payment-note {
    margin-left: 10px;
    font-size: 0.85rem;
    color: var(--accent-color);
    font-weight: 500;
    padding: 2px 8px;
    border-radius: 10px;
    background-color: rgba(255, 152, 0, 0.1);
}

.checkout-btn {
    margin-top: 20px;
    width: 100%;
    padding: 15px;
    font-size: 16px;
    font-weight: 600;
    background-color: var(--primary-color);
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.checkout-btn:hover {
    background-color: var(--secondary-color);
}

@media (max-width: 768px) {
    .delivery-option {
        flex-wrap: wrap;
    }
    
    .delivery-logo {
        order: 0;
        margin-right: 8px;
    }
    
    .delivery-label {
        order: 2;
        flex-basis: 100%;
        margin-top: 5px;
        margin-left: 25px;
    }
    
    .delivery-price {
        order: 1;
        margin-left: auto;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const deliveryOptions = document.querySelectorAll('input[name="delivery_method"]');
    const paymentOptions = document.querySelectorAll('input[name="payment_method"]');
    const shippingMethodSpan = document.getElementById('shipping-method');
    const shippingCostSpan = document.getElementById('shipping-cost');
    const totalWithShippingSpan = document.getElementById('total-with-shipping');
    const subtotalAmount = <?php echo $totalAmount; ?>;
    
    // Format number to currency
    function formatCurrency(amount) {
        return new Intl.NumberFormat('id-ID').format(amount);
    }
    
    // Update totals based on selected shipping method
    function updateTotals(shippingCost, shippingMethod) {
        const totalWithShipping = subtotalAmount + shippingCost;
        
        shippingMethodSpan.textContent = shippingMethod;
        shippingCostSpan.textContent = formatCurrency(shippingCost);
        totalWithShippingSpan.textContent = formatCurrency(totalWithShipping);
        
        // Add visual feedback by highlighting the selected option
        document.querySelectorAll('.delivery-option').forEach(option => {
            option.classList.remove('selected');
        });
        
        const selectedOption = document.querySelector(`input[name="delivery_method"]:checked`).closest('.delivery-option');
        if (selectedOption) {
            selectedOption.classList.add('selected');
        }
    }
    
    // Handle payment method selection
    function handlePaymentSelection() {
        document.querySelectorAll('.payment-option').forEach(option => {
            option.classList.remove('selected');
        });
        
        const selectedPayment = document.querySelector('input[name="payment_method"]:checked');
        if (selectedPayment) {
            selectedPayment.closest('.payment-option').classList.add('selected');
        }
    }
    
    // Add click handler to delivery options
    deliveryOptions.forEach(option => {
        option.addEventListener('change', function() {
            const method = this.value;
            let cost = 10000;
            let methodName = 'Reguler';
            
            if (method === 'gojek') {
                cost = 15000;
                methodName = 'Gojek';
            } else if (method === 'grab') {
                cost = 15000;
                methodName = 'Grab';
            }
            
            updateTotals(cost, methodName);
        });
        
        // Add click handler to the parent label for better UX
        const parentLabel = option.closest('.delivery-option');
        if (parentLabel) {
            parentLabel.addEventListener('click', function() {
                option.checked = true;
                option.dispatchEvent(new Event('change'));
            });
        }
    });
    
    // Add click handler to payment options
    paymentOptions.forEach(option => {
        option.addEventListener('change', handlePaymentSelection);
        
        // Add click handler to the parent label for better UX
        const parentLabel = option.closest('.payment-option');
        if (parentLabel) {
            parentLabel.addEventListener('click', function() {
                option.checked = true;
                option.dispatchEvent(new Event('change'));
            });
        }
    });
    
    // Initialize with default options
    const defaultDeliveryOption = document.querySelector('input[name="delivery_method"]:checked');
    if (defaultDeliveryOption) {
        defaultDeliveryOption.dispatchEvent(new Event('change'));
    } else {
        // Select the first option if none is checked
        const firstDeliveryOption = document.querySelector('input[name="delivery_method"]');
        if (firstDeliveryOption) {
            firstDeliveryOption.checked = true;
            firstDeliveryOption.dispatchEvent(new Event('change'));
        }
    }
    
    // Initialize payment method selection
    handlePaymentSelection();
});
</script>

<?php include '../includes/footer.php'; ?> 