<?php include __DIR__ . '/../layout/header.php'; ?>

<?php 
$customer = (new \App\Core\Session())->get('customer_user'); 
?>

<style>
/* Checkout page - same sidebar layout as profile */
.account-wrapper {
    max-width: var(--max-w);
    margin: 40px auto;
    padding: 0 20px;
    display: grid;
    grid-template-columns: 280px 1fr;
    gap: 30px;
    align-items: start;
}
@media (max-width: 900px) {
    .account-wrapper { grid-template-columns: 1fr; }
}
.account-sidebar {
    background: var(--surface-card);
    border-radius: var(--r-lg);
    box-shadow: var(--shadow-card);
    border: 1px solid var(--border);
    overflow: hidden;
}
.sidebar-user {
    padding: 30px 20px;
    text-align: center;
    border-bottom: 1px solid var(--border);
    background: var(--surface-2);
}
.sidebar-avatar {
    width: 80px; height: 80px;
    border-radius: 50%; object-fit: cover;
    margin: 0 auto 15px auto;
    border: 2px solid var(--orange);
    box-shadow: var(--shadow-glow);
}
.sidebar-avatar-placeholder {
    width: 80px; height: 80px;
    border-radius: 50%;
    background: var(--orange);
    color: #fff;
    display: flex; align-items: center; justify-content: center;
    font-size: 32px; font-weight: 700;
    margin: 0 auto 15px auto;
    box-shadow: var(--shadow-glow);
}
.sidebar-user h3 { font-size: 18px; color: var(--text-1); margin: 0 0 5px 0; }
.sidebar-user p  { font-size: 13px; color: var(--text-3); margin: 0; }
.sidebar-menu { list-style: none; padding: 10px 0; margin: 0; }
.sidebar-menu li { margin: 0; }
.sidebar-menu a {
    display: flex; align-items: center; gap: 15px;
    padding: 15px 25px;
    color: var(--text-2); font-size: 15px; font-weight: 500;
    transition: all 0.3s ease;
    border-left: 3px solid transparent;
}
.sidebar-menu a:hover { background: var(--surface-2); color: var(--text-1); }
.sidebar-menu a.active { background: var(--surface-2); color: var(--orange); border-left-color: var(--orange); }
.sidebar-menu a i { width: 20px; text-align: center; font-size: 18px; }

.account-content {
    background: var(--surface-card);
    border-radius: var(--r-lg);
    box-shadow: var(--shadow-card);
    border: 1px solid var(--border);
    padding: 40px;
}
@media (max-width: 768px) { .account-content { padding: 24px; } }

/* Checkout inner grid */
.checkout-grid {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 24px;
    align-items: start;
    margin-top: 20px;
}
@media (max-width: 860px) { .checkout-grid { grid-template-columns: 1fr; } }

/* Guest wrapper */
.checkout-guest-wrap {
    max-width: 1000px;
    margin: 40px auto;
    padding: 0 20px;
}
</style>

<?php if ($customer): ?>

