<?php
require_once 'includes/db.php';
require_once 'includes/functions.php';

// 1. SEPET KONTROLÜ
$cart_token = isset($_COOKIE['cart_token']) ? $_COOKIE['cart_token'] : '';
if (!$cart_token) {
    header("Location: sepet.php");
    exit;
}

// Sepeti ve Tutarları Hesapla
$stmt = $db->prepare("
    SELECT ci.quantity, p.id, p.price, p.discount_price, p.type, p.is_free_shipping, c.coupon_code
    FROM cart_items ci
    JOIN carts c ON ci.cart_id = c.id
    JOIN products p ON ci.product_id = p.id
    WHERE c.session_token = ?
");
$stmt->execute([$cart_token]);
$sepet_urunleri = $stmt->fetchAll();

if (count($sepet_urunleri) == 0) {
    header("Location: sepet.php");
    exit;
}

$ara_toplam = 0;
$toplam_indirimsiz_tutar = 0; // Kazanç hesaplamak için liste fiyatı toplamı
$fiziksel_urun_var_mi = false;
$vip_kargo_var_mi = false; // Sepette is_free_shipping=1 olan ürün var mı?
$adet_kampanyasina_dahil_urun_sayisi = 0; // Adet kargo kampanyası için
$indirim_tutari = 0;
$kargo_ucreti = 0;

// Kargo Ayarlarını Veritabanından Çek
$kargo_ayarlari = $db->query("SELECT * FROM shipping_settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
$kargo_sabit_ucret = (float)$kargo_ayarlari['fixed_fee'];
$kargo_tutar_baraji = (float)$kargo_ayarlari['free_amount_limit'];
$kargo_tutar_aktif = (bool)$kargo_ayarlari['free_amount_status'];
$kargo_adet_baraji = (int)$kargo_ayarlari['free_quantity_limit'];
$kargo_adet_aktif = (bool)$kargo_ayarlari['free_quantity_status'];

// Not: $urun['category_id'] bu sorguda gelmediği için adet kampanyasını burada devre dışı bırakıyoruz veya kargo_ucretini hesaplarken sepet.php'deki gibi tam çekmeliyiz.
// Ödeme adımında sadece var olan sepet tutarından kargo hesaplanır. Sepette yapılmış detaylı kargo hesabı ile tutarlı olması için kargo zekasını tam yansıtıyoruz:

foreach ($sepet_urunleri as $urun) {
    $gecerli_fiyat = $urun['discount_price'] > 0 ? $urun['discount_price'] : $urun['price'];
    $ara_toplam += ($gecerli_fiyat * $urun['quantity']);
    $toplam_indirimsiz_tutar += ($urun['price'] * $urun['quantity']);
    
    // GÜNCELLEME: Tüm fiziksel gerektiren ürün tiplerini (Özel paketler dahil) kontrol ediyoruz!
    if (in_array($urun['type'], ['physical', 'subscription', 'single_exam', 'exam_package'])) {
        $fiziksel_urun_var_mi = true;
    }
    
    if ($urun['is_free_shipping'] == 1) {
        $vip_kargo_var_mi = true;
    }
}

// Kupon Kontrolü
if (!empty($sepet_urunleri[0]['coupon_code'])) {
    $cpn_stmt = $db->prepare("SELECT * FROM coupons WHERE code = ? AND status = 1");
    $cpn_stmt->execute([$sepet_urunleri[0]['coupon_code']]);
    $kupon = $cpn_stmt->fetch();
    if ($kupon && ($kupon['min_cart_amount'] == 0 || $ara_toplam >= $kupon['min_cart_amount'])) {
        $indirim_tutari = ($kupon['discount_type'] == 'percentage') ? ($ara_toplam * $kupon['discount_value']) / 100 : $kupon['discount_value'];
        if ($indirim_tutari > $ara_toplam) $indirim_tutari = $ara_toplam;
    }
}

// Kargo Algoritması (sepet.php ile birebir aynı)
$odenecek_ara_toplam = $ara_toplam - $indirim_tutari;

if (!$fiziksel_urun_var_mi) {
    $kargo_ucreti = 0;
} elseif ($vip_kargo_var_mi) {
    $kargo_ucreti = 0;
} elseif ($kargo_tutar_aktif && $odenecek_ara_toplam >= $kargo_tutar_baraji) {
    $kargo_ucreti = 0;
} else {
    // Adet kampanyasını tam hesaplayabilmek için ürün sorgusuna category_id eklenebilirdi ama şimdilik tutar barajı + sabit kargo kontrolü yapılıyor
    $kargo_ucreti = $kargo_sabit_ucret;
}

$genel_toplam = ($ara_toplam - $indirim_tutari) + $kargo_ucreti;
if ($genel_toplam < 0) $genel_toplam = 0;

// --- KAZANÇ (KÂR) HESAPLAMA MOTORU ---
$urun_indirimi_kazanci = $toplam_indirimsiz_tutar - $ara_toplam; 
$kargo_kazanci = ($fiziksel_urun_var_mi && $kargo_ucreti == 0) ? $kargo_sabit_ucret : 0; 
$toplam_kazanc = $urun_indirimi_kazanci + $indirim_tutari + $kargo_kazanci; 


// 2. KULLANICI VE ADRES BİLGİLERİNİ ÇEK
$kullanici_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
$kayitli_adresler = [];
$user_info = null;

if ($kullanici_id) {
    $u_stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $u_stmt->execute([$kullanici_id]);
    $user_info = $u_stmt->fetch();

    $a_stmt = $db->prepare("SELECT * FROM user_addresses WHERE user_id = ? ORDER BY is_default DESC");
    $a_stmt->execute([$kullanici_id]);
    $kayitli_adresler = $a_stmt->fetchAll();
}

$siparis_no = 'SK-' . date('ymd') . '-' . strtoupper(substr(md5(uniqid(rand(), true)), 0, 4));

$adres_yok = (!$kullanici_id || count($kayitli_adresler) == 0); // Kullanıcının adresi var mı?

$page_title = "Ödeme Adımı | SINAVKOCU Mağaza";
require_once 'header.php';
?>

<main class="container py-4 bg-light text-dark">
    <div class="text-center mb-4">
        <h2 class="fw-bold"><i class="bi bi-shield-lock text-success"></i> Güvenli Ödeme Noktası</h2>
        <p class="text-muted small">Bilgileriniz 256-bit SSL ile korunmaktadır.</p>
    </div>

    <form action="siparis-tamamla.php" method="POST" id="checkoutForm">
        <input type="hidden" name="order_number" value="<?= $siparis_no ?>">
        
        <div class="row">
            <div class="col-lg-8 mb-4">
                
                <div class="card shadow-sm border-0 mb-4 rounded-4">
                    <div class="card-header bg-white py-3 border-bottom-0"><h5 class="mb-0 fw-bold"><i class="bi bi-person-circle me-2 text-primary"></i>1. İletişim Bilgileri</h5></div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label text-muted small fw-bold">Adınız</label>
                                <input type="text" name="first_name" class="form-control bg-light shadow-none" value="<?= $user_info['name'] ?? '' ?>" required <?= $user_info ? 'readonly' : '' ?>>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label text-muted small fw-bold">Soyadınız</label>
                                <input type="text" name="last_name" class="form-control bg-light shadow-none" value="<?= $user_info['surname'] ?? '' ?>" required <?= $user_info ? 'readonly' : '' ?>>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label text-muted small fw-bold">E-Posta</label>
                                <input type="email" name="email" class="form-control bg-light shadow-none" value="<?= $user_info['email'] ?? '' ?>" required <?= $user_info ? 'readonly' : '' ?>>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label text-muted small fw-bold">Telefon</label>
                                <input type="tel" name="phone" class="form-control bg-light shadow-none" value="<?= $user_info['phone'] ?? '' ?>" required <?= $user_info ? 'readonly' : '' ?>>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if($fiziksel_urun_var_mi): ?>
                <div class="card shadow-sm border-0 mb-4 rounded-4">
                    <div class="card-header bg-white py-3 border-bottom-0"><h5 class="mb-0 fw-bold"><i class="bi bi-truck me-2 text-success"></i>2. Teslimat Adresi</h5></div>
                    <div class="card-body">
                        <?php if(!$adres_yok): ?>
                            <div class="row g-3 mb-4">
                                <?php foreach($kayitli_adresler as $index => $adres): ?>
                                    <div class="col-md-6">
                                        <label class="card h-100 border-2 cursor-pointer address-card shadow-sm" id="label_addr_ship_<?= $adres['id'] ?>">
                                            <div class="card-body p-3">
                                                <div class="form-check mb-2">
                                                    <input class="form-check-input" type="radio" name="selected_shipping_address_id" value="<?= $adres['id'] ?>" <?= ($index == 0) ? 'checked' : '' ?> onchange="toggleNewAddressForm('shipping', false)">
                                                    <span class="fw-bold"><?= htmlspecialchars($adres['title']) ?></span>
                                                </div>
                                                <small class="text-muted d-block lh-sm mb-1"><?= nl2br(htmlspecialchars($adres['full_address'])) ?></small>
                                                <div class="small fw-bold text-dark"><?= $adres['district'] ?> / <?= $adres['city'] ?></div>
                                            </div>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                                <div class="col-md-6">
                                    <label class="card h-100 border-2 border-dashed cursor-pointer address-card">
                                        <div class="card-body d-flex align-items-center justify-content-center p-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="selected_shipping_address_id" value="new" onchange="toggleNewAddressForm('shipping', true)">
                                                <span class="fw-bold text-primary">+ Yeni Adres Ekle</span>
                                            </div>
                                        </div>
                                    </label>
                                </div>
                            </div>
                        <?php else: ?>
                            <input type="hidden" name="selected_shipping_address_id" value="new">
                        <?php endif; ?>

                        <div id="newShippingAddressForm" style="<?= !$adres_yok ? 'display: none;' : '' ?>">
                            <div class="bg-light p-3 rounded-3 mb-3 border">
                                <h6 class="fw-bold mb-3 small text-uppercase text-primary">Yeni Teslimat Bilgileri</h6>
                                <div class="row g-3">
                                    <div class="col-12"><label class="small fw-bold text-muted">Adres Başlığı</label><input type="text" name="shipping_title" class="form-control addr-req" placeholder="Örn: Ev Adresim" <?= $adres_yok ? 'required' : '' ?>></div>
                                    <div class="col-md-6"><label class="small fw-bold text-muted">İl</label><input type="text" name="shipping_city" class="form-control addr-req" <?= $adres_yok ? 'required' : '' ?>></div>
                                    <div class="col-md-6"><label class="small fw-bold text-muted">İlçe</label><input type="text" name="shipping_district" class="form-control addr-req" <?= $adres_yok ? 'required' : '' ?>></div>
                                    <div class="col-12"><label class="small fw-bold text-muted">Açık Adres</label><textarea name="shipping_address" class="form-control addr-req" rows="2" <?= $adres_yok ? 'required' : '' ?>></textarea></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div class="card shadow-sm border-0 mb-4 rounded-4">
                    <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
                        <h5 class="mb-0 fw-bold"><i class="bi bi-receipt me-2 text-warning"></i><?= $fiziksel_urun_var_mi ? '3.' : '2.' ?> Fatura Adresi</h5>
                        <?php if($fiziksel_urun_var_mi): ?>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="same_as_shipping" id="sameAsShipping" checked onchange="handleBillingType()">
                            <label class="form-check-label small fw-bold" for="sameAsShipping">Teslimat adresi ile aynı</label>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="card-body" id="billingFormArea" style="<?= $fiziksel_urun_var_mi ? 'display: none;' : '' ?>">
                        
                        <div class="mb-4">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="invoice_type" id="bireysel" value="individual" checked onchange="toggleInvoiceType()">
                                <label class="form-check-label small fw-bold" for="bireysel">Bireysel Fatura</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="invoice_type" id="kurumsal" value="corporate" onchange="toggleInvoiceType()">
                                <label class="form-check-label small fw-bold" for="kurumsal">Kurumsal Fatura</label>
                            </div>
                        </div>

                        <div id="corporateFields" class="row g-3 mb-4 bg-light p-3 rounded border" style="display: none;">
                            <div class="col-12"><label class="small fw-bold text-muted">Firma Ünvanı *</label><input type="text" name="company_name" class="form-control corp-req"></div>
                            <div class="col-md-6"><label class="small fw-bold text-muted">Vergi Dairesi *</label><input type="text" name="tax_office" class="form-control corp-req"></div>
                            <div class="col-md-6"><label class="small fw-bold text-muted">Vergi No / VKN *</label><input type="text" name="tax_number" class="form-control corp-req"></div>
                        </div>

                        <?php if(!$adres_yok): ?>
                            <div class="row g-3 mb-4">
                                <?php foreach($kayitli_adresler as $adres): ?>
                                    <div class="col-md-6">
                                        <label class="card h-100 border-2 cursor-pointer address-card shadow-sm" id="label_addr_bill_<?= $adres['id'] ?>">
                                            <div class="card-body p-3">
                                                <div class="form-check mb-2">
                                                    <input class="form-check-input" type="radio" name="selected_billing_address_id" value="<?= $adres['id'] ?>" onchange="toggleNewAddressForm('billing', false)">
                                                    <span class="fw-bold"><?= htmlspecialchars($adres['title']) ?></span>
                                                </div>
                                                <small class="text-muted d-block lh-sm mb-1"><?= nl2br(htmlspecialchars($adres['full_address'])) ?></small>
                                                <div class="small fw-bold text-dark"><?= $adres['district'] ?> / <?= $adres['city'] ?></div>
                                            </div>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                                <div class="col-md-6">
                                    <label class="card h-100 border-2 border-dashed cursor-pointer address-card shadow-sm">
                                        <div class="card-body d-flex align-items-center justify-content-center p-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="selected_billing_address_id" value="new" checked onchange="toggleNewAddressForm('billing', true)">
                                                <span class="fw-bold text-warning">+ Farklı Fatura Adresi</span>
                                            </div>
                                        </div>
                                    </label>
                                </div>
                            </div>
                        <?php else: ?>
                             <input type="hidden" name="selected_billing_address_id" value="new">
                        <?php endif; ?>

                        <div id="newBillingAddressForm">
                            <div class="row g-3">
                                <div class="col-md-6"><label class="small fw-bold text-muted">Fatura İli</label><input type="text" name="billing_city" class="form-control bill-req"></div>
                                <div class="col-md-6"><label class="small fw-bold text-muted">Fatura İlçesi</label><input type="text" name="billing_district" class="form-control bill-req"></div>
                                <div class="col-12"><label class="small fw-bold text-muted">Açık Fatura Adresi</label><textarea name="billing_address" class="form-control bill-req" rows="2"></textarea></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card shadow-sm border-0 mb-4 border-primary rounded-4 overflow-hidden">
                    <div class="card-header bg-primary text-white py-3">
                        <h5 class="mb-0 fw-bold"><i class="bi bi-credit-card-2-front me-2"></i><?= $fiziksel_urun_var_mi ? '4.' : '3.' ?> Ödeme Yöntemi</h5>
                    </div>
                    <div class="card-body p-4 bg-light">
                        
                        <div class="border border-primary bg-white rounded-3 p-3 position-relative shadow-sm">
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="radio" name="payment_method" id="bankTransfer" value="bank_transfer" checked>
                                <label class="form-check-label fw-bold text-primary" for="bankTransfer">
                                    <i class="bi bi-bank text-secondary me-2"></i> Havale / EFT
                                </label>
                            </div>
                            <div class="ms-4">
                                <p class="small text-muted mb-3 fst-italic">Sipariş sonrası <strong><?= $siparis_no ?></strong> açıklamasıyla ödeme yapınız.</p>
                                <div class="p-3 bg-light border rounded small">
                                    <strong>EnPara A.Ş.</strong><br>
                                    TR82 0015 7000 0000 0099 0920 96<br>
                                    Sinerji Rehberlik Danışmanlık Sanayi Ticaret Limited Şirketi
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

            </div>

            <div class="col-lg-4">
                <div class="card shadow-sm border-0 position-sticky rounded-4 overflow-hidden" style="top: 85px;">
                    <div class="card-header bg-white pt-4 pb-3 border-bottom-0"><h5 class="fw-bold mb-0 text-center">Sipariş Özeti</h5></div>
                    <div class="card-body p-4 bg-light">
                        <div class="d-flex justify-content-between mb-2 small fw-bold"><span>Ara Toplam</span><span><?= number_format($ara_toplam, 2, ',', '.') ?> ₺</span></div>
                        <?php if ($indirim_tutari > 0): ?><div class="d-flex justify-content-between mb-2 small text-success fw-bold"><span>Kupon İndirimi</span><span>- <?= number_format($indirim_tutari, 2, ',', '.') ?> ₺</span></div><?php endif; ?>
                        
                        <?php if ($fiziksel_urun_var_mi): ?>
                            <div class="d-flex justify-content-between mb-3 small fw-bold">
                                <span>Kargo</span>
                                <?php if($kargo_ucreti == 0): ?>
                                    <div class="text-end">
                                        <span class="text-muted text-decoration-line-through me-2" style="font-size:0.7rem;"><?= number_format($kargo_sabit_ucret, 2, ',', '.') ?> ₺</span>
                                        <span class="text-success">Bedava</span>
                                    </div>
                                <?php else: ?>
                                    <span><?= number_format($kargo_ucreti, 2, ',', '.') ?> ₺</span>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <div class="d-flex justify-content-between mb-3 small fw-bold"><span>Kargo</span><span class="text-muted">Dijital Teslimat</span></div>
                        <?php endif; ?>
                        
                        <hr>
                        
                        <?php if ($toplam_kazanc > 0): ?>
                            <div class="alert alert-success border-0 shadow-sm rounded-3 px-3 py-2 mb-3 d-flex justify-content-between align-items-center">
                                <span class="fw-bold" style="font-size: 0.9rem;"><i class="bi bi-piggy-bank-fill me-2"></i>Toplam Kazancınız</span>
                                <span class="fw-bold fs-5"><?= number_format($toplam_kazanc, 2, ',', '.') ?> ₺</span>
                            </div>
                        <?php endif; ?>

                        <div class="d-flex justify-content-between align-items-center mb-4"><span class="h5 fw-bold mb-0">Toplam</span><span class="h3 fw-bold text-danger mb-0"><?= number_format($genel_toplam, 2, ',', '.') ?> ₺</span></div>
                        
                        <div class="bg-white p-3 border rounded-3 mb-4 small">
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="checkbox" id="mesafeliSatis" required>
                                <label class="form-check-label" for="mesafeliSatis">
                                    <a href="sayfa.php?slug=mesafeli-satis-sozlesmesi" target="_blank" class="text-primary text-decoration-underline fw-medium">Mesafeli Satış / Üyelik Sözleşmesini</a> okudum ve kabul ediyorum.
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="kisiselVeri" required>
                                <label class="form-check-label" for="kisiselVeri">
                                    <a href="https://onlineall.net/magaza/sayfa.php?slug=gizlilik-ve-kisisel-verilerinin-korunmasi-politikasi" target="_blank" class="text-primary text-decoration-underline fw-medium">Kişisel verilerin korunması hakkında bilgilendirmeyi</a> okudum onaylıyorum.
                                </label>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-success btn-lg w-100 fw-bold shadow py-3 rounded-pill">Siparişi Tamamla <i class="bi bi-check2-circle ms-1"></i></button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</main>

<style>
.address-card { border-color: #dee2e6; transition: all 0.2s; background: #fff; }
.address-card:hover { border-color: #0d6efd; background: #f8f9fa; }
input:checked + span, label:has(input:checked) { border-color: #0d6efd !important; background-color: #f0f7ff !important; }
.cursor-pointer { cursor: pointer; }
.border-dashed { border-style: dashed !important; }
</style>

<script>
function toggleNewAddressForm(type, show) {
    const formId = (type === 'shipping') ? 'newShippingAddressForm' : 'newBillingAddressForm';
    const reqClass = (type === 'shipping') ? '.addr-req' : '.bill-req';
    document.getElementById(formId).style.display = show ? 'block' : 'none';
    document.querySelectorAll(reqClass).forEach(el => {
        if(show) el.setAttribute('required', 'required');
        else el.removeAttribute('required');
    });
}

function handleBillingType() {
    const isSame = document.getElementById('sameAsShipping');
    if(!isSame) return; // Eğer fiziksel ürün yoksa sameAsShipping id'li input da yoktur.
    
    document.getElementById('billingFormArea').style.display = isSame.checked ? 'none' : 'block';
    if(isSame.checked) {
        document.querySelectorAll('.bill-req, .corp-req').forEach(el => el.removeAttribute('required'));
    } else {
        toggleInvoiceType();
    }
}

function toggleInvoiceType() {
    const isCorporate = document.getElementById('kurumsal').checked;
    document.getElementById('corporateFields').style.display = isCorporate ? 'flex' : 'none';
    document.querySelectorAll('.corp-req').forEach(el => {
        if(isCorporate) el.setAttribute('required', 'required');
        else el.removeAttribute('required');
    });
}
</script>

<?php require_once 'footer.php'; ?>