<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/midtrans_util.php';
require_once __DIR__ . '/../models/Order.php';
require_once(__DIR__ . '/../config/db_config.php');

// Cek jika ada order_id di URL
$order_data = null;
$cart_items = [];
$total_amount = 0;
$prefill_form = [
    'name' => '',
    'phone' => '',
    'email' => '',
    'address' => '',
    'shipping_label' => '',
    'shipping_cost' => 0
];

if (isset($_GET['order_id'])) {
    $order_code = $_GET['order_id'];
    $order = new Order();
    if ($order->getOrderByOrderCode($order_code)) {
        $order_data = $order;
        // Prefill form
        $prefill_form['name'] = $order->name;
        $prefill_form['phone'] = $order->phone;
        $prefill_form['email'] = $order->email;
        $prefill_form['address'] = $order->address;
        $prefill_form['shipping_label'] = $order->payment_method ?? '';
        $prefill_form['shipping_cost'] = 0; // (optional: simpan ongkir di DB jika ada)
        $cart_items = array_map(function($item) {
            return [
                'product' => $item['product_name'],
                'price' => (int)$item['product_price'],
                'quantity' => (int)$item['quantity']
            ];
        }, $order->items);
        $total_amount = (int)$order->total_amount;
        $order_id = $order->order_code;
    }
}

?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Form Pembayaran</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- <script type="text/javascript" src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="SB-Mid-client-VOik1MpUC4zF8TdN"></script> -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
  <!-- Navbar -->
  <nav class="bg-white shadow sticky top-0 z-50 px-8 py-4 flex justify-between items-center">
    <div class="flex items-center gap-4">
      <img src="/logo.png" alt="Logo" class="h-10 w-10 rounded-full bg-gray-200 object-cover" onerror="this.style.display='none'">
      <span class="text-2xl font-bold text-green-700 tracking-wide">Bakso Alam</span>
    </div>
    <div class="flex items-center gap-6">
      <a href="dashboard.php" class="text-gray-700 hover:text-green-700 font-semibold">Home</a>
      <a href="cek_transaction.php" class="text-gray-700 hover:text-green-700 font-semibold">Transaksi</a>
      <a href="https://wa.me/6285956631642" target="_blank" rel="noopener" class="text-gray-700 hover:text-green-700 font-semibold flex items-center gap-1"><i class="fab fa-whatsapp"></i> Kontak Kami</a>
      <?php if (isset($_SESSION['user_id'])): ?>
        <a href="cart.php" class="relative text-gray-700 hover:text-green-700">
          <i class="fas fa-shopping-cart text-2xl"></i>
          <span id="cart-count" class="absolute -top-2 -right-2 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center">0</span>
        </a>
      <?php endif; ?>
      <?php if (isset($_SESSION['user_id'])): ?>
        <a href="logout.php" class="ml-4 px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition">Logout</a>
      <?php else: ?>
        <a href="login.php" class="ml-4 px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition">Sign in</a>
      <?php endif; ?>
    </div>
  </nav>

  <div class="max-w-3xl w-full mx-auto px-4 py-10 flex-1">
    <div class="bg-white rounded-2xl shadow-lg p-8">
      <h2 class="text-2xl font-bold text-green-800 mb-6">Informasi Pengiriman</h2>
      <form id="checkout-form" class="space-y-5" method="POST" action="process_payment.php">
        <input type="hidden" name="items" id="items-hidden">
        <input type="hidden" name="gross_amount" id="gross-amount-hidden">
        <!-- Tampilkan detail pesanan -->
        <div class="mb-6">
          <div class="text-lg font-bold text-gray-800 mb-2">Detail Pesanan</div>
          <div id="order-summary" class="bg-gray-50 rounded-xl p-4 shadow-inner"></div>
        </div>
        <div>
          <label class="block font-semibold text-gray-700 mb-1">Nama Lengkap</label>
          <input type="text" name="customer_name" id="customer-name" required class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-400" value="<?php echo htmlspecialchars($prefill_form['name']); ?>">
        </div>
        <div>
          <label class="block font-semibold text-gray-700 mb-1">No Handphone</label>
          <input type="text" name="customer_phone" id="customer-phone" required class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-400" value="<?php echo htmlspecialchars($prefill_form['phone']); ?>">
        </div>
        <div>
          <label class="block font-semibold text-gray-700 mb-1">Email</label>
          <input type="text" name="customer_email" id="customer-email" required class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-400" value="<?php echo htmlspecialchars($prefill_form['email']); ?>">
        </div>
        <div>
          <label class="block font-semibold text-gray-700 mb-1">Alamat</label>
          <input type="text" name="customer_address" id="customer-address" required class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-400" value="<?php echo htmlspecialchars($prefill_form['address']); ?>">
        </div>
        <div>
          <label class="block font-semibold text-gray-700 mb-1">Pengiriman</label>
          <select id="shipping-method" name="shipping_label" class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-green-400">
            <option value="gojek">gojek (Rp 15.000)</option>
            <option value="jne">JNE (Rp 25.000)</option>
            <option value="grab">Grab (Rp 18.000)</option>
            <option value="sicepat">SiCepat (Rp 20.000)</option>
            <option value="bekasi">Bekasi (Rp 15.000)</option>
          </select>
        </div>
        <div>
          <div class="text-lg font-bold text-gray-800 mt-8 mb-2">Metode Pembayaran</div>
          <div class="flex flex-col gap-2">
            <label class="inline-flex items-center">
              <input type="radio" name="payment_method" id="payment-dana" value="dana" class="form-radio mr-2" required>
              <span class="font-semibold">DANA</span>
            </label>
            <label class="inline-flex items-center">
              <input type="radio" name="payment_method" id="payment-mandiri" value="mandiri" class="form-radio mr-2" required>
              <span class="font-semibold">Mandiri</span>
            </label>
          </div>
          <div id="payment-instructions" class="mt-4 p-4 bg-blue-50 rounded-lg text-blue-800 hidden"></div>
        </div>
        <div class="flex flex-col md:flex-row gap-4 mt-8">
          <button type="submit" id="pay-button" class="flex-1 bg-green-600 hover:bg-green-700 text-white py-3 rounded-lg font-semibold shadow transition">Bayar Sekarang</button>
        </div>
        <div id="payment-error" class="mt-4 text-red-500"></div>
      </form>
      <div id="debug-info" style="display:none"></div>
      <div id="success-message" class="hidden mt-8">
        <div class="bg-green-100 p-6 rounded-lg mb-4 text-center">
          <h2 class="text-green-800 text-xl font-bold mb-2">Pembayaran Berhasil!</h2>
          <p class="text-green-700">Terima kasih telah berbelanja di Bakso Alam.</p>
        </div>
        <div class="text-center mt-6">
          <a href="dashboard.php" class="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded">Kembali ke Beranda</a>
        </div>
      </div>
    </div>
  </div>

  <script>
    // Enable debug mode
    const DEBUG = true;
    
    // Debug function
    function debugLog(message, data) {
        if (DEBUG) {
            console.log(message, data);
            const debugInfo = document.getElementById('debug-info');
            const timestamp = new Date().toISOString().slice(11, 19);
            
            let dataText = '';
            if (data) {
                try {
                    if (typeof data === 'object') {
                        dataText = JSON.stringify(data, null, 2);
                    } else {
                        dataText = String(data);
                    }
                } catch (e) {
                    dataText = 'Error stringifying data';
                }
            }
            
            const logEntry = document.createElement('div');
            logEntry.innerHTML = `<strong>${timestamp}</strong>: ${message}${dataText ? '<pre>' + dataText + '</pre>' : ''}`;
            
            debugInfo.appendChild(logEntry);
            debugInfo.style.display = 'block';
        }
    }
    
    // Initialize cart data from localStorage
    let cartItems = [];
    let totalAmount = 0;
    let shippingCost = 15000;
    let shippingLabel = 'gojek';

    // Function to format price to Rupiah
    function formatRupiah(price) {
        return 'Rp ' + price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }
    
    // Show errors
    function showError(message) {
        const errorElement = document.getElementById('payment-error');
        errorElement.textContent = message;
        errorElement.classList.add('p-3', 'bg-red-100', 'rounded');
        debugLog('ERROR: ' + message);
    }
    
    // Update payment details to include shipping
    function updatePaymentDetails(items, totalAmount) {
      let paymentDetailsHtml = '';
      let itemsTotal = 0;
      const groupedItems = {};
      items.forEach(item => {
        if (!groupedItems[item.product]) {
          groupedItems[item.product] = {
            product: item.product,
            price: item.price,
            quantity: item.quantity || 1
          };
        } else {
          groupedItems[item.product].quantity += item.quantity || 1;
        }
      });
      Object.values(groupedItems).forEach(item => {
        const itemTotal = item.price * item.quantity;
        itemsTotal += itemTotal;
        paymentDetailsHtml += `
          <div class="flex justify-between">
            <span>${item.product} × ${item.quantity}</span>
            <span>${formatRupiah(itemTotal)}</span>
          </div>
        `;
      });
      paymentDetailsHtml += `
        <div class="flex justify-between mt-2">
          <span>Ongkir (${shippingLabel})</span>
          <span>${formatRupiah(shippingCost)}</span>
        </div>
        <div class="border-t pt-2 mt-2">
          <div class="flex justify-between font-bold">
            <span>TOTAL:</span>
            <span>${formatRupiah(itemsTotal + shippingCost)}</span>
          </div>
        </div>
      `;
      document.getElementById('payment-details').innerHTML = paymentDetailsHtml;
    }

    function renderOrderSummary(items, shippingCost, shippingLabel) {
      const orderSummaryDiv = document.getElementById('order-summary');
      if (!orderSummaryDiv) return;
      let html = '';
      let itemsTotal = 0;

      if (!items || items.length === 0) {
        html = '<div class="text-red-600">Keranjang kosong. Silakan pilih produk terlebih dahulu.</div>';
        orderSummaryDiv.innerHTML = html;
        document.getElementById('pay-button').disabled = true;
        document.getElementById('pay-button').classList.add('opacity-50');
        return;
      } else {
        document.getElementById('pay-button').disabled = false;
        document.getElementById('pay-button').classList.remove('opacity-50');
      }

      html += `
        <table style="width:100%; border-collapse:collapse; margin-bottom:12px;">
          <thead>
            <tr style="background:#f3f4f6;">
              <th style="text-align:left; padding:8px; border-bottom:2px solid #e5e7eb;">Produk</th>
              <th style="text-align:center; padding:8px; border-bottom:2px solid #e5e7eb;">Qty</th>
              <th style="text-align:right; padding:8px; border-bottom:2px solid #e5e7eb;">Harga</th>
              <th style="text-align:right; padding:8px; border-bottom:2px solid #e5e7eb;">Subtotal</th>
            </tr>
          </thead>
          <tbody>
      `;
      items.forEach(item => {
        const qty = item.quantity || 1;
        const subtotal = item.price * qty;
        itemsTotal += subtotal;
        html += `
          <tr>
            <td style="padding:8px; border-bottom:1px solid #e5e7eb;">${item.product}</td>
            <td style="text-align:center; padding:8px; border-bottom:1px solid #e5e7eb;">${qty}</td>
            <td style="text-align:right; padding:8px; border-bottom:1px solid #e5e7eb;">${formatRupiah(item.price)}</td>
            <td style="text-align:right; padding:8px; border-bottom:1px solid #e5e7eb;">${formatRupiah(subtotal)}</td>
          </tr>
        `;
      });
      html += `
          </tbody>
          <tfoot>
            <tr>
              <td colspan="3" style="text-align:right; font-weight:600; padding:8px; border-top:2px solid #e5e7eb;">Ongkir (${shippingLabel})</td>
              <td style="text-align:right; padding:8px; border-top:2px solid #e5e7eb;">${formatRupiah(shippingCost)}</td>
            </tr>
            <tr>
              <td colspan="3" style="text-align:right; font-weight:bold; padding:8px;">Total</td>
              <td style="text-align:right; font-weight:bold; padding:8px;">${formatRupiah(itemsTotal + shippingCost)}</td>
            </tr>
          </tfoot>
        </table>
      `;
      orderSummaryDiv.innerHTML = html;
    }
    
    // Load cart data and populate fields when page loads
    // Inject PHP cart_items dan total_amount ke JS jika ada order_id
    const orderFromDb = <?php echo isset($_GET['order_id']) && $order_data ? 'true' : 'false'; ?>;
    const dbCartItems = <?php echo isset($_GET['order_id']) && $order_data ? json_encode($cart_items) : '[]'; ?>;
    const dbTotalAmount = <?php echo isset($_GET['order_id']) && $order_data ? (int)$total_amount : 0; ?>;

    window.addEventListener('DOMContentLoaded', function() {
        // Debug: cek isi sessionStorage dan localStorage
        console.log('buyNowItem:', sessionStorage.getItem('buyNowItem'));
        console.log('checkoutItems:', sessionStorage.getItem('checkoutItems'));
        console.log('cartItems:', localStorage.getItem('cartItems'));

        // Ambil mode checkout
        const urlParams = new URLSearchParams(window.location.search);
        let items = [];
        if (urlParams.get('buynow') === '1' && sessionStorage.getItem('buyNowItem')) {
            items = JSON.parse(sessionStorage.getItem('buyNowItem'));
        } else if (urlParams.get('cart') === '1' && sessionStorage.getItem('checkoutItems')) {
            items = JSON.parse(sessionStorage.getItem('checkoutItems'));
        } else if (localStorage.getItem('cartItems')) {
            items = JSON.parse(localStorage.getItem('cartItems'));
        }
        // debugLog('Cart data from localStorage', items);

        // Tambahkan baris berikut agar cartItems diisi dari items
        cartItems = items;

        if (orderFromDb) {
            cartItems = dbCartItems;
            totalAmount = dbTotalAmount;
            // Render ulang detail pembayaran
            renderOrderSummary(cartItems, shippingCost, shippingLabel);
            // Disable form input agar tidak bisa diubah
            document.getElementById('customer-name').readOnly = true;
            document.getElementById('customer-phone').readOnly = true;
            document.getElementById('customer-email').readOnly = true;
            document.getElementById('customer-address').readOnly = true;
            document.getElementById('shipping-method').disabled = true;
        } else if (items.length > 0) {
            // Group same products together
            const groupedItems = {};
            
            items.forEach(item => {
                if (!groupedItems[item.product]) {
                    groupedItems[item.product] = {
                        product: item.product,
                        price: item.price,
                        quantity: item.quantity || 1
                    };
                } else {
                    groupedItems[item.product].quantity += item.quantity || 1;
                }
            });
            
            // Calculate totals and display items
            let paymentDetailsHtml = '';
            let itemsTotal = 0;
            
            Object.values(groupedItems).forEach(item => {
                const itemTotal = item.price * item.quantity;
                itemsTotal += itemTotal;
                
                paymentDetailsHtml += `
                    <div class="flex justify-between">
                        <span>${item.product} × ${item.quantity}</span>
                        <span>${formatRupiah(itemTotal)}</span>
                    </div>
                `;
            });
            
            // Add totals
            totalAmount = itemsTotal;
            // debugLog('Total amount calculated', totalAmount);
            
            paymentDetailsHtml += `
                <div class="border-t pt-2 mt-2">
                    <div class="flex justify-between font-bold">
                        <span>TOTAL:</span>
                        <span>${formatRupiah(totalAmount)}</span>
                    </div>
                </div>
            `;
            
            // Display in payment details
            document.getElementById('payment-details').innerHTML = paymentDetailsHtml;
            // renderOrderSummary(items, shippingCost, shippingLabel); // Initial call to update details
        } else {
            // No items in cart
            // debugLog('No items in cart');
            document.getElementById('payment-details').innerHTML = `
                <div class="bg-red-100 text-red-700 p-4 rounded">Keranjang belanja kosong atau data checkout tidak ditemukan.<br>Silakan ulangi proses dari halaman produk/keranjang.</div>
            `;
            document.getElementById('pay-button').disabled = true;
            document.getElementById('pay-button').classList.add('opacity-50');
        }

        // Render ringkasan pesanan di awal
        renderOrderSummary(cartItems, shippingCost, shippingLabel);

        // Update shipping cost if dropdown changed
        document.getElementById('shipping-method').addEventListener('change', function() {
          if (this.value === 'bekasi') {
            shippingCost = 15000;
            shippingLabel = 'Bekasi';
          } else if (this.value === 'jne') {
            shippingCost = 25000;
            shippingLabel = 'JNE';
          } else if (this.value === 'gojek') {
            shippingCost = 15000;
            shippingLabel = 'gojek';
          } else if (this.value === 'grab') {
            shippingCost = 18000;
            shippingLabel = 'Grab';
          } else if (this.value === 'sicepat') {
            shippingCost = 20000;
            shippingLabel = 'SiCepat';
          }
          renderOrderSummary(cartItems, shippingCost, shippingLabel);
        });

        // Handle payment method selection and show instructions
        document.querySelectorAll('input[name="payment_method"]').forEach(function(radio) {
          radio.addEventListener('change', function() {
            const instruksi = document.getElementById('payment-instructions');
            if (this.value === 'dana') {
              instruksi.innerHTML = '<b>Transfer ke DANA:</b><br>Nomor: <span class="font-mono">0812xxxxxxx</span><br>Atas Nama: <span class="font-mono">Nama Anda</span><br>Setelah transfer, klik Bayar Sekarang.';
              instruksi.classList.remove('hidden');
            } else if (this.value === 'mandiri') {
              instruksi.innerHTML = '<b>Transfer ke Mandiri:</b><br>Nomor Rekening: <span class="font-mono">123000xxxxxx</span><br>Atas Nama: <span class="font-mono">Nama Anda</span><br>Setelah transfer, klik Bayar Sekarang.';
              instruksi.classList.remove('hidden');
            } else {
              instruksi.classList.add('hidden');
            }
          });
        });

        // Cek login dari PHP ke JS
        const isLoggedIn = <?php echo isset($_SESSION['user_id']) ? 'true' : 'false'; ?>;
        const userId = <?php echo isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 'null'; ?>;
        const cartKey = userId ? `cartItems_user_${userId}` : 'cartItems_guest';
        const cartCountKey = userId ? `cartCount_user_${userId}` : 'cartCount_guest';
        // Update cart count di navbar
        const savedCartCount = localStorage.getItem(cartCountKey);
        if (savedCartCount) {
          document.getElementById('cart-count').textContent = savedCartCount;
        } else {
          document.getElementById('cart-count').textContent = 0;
        }
    
        // Tambahkan event listener untuk submit form
        document.getElementById('checkout-form').addEventListener('submit', function(e) {
          // Sebelum submit, set input hidden items dan gross_amount
          document.getElementById('items-hidden').value = JSON.stringify(cartItems);
          document.getElementById('gross-amount-hidden').value = totalAmount;
            });
            
        // Jika cartItems berubah (misal dari DB), render ulang ringkasan pesanan
        // renderOrderSummary(cartItems, shippingCost, shippingLabel); // Removed duplicate call
    });
    
  </script>
</body>
</html>