<!-- ===== LOGGED-IN: Profile sidebar layout ===== -->
<div class="account-wrapper">
    <!-- Sidebar -->
    <aside class="account-sidebar">
        <div class="sidebar-user">
            <?php if (!empty($customer['avatar'])): ?>
                <img src="<?php echo htmlspecialchars($customer['avatar']); ?>" alt="Profil Resmi" referrerpolicy="no-referrer" class="sidebar-avatar">
            <?php else: ?>
                <div class="sidebar-avatar-placeholder">
                    <?php echo mb_substr(mb_strtoupper(htmlspecialchars($customer['name']), 'UTF-8'), 0, 1, 'UTF-8'); ?>
                </div>
            <?php endif; ?>
            <h3><?php echo htmlspecialchars($customer['name']); ?></h3>
            <p>Müşteri Hesabı</p>
        </div>
        <ul class="sidebar-menu">
            <li>
                <a href="<?php echo $baseUrl; ?>/profile">
                    <i class="fa fa-user"></i> Hesap Bilgilerim
                </a>
            </li>
            <li>
                <a href="<?php echo $baseUrl; ?>/profile/orders">
                    <i class="fa fa-shopping-bag"></i> Siparişlerim
                </a>
            </li>
            <li>
                <a href="<?php echo $baseUrl; ?>/cart">
                    <i class="fa fa-shopping-cart"></i> Sepetim
                </a>
            </li>
            <li>
                <a href="<?php echo $baseUrl; ?>/checkout" class="active">
                    <i class="fa fa-credit-card"></i> Ödeme
                </a>
            </li>
            <li>
                <a href="<?php echo $baseUrl; ?>/logout" style="color: #ef4444; margin-top: 10px; border-top: 1px solid var(--border);">
                    <i class="fa fa-sign-out"></i> Çıkış Yap
                </a>
            </li>
        </ul>
    </aside>

    <!-- Main Content -->
    <main class="account-content">
        <div style="margin-bottom: 24px; padding-bottom: 16px; border-bottom: 1px solid var(--border);">
            <h1 style="font-size: 22px; color: var(--text-1); margin: 0 0 4px 0;">Sipariş Onayı</h1>
            <p style="color: var(--text-3); font-size: 14px; margin: 0;">Bilgilerinizi kontrol edin ve siparişi tamamlayın.</p>
        </div>

        <form action="<?php echo $baseUrl; ?>/checkout/submit" method="POST">

            <?php if (!empty($error)): ?>
            <div style="background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.3); border-radius: var(--r-md); padding: 16px; margin-bottom: 24px;">
                <div style="display: flex; align-items: center; gap: 12px;">
                    <i class="fa fa-exclamation-circle" style="color: #ef4444; font-size: 24px;"></i>
                    <div>
                        <strong style="color: #ef4444; display: block; font-size: 15px; margin-bottom: 4px;">Ödeme İşlemi Başarısız</strong>
                        <span style="color: var(--text-2); font-size: 14px;"><?php echo htmlspecialchars($error); ?></span>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div class="checkout-grid">

                <!-- Left: Delivery + Payment -->
                <div style="display: flex; flex-direction: column; gap: 24px;">

                    <!-- Delivery Address -->
                    <section style="background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-md); padding: 20px;">
                        <h2 style="font-size: 15px; font-weight: 700; margin: 0 0 16px 0; color: var(--text-1);">
                            <i class="fa fa-map-marker" style="color: var(--orange);"></i> Teslimat Bilgileri
                        </h2>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                            <div style="grid-column: 1 / -1;">
                                <label style="display: block; font-size: 12px; color: var(--text-3); margin-bottom: 6px;">Ad Soyad</label>
                                <input type="text" name="customer_name" value="<?php echo htmlspecialchars($customer['name'] ?? ''); ?>" required
                                    style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-card); color: var(--text-1); font-family: var(--font); box-sizing: border-box; outline: none;">
                            </div>
                            <div>
                                <label style="display: block; font-size: 12px; color: var(--text-3); margin-bottom: 6px;">E-posta</label>
                                <input type="email" name="customer_email" value="<?php echo htmlspecialchars($customer['email'] ?? ''); ?>" required
                                    style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-card); color: var(--text-1); font-family: var(--font); box-sizing: border-box; outline: none;">
                            </div>
                            <div>
                                <label style="display: block; font-size: 12px; color: var(--text-3); margin-bottom: 6px;">Telefon</label>
                                <input type="tel" name="customer_phone" value="<?php echo htmlspecialchars($user ? ($user->phone ?? '') : ($customer['phone'] ?? '')); ?>" required
                                    style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-card); color: var(--text-1); font-family: var(--font); box-sizing: border-box; outline: none;">
                            </div>
                            <div style="grid-column: 1 / -1;">
                                <label style="display: block; font-size: 12px; color: var(--text-3); margin-bottom: 6px;">Teslimat Adresi</label>
                                <textarea name="customer_address" rows="3" required
                                    style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-card); color: var(--text-1); font-family: var(--font); box-sizing: border-box; outline: none; resize: vertical;"><?php echo htmlspecialchars($user ? ($user->address ?? '') : ($customer['address'] ?? '')); ?></textarea>
                            </div>
                            <div style="grid-column: 1 / -1;">
                                <label style="display: block; font-size: 12px; color: var(--text-3); margin-bottom: 6px;">Sipariş Notu (İsteğe Bağlı)</label>
                                <textarea name="customer_notes" rows="2" placeholder="Siparişinizle ilgili notunuz varsa buraya yazabilirsiniz..."
                                    style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-card); color: var(--text-1); font-family: var(--font); box-sizing: border-box; outline: none; resize: vertical;"></textarea>
                            </div>
                        </div>
                    </section>

                    <!-- Shipping Method -->
                    <?php if (!empty($shippingMethods)): ?>
                    <section style="background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-md); padding: 20px;">
                        <h2 style="font-size: 15px; font-weight: 700; margin: 0 0 16px 0; color: var(--text-1);">
                            <i class="fa fa-truck" style="color: var(--orange);"></i> Kargo Seçenekleri
                        </h2>
                        <div style="display: flex; flex-direction: column; gap: 10px;">
                            <?php $firstShipping = true; foreach ($shippingMethods as $opt): ?>
                            <?php if (empty($opt['name'])) continue; ?>
                            <label style="display: flex; align-items: center; gap: 10px; padding: 12px 16px; border: 1px solid var(--border); border-radius: var(--r-md); cursor: pointer; background: var(--surface-card);">
                                <input type="radio" name="shipping_method" value="<?php echo htmlspecialchars($opt['name']); ?>"
                                    data-cost="<?php echo (float)($opt['cost'] ?? 0); ?>"
                                    class="shipping-radio"
                                    style="accent-color: var(--orange);"
                                    <?php echo $firstShipping ? 'checked' : ''; ?>>
                                <span style="flex: 1; font-size: 14px; font-weight: 500;"><?php echo htmlspecialchars($opt['name']); ?></span>
                                <span style="font-weight: 700; color: var(--orange);">
                                    <?php echo \App\Services\CurrencyService::format((float)($opt['cost'] ?? 0)); ?>
                                </span>
                            </label>
                            <?php $firstShipping = false; endforeach; ?>
                        </div>
                    </section>
                    <?php endif; ?>

                    <!-- Payment Method -->
                    <section style="background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-md); padding: 20px;">
                        <h2 style="font-size: 15px; font-weight: 700; margin: 0 0 16px 0; color: var(--text-1);">
                            <i class="fa fa-credit-card" style="color: var(--orange);"></i> Ödeme Yöntemi
                        </h2>
                        <?php include __DIR__ . '/components/payment_methods_form.php'; ?>
                    </section>

                </div>

                <!-- Right: Order Summary -->
                <aside style="background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-lg); padding: 24px; position: sticky; top: 20px;">
                    <h3 style="font-size: 16px; font-weight: 700; margin: 0 0 16px 0; padding-bottom: 12px; border-bottom: 1px solid var(--border);">Sepetiniz</h3>

                    <div style="display: flex; flex-direction: column; gap: 12px; max-height: 240px; overflow-y: auto; margin-bottom: 16px;">
                        <?php 
                        $totalPrice = 0.0;
                        foreach ($cartItems as $item):
                            $prod = $item['product'];
                            $qty  = $item['quantity'];
                            $itemPrice    = $prod->getConvertedPrice();
                            $itemSubtotal = $itemPrice * $qty;
                            $totalPrice  += $itemSubtotal;
                        ?>
                        <div style="display: flex; justify-content: space-between; align-items: start; gap: 8px; font-size: 13px;">
                            <span style="color: var(--text-3); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                <?php echo htmlspecialchars($prod->name); ?> <strong style="color: var(--text-1);">×<?php echo $qty; ?></strong>
                            </span>
                            <span style="font-weight: 600; flex-shrink: 0;"><?php echo \App\Services\CurrencyService::format($itemSubtotal); ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <div style="display: flex; flex-direction: column; gap: 8px; font-size: 14px; border-top: 1px solid var(--border); padding-top: 14px;">
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-3);">Ara Toplam:</span>
                            <span style="font-weight: 600;"><?php echo \App\Services\CurrencyService::format($totalPrice); ?></span>
                        </div>
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-3);">Kargo Ücreti:</span>
                            <span style="font-weight: 600;" id="shipping-cost-display">0,00 TL</span>
                        </div>
                        <div style="display: none; justify-content: space-between;" id="payment-fee-row">
                            <span style="color: var(--text-3);">İşlem Ücreti:</span>
                            <span style="font-weight: 600;" id="payment-fee-display">0,00 TL</span>
                        </div>
                        <div style="display: flex; justify-content: space-between; font-size: 16px; font-weight: 700; border-top: 1px solid var(--border); padding-top: 10px; margin-top: 4px;">
                            <span>Genel Toplam:</span>
                            <span style="color: var(--orange);" id="total-price-display"><?php echo \App\Services\CurrencyService::format($totalPrice); ?></span>
                        </div>
                    </div>

                    <button type="submit" style="display: inline-flex; align-items: center; justify-content: center; gap: 10px; background: var(--orange); color: #fff; border: none; border-radius: var(--r-md); padding: 16px 28px; font-size: 16px; font-weight: 600; cursor: pointer; width: 100%; margin-top: 16px; transition: all .25s var(--ease);">
                        <i class="fa fa-check-circle"></i> Siparişi Onayla
                    </button>
                </aside>

            </div><!-- /.checkout-grid -->

        </form>
    </main>
</div>

<?php else: ?>

<!-- ===== GUEST: full-width layout ===== -->
<div class="checkout-guest-wrap">
    <div style="background: var(--surface-card); border-radius: var(--r-lg); box-shadow: var(--shadow-card); border: 1px solid var(--border); padding: 40px;">
        <h1 style="font-size: 22px; color: var(--text-1); margin: 0 0 4px 0;">Sipariş Onayı</h1>
        <p style="color: var(--text-3); font-size: 14px; margin: 0 0 24px 0;">Bilgilerinizi girerek siparişi tamamlayın.</p>

        <form action="<?php echo $baseUrl; ?>/checkout/submit" method="POST">

            <?php if (!empty($error)): ?>
            <div style="background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.3); border-radius: var(--r-md); padding: 16px; margin-bottom: 24px;">
                <div style="display: flex; align-items: center; gap: 12px;">
                    <i class="fa fa-exclamation-circle" style="color: #ef4444; font-size: 24px;"></i>
                    <div>
                        <strong style="color: #ef4444; display: block; font-size: 15px; margin-bottom: 4px;">Ödeme İşlemi Başarısız</strong>
                        <span style="color: var(--text-2); font-size: 14px;"><?php echo htmlspecialchars($error); ?></span>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div class="checkout-grid">

                <div style="display: flex; flex-direction: column; gap: 24px;">

                    <!-- Delivery -->
                    <section style="background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-md); padding: 20px;">
                        <h2 style="font-size: 15px; font-weight: 700; margin: 0 0 16px 0; color: var(--text-1);">
                            <i class="fa fa-map-marker" style="color: var(--orange);"></i> Teslimat Bilgileri
                        </h2>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                            <div style="grid-column: 1 / -1;">
                                <label style="display: block; font-size: 12px; color: var(--text-3); margin-bottom: 6px;">Ad Soyad</label>
                                <input type="text" name="customer_name" required
                                    style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-card); color: var(--text-1); font-family: var(--font); box-sizing: border-box; outline: none;">
                            </div>
                            <div>
                                <label style="display: block; font-size: 12px; color: var(--text-3); margin-bottom: 6px;">E-posta</label>
                                <input type="email" name="customer_email" required
                                    style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-card); color: var(--text-1); font-family: var(--font); box-sizing: border-box; outline: none;">
                            </div>
                            <div>
                                <label style="display: block; font-size: 12px; color: var(--text-3); margin-bottom: 6px;">Telefon</label>
                                <input type="tel" name="customer_phone" required
                                    style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-card); color: var(--text-1); font-family: var(--font); box-sizing: border-box; outline: none;">
                            </div>
                            <div style="grid-column: 1 / -1;">
                                <label style="display: block; font-size: 12px; color: var(--text-3); margin-bottom: 6px;">Teslimat Adresi</label>
                                <textarea name="customer_address" rows="3" required
                                    style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-card); color: var(--text-1); font-family: var(--font); box-sizing: border-box; outline: none; resize: vertical;"></textarea>
                            </div>
                            <div style="grid-column: 1 / -1;">
                                <label style="display: block; font-size: 12px; color: var(--text-3); margin-bottom: 6px;">Sipariş Notu (İsteğe Bağlı)</label>
                                <textarea name="customer_notes" rows="2" placeholder="Siparişinizle ilgili notunuz varsa..."
                                    style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-card); color: var(--text-1); font-family: var(--font); box-sizing: border-box; outline: none; resize: vertical;"></textarea>
                            </div>
                        </div>
                    </section>

                    <!-- Shipping -->
                    <?php if (!empty($shippingMethods)): ?>
                    <section style="background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-md); padding: 20px;">
                        <h2 style="font-size: 15px; font-weight: 700; margin: 0 0 16px 0; color: var(--text-1);">
                            <i class="fa fa-truck" style="color: var(--orange);"></i> Kargo Seçenekleri
                        </h2>
                        <div style="display: flex; flex-direction: column; gap: 10px;">
                            <?php $firstShipping = true; foreach ($shippingMethods as $opt): ?>
                            <?php if (empty($opt['name'])) continue; ?>
                            <label style="display: flex; align-items: center; gap: 10px; padding: 12px 16px; border: 1px solid var(--border); border-radius: var(--r-md); cursor: pointer; background: var(--surface-card);">
                                <input type="radio" name="shipping_method" value="<?php echo htmlspecialchars($opt['name']); ?>"
                                    data-cost="<?php echo (float)($opt['cost'] ?? 0); ?>"
                                    class="shipping-radio"
                                    style="accent-color: var(--orange);"
                                    <?php echo $firstShipping ? 'checked' : ''; ?>>
                                <span style="flex: 1; font-size: 14px; font-weight: 500;"><?php echo htmlspecialchars($opt['name']); ?></span>
                                <span style="font-weight: 700; color: var(--orange);">
                                    <?php echo \App\Services\CurrencyService::format((float)($opt['cost'] ?? 0)); ?>
                                </span>
                            </label>
                            <?php $firstShipping = false; endforeach; ?>
                        </div>
                    </section>
                    <?php endif; ?>

                    <!-- Payment -->
                    <section style="background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-md); padding: 20px;">
                        <h2 style="font-size: 15px; font-weight: 700; margin: 0 0 16px 0; color: var(--text-1);">
                            <i class="fa fa-credit-card" style="color: var(--orange);"></i> Ödeme Yöntemi
                        </h2>
                        <?php include __DIR__ . '/components/payment_methods_form.php'; ?>
                    </section>

                </div>

                <!-- Order Summary -->
                <aside style="background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-lg); padding: 24px; position: sticky; top: 20px;">
                    <h3 style="font-size: 16px; font-weight: 700; margin: 0 0 16px 0; padding-bottom: 12px; border-bottom: 1px solid var(--border);">Sepetiniz</h3>

                    <div style="display: flex; flex-direction: column; gap: 12px; max-height: 240px; overflow-y: auto; margin-bottom: 16px;">
                        <?php 
                        $totalPrice = 0.0;
                        foreach ($cartItems as $item):
                            $prod = $item['product'];
                            $qty  = $item['quantity'];
                            $itemPrice    = $prod->getConvertedPrice();
                            $itemSubtotal = $itemPrice * $qty;
                            $totalPrice  += $itemSubtotal;
                        ?>
                        <div style="display: flex; justify-content: space-between; align-items: start; gap: 8px; font-size: 13px;">
                            <span style="color: var(--text-3); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                <?php echo htmlspecialchars($prod->name); ?> <strong style="color: var(--text-1);">×<?php echo $qty; ?></strong>
                            </span>
                            <span style="font-weight: 600; flex-shrink: 0;"><?php echo \App\Services\CurrencyService::format($itemSubtotal); ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <div style="display: flex; flex-direction: column; gap: 8px; font-size: 14px; border-top: 1px solid var(--border); padding-top: 14px;">
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-3);">Ara Toplam:</span>
                            <span style="font-weight: 600;"><?php echo \App\Services\CurrencyService::format($totalPrice); ?></span>
                        </div>
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-3);">Kargo Ücreti:</span>
                            <span style="font-weight: 600;" id="shipping-cost-display">0,00 TL</span>
                        </div>
                        <div style="display: none; justify-content: space-between;" id="payment-fee-row">
                            <span style="color: var(--text-3);">İşlem Ücreti:</span>
                            <span style="font-weight: 600;" id="payment-fee-display">0,00 TL</span>
                        </div>
                        <div style="display: flex; justify-content: space-between; font-size: 16px; font-weight: 700; border-top: 1px solid var(--border); padding-top: 10px; margin-top: 4px;">
                            <span>Genel Toplam:</span>
                            <span style="color: var(--orange);" id="total-price-display"><?php echo \App\Services\CurrencyService::format($totalPrice); ?></span>
                        </div>
                    </div>

                    <button type="submit" style="display: inline-flex; align-items: center; justify-content: center; gap: 10px; background: var(--orange); color: #fff; border: none; border-radius: var(--r-md); padding: 16px 28px; font-size: 16px; font-weight: 600; cursor: pointer; width: 100%; margin-top: 16px; transition: all .25s var(--ease);">
                        <i class="fa fa-check-circle"></i> Siparişi Onayla
                    </button>
                </aside>

            </div><!-- /.checkout-grid -->
        </form>
    </div>
</div>

<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const subtotal = <?php echo (float)($totalPrice ?? 0); ?>;
    const currencySymbol = '<?php echo \App\Services\CurrencyService::getSymbol(\App\Services\CurrencyService::getCurrentCurrency()); ?>';

    function formatCurrency(amount) {
        return new Intl.NumberFormat('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(amount) + ' ' + currencySymbol;
    }

    const shippingRadios = document.querySelectorAll('.shipping-radio');
    const paymentRadios  = document.querySelectorAll('.payment-radio');
    const shippingDisplay = document.getElementById('shipping-cost-display');
    const totalDisplay    = document.getElementById('total-price-display');
    const paymentFeeRow   = document.getElementById('payment-fee-row');
    const paymentFeeDisp  = document.getElementById('payment-fee-display');

    function updateTotal() {
        const checkedShipping = document.querySelector('.shipping-radio:checked');
        let shippingCost = 0;
        if (checkedShipping) {
            shippingCost = parseFloat(checkedShipping.getAttribute('data-cost') || '0') || 0;
        }

        const checkedPayment = document.querySelector('.payment-radio:checked');
        let paymentFee = 0;
        if (checkedPayment && checkedPayment.value === 'cash_on_delivery') {
            paymentFee = parseFloat(checkedPayment.getAttribute('data-fee') || '0') || 0;
        }

        if (shippingDisplay) shippingDisplay.textContent = formatCurrency(shippingCost);
        if (totalDisplay)    totalDisplay.textContent    = formatCurrency(subtotal + shippingCost + paymentFee);
        if (paymentFeeRow) {
            paymentFeeRow.style.display = paymentFee > 0 ? 'flex' : 'none';
        }
        if (paymentFeeDisp) paymentFeeDisp.textContent = formatCurrency(paymentFee);
    }

    shippingRadios.forEach(r => r.addEventListener('change', updateTotal));
    paymentRadios.forEach(r  => r.addEventListener('change', updateTotal));
    updateTotal();

    const ccForm  = document.getElementById('credit-card-form');
    const btInfo  = document.getElementById('bank-transfer-info');
    const codInfo = document.getElementById('cash-on-delivery-info');

    function updatePaymentForms() {
        const checkedPayment = document.querySelector('.payment-radio:checked');
        const val = checkedPayment ? checkedPayment.value : '';
        if (ccForm)  ccForm.style.display  = val === 'credit_card'      ? 'flex'  : 'none';
        if (btInfo)  btInfo.style.display  = val === 'bank_transfer'    ? 'block' : 'none';
        if (codInfo) codInfo.style.display = val === 'cash_on_delivery' ? 'block' : 'none';
    }

    paymentRadios.forEach(r => r.addEventListener('change', updatePaymentForms));
    updatePaymentForms();

    // ===== Credit Card Formatting & Validation =====
    const ccNumber = document.getElementById('cc-number');
    const ccExpiry = document.getElementById('cc-expiry');
    const ccCvv    = document.getElementById('cc-cvv');
    const ccName   = document.getElementById('cc-name');
    const ccError  = document.getElementById('cc-error');

    function showCCError(msg) {
        if (ccError) { ccError.textContent = msg; ccError.style.display = 'block'; }
    }
    function hideCCError() {
        if (ccError) { ccError.style.display = 'none'; ccError.textContent = ''; }
    }

    // Card number: only digits, auto-space every 4
    if (ccNumber) {
        ccNumber.addEventListener('input', function(e) {
            let v = this.value.replace(/\D/g, '');
            if (v.length > 16) v = v.substring(0, 16);
            this.value = v.replace(/(.{4})/g, '$1 ').trim();
            hideCCError();
        });
        ccNumber.addEventListener('keydown', function(e) {
            const allowed = ['Backspace','Delete','Tab','ArrowLeft','ArrowRight','Home','End'];
            if (allowed.includes(e.key) || e.ctrlKey || e.metaKey) return;
            if (!/^\d$/.test(e.key)) e.preventDefault();
        });
    }

    // Expiry: only digits, auto-slash after 2
    if (ccExpiry) {
        ccExpiry.addEventListener('input', function(e) {
            let v = this.value.replace(/\D/g, '');
            if (v.length > 4) v = v.substring(0, 4);
            if (v.length >= 2) {
                let month = parseInt(v.substring(0, 2), 10);
                if (month > 12) v = '12' + v.substring(2);
                if (month < 1 && v.substring(0,2) !== '0' && v.substring(0,2) !== '00') v = '01' + v.substring(2);
                this.value = v.substring(0, 2) + '/' + v.substring(2);
            } else {
                this.value = v;
            }
            hideCCError();
        });
        ccExpiry.addEventListener('keydown', function(e) {
            const allowed = ['Backspace','Delete','Tab','ArrowLeft','ArrowRight','Home','End'];
            if (allowed.includes(e.key) || e.ctrlKey || e.metaKey) return;
            if (!/^\d$/.test(e.key)) e.preventDefault();
        });
    }

    // CVV: only digits
    if (ccCvv) {
        ccCvv.addEventListener('input', function() {
            this.value = this.value.replace(/\D/g, '').substring(0, 4);
            hideCCError();
        });
        ccCvv.addEventListener('keydown', function(e) {
            const allowed = ['Backspace','Delete','Tab','ArrowLeft','ArrowRight','Home','End'];
            if (allowed.includes(e.key) || e.ctrlKey || e.metaKey) return;
            if (!/^\d$/.test(e.key)) e.preventDefault();
        });
    }

    // Card name: only letters and spaces
    if (ccName) {
        ccName.addEventListener('input', function() {
            this.value = this.value.replace(/[^a-zA-ZçÇğĞıİöÖşŞüÜ\s]/g, '').toUpperCase();
            hideCCError();
        });
    }

    // Form submit validation
    document.querySelectorAll('form').forEach(function(form) {
        form.addEventListener('submit', function(e) {
            const checkedPayment = document.querySelector('.payment-radio:checked');
            if (!checkedPayment || checkedPayment.value !== 'credit_card') return;

            hideCCError();

            const name = ccName ? ccName.value.trim() : '';
            const number = ccNumber ? ccNumber.value.replace(/\s/g, '') : '';
            const expiry = ccExpiry ? ccExpiry.value.trim() : '';
            const cvv = ccCvv ? ccCvv.value.trim() : '';

            if (name.length < 3) {
                e.preventDefault();
                showCCError('Kart üzerindeki ismi girin (en az 3 karakter).');
                if (ccName) ccName.focus();
                return;
            }
            if (number.length < 15 || number.length > 16) {
                e.preventDefault();
                showCCError('Geçerli bir kart numarası girin (15-16 haneli).');
                if (ccNumber) ccNumber.focus();
                return;
            }
            if (!/^\d{2}\/\d{2}$/.test(expiry)) {
                e.preventDefault();
                showCCError('Son kullanma tarihini AA/YY formatında girin.');
                if (ccExpiry) ccExpiry.focus();
                return;
            }
            const [mm, yy] = expiry.split('/').map(Number);
            const now = new Date();
            const expDate = new Date(2000 + yy, mm);
            if (mm < 1 || mm > 12 || expDate <= now) {
                e.preventDefault();
                showCCError('Kart son kullanma tarihi geçersiz veya süresi dolmuş.');
                if (ccExpiry) ccExpiry.focus();
                return;
            }
            if (cvv.length < 3 || cvv.length > 4) {
                e.preventDefault();
                showCCError('CVV 3 veya 4 haneli olmalıdır.');
                if (ccCvv) ccCvv.focus();
                return;
            }
        });
    });
});
</script>

<?php include __DIR__ . '/../layout/footer.php'; ?>
