<?php
require __DIR__ . '/app/bootstrap.php';

$quantity = (int) ($_GET['quantity'] ?? ($_SESSION['checkout_old']['quantity'] ?? 1));
$package = package_details($quantity) ?? package_details(1);
$quantity = $package['quantity'];
$errors = $_SESSION['checkout_errors'] ?? [];
$old = $_SESSION['checkout_old'] ?? [];
unset($_SESSION['checkout_errors'], $_SESSION['checkout_old']);

$pageTitle = 'Sipariş Bilgileri';
$pageDescription = 'Teslimat bilgilerinizi girerek güvenli siparişinizi oluşturun.';
require __DIR__ . '/app/header.php';

function old_value(string $key, string $default = ''): string
{
    global $old;
    return e($old[$key] ?? $default);
}

function field_error(string $key): string
{
    global $errors;
    return isset($errors[$key]) ? '<span class="field-error">' . e($errors[$key]) . '</span>' : '';
}
?>
<section class="page-shell">
    <div class="container">
        <div class="page-heading checkout-heading">
            <a class="back-link" href="index.php"><i class="bi bi-arrow-left"></i> Ürüne dön</a>
            <div class="checkout-kicker"><i class="bi bi-shield-lock-fill"></i> 256-bit güvenli sipariş akışı</div>
            <h1>Siparişinizi tamamlayın</h1>
            <p>Bilgilerinizi tamamlayın; banka ve IBAN detayları bir sonraki adımda güvenli biçimde gösterilsin.</p>
            <div class="checkout-progress" aria-label="Sipariş adımları">
                <div class="current"><b>1</b><span><strong>Teslimat</strong><small>İletişim ve adres</small></span></div>
                <i class="bi bi-chevron-right"></i>
                <div><b>2</b><span><strong>Havale/EFT</strong><small>IBAN ve ödeme</small></span></div>
                <i class="bi bi-chevron-right"></i>
                <div><b>3</b><span><strong>Dekont</strong><small>Hızlı onay</small></span></div>
            </div>
        </div>

        <div class="checkout-layout">
            <form class="form-card" action="create-order.php" method="post" data-loading>
                <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                <input type="hidden" name="quantity" value="<?= (int) $quantity ?>">
                <div class="honeypot" aria-hidden="true"><label>Web sitesi<input type="text" name="website" tabindex="-1" autocomplete="off"></label></div>

                <div class="form-card-top">
                    <div><span>GÜVENLİ SİPARİŞ</span><strong>Teslimat bilgileri</strong><small>Zorunlu alanlar yıldızla işaretlenmiştir.</small></div>
                    <i class="bi bi-fingerprint"></i>
                </div>

                <?php if ($errors): ?>
                    <div class="form-alert" role="alert">
                        <strong>Lütfen işaretli alanları kontrol edin.</strong>
                        <?php if (isset($errors['form'])): ?><div><?= e($errors['form']) ?></div><?php endif; ?>
                    </div>
                <?php endif; ?>

                <section class="form-section">
                    <h2><i class="bi bi-person"></i> İletişim Bilgileri</h2>
                    <div class="field-grid">
                        <div class="field <?= isset($errors['first_name']) ? 'has-error' : '' ?>">
                            <label for="first_name">Ad <span class="required">*</span></label>
                            <input id="first_name" name="first_name" type="text" value="<?= old_value('first_name') ?>" autocomplete="given-name" placeholder="Adınız" required maxlength="70">
                            <?= field_error('first_name') ?>
                        </div>
                        <div class="field <?= isset($errors['last_name']) ? 'has-error' : '' ?>">
                            <label for="last_name">Soyad <span class="required">*</span></label>
                            <input id="last_name" name="last_name" type="text" value="<?= old_value('last_name') ?>" autocomplete="family-name" placeholder="Soyadınız" required maxlength="70">
                            <?= field_error('last_name') ?>
                        </div>
                        <div class="field <?= isset($errors['email']) ? 'has-error' : '' ?>">
                            <label for="email">E-posta <span class="required">*</span></label>
                            <input id="email" name="email" type="email" value="<?= old_value('email') ?>" autocomplete="email" inputmode="email" placeholder="ornek@email.com" required maxlength="120">
                            <?= field_error('email') ?>
                        </div>
                        <div class="field <?= isset($errors['phone']) ? 'has-error' : '' ?>">
                            <label for="phone">Telefon Numarası <span class="required">*</span></label>
                            <input id="phone" name="phone" type="tel" value="<?= old_value('phone') ?>" autocomplete="tel" inputmode="tel" placeholder="05xx xxx xx xx" required maxlength="20">
                            <?= field_error('phone') ?>
                        </div>
                    </div>
                </section>

                <section class="form-section">
                    <h2><i class="bi bi-geo-alt"></i> Teslimat Adresi</h2>
                    <div class="field-grid" id="address-picker" data-old-district="<?= old_value('district') ?>" data-old-neighborhood="<?= old_value('neighborhood') ?>">
                        <div class="field <?= isset($errors['province']) ? 'has-error' : '' ?>">
                            <label for="province">İl <span class="required">*</span></label>
                            <select id="province" name="province" autocomplete="address-level1" required>
                                <option value="">İl seçin</option>
                                <?php foreach (turkey_provinces() as $id => $province): ?>
                                    <option value="<?= e($province) ?>" data-id="<?= (int) $id ?>" <?= (($old['province'] ?? '') === $province) ? 'selected' : '' ?>><?= e($province) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <?= field_error('province') ?>
                        </div>
                        <div class="field <?= isset($errors['district']) ? 'has-error' : '' ?>">
                            <label for="district">İlçe <span class="required">*</span></label>
                            <select id="district" name="district" autocomplete="address-level2" required disabled>
                                <option value="">Önce il seçin</option>
                            </select>
                            <div class="manual-field" id="district-manual-wrap" hidden>
                                <input name="district_manual" type="text" value="<?= old_value('district_manual') ?>" placeholder="İlçenizi yazın" maxlength="80">
                            </div>
                            <?= field_error('district') ?>
                        </div>
                        <div class="field full <?= isset($errors['neighborhood']) ? 'has-error' : '' ?>">
                            <label for="neighborhood">Mahalle <span class="required">*</span></label>
                            <select id="neighborhood" name="neighborhood" autocomplete="address-level3" required disabled>
                                <option value="">Önce ilçe seçin</option>
                            </select>
                            <div class="manual-field" id="neighborhood-manual-wrap" hidden>
                                <input name="neighborhood_manual" type="text" value="<?= old_value('neighborhood_manual') ?>" placeholder="Mahallenizi yazın" maxlength="100">
                            </div>
                            <?= field_error('neighborhood') ?>
                            <span class="selection-note"><i class="bi bi-info-circle"></i> Liste yüklenemezse bilgileri elle yazabilirsiniz.</span>
                        </div>
                        <div class="field full <?= isset($errors['address']) ? 'has-error' : '' ?>">
                            <label for="address">Açık Adres <span class="required">*</span></label>
                            <textarea id="address" name="address" autocomplete="street-address" placeholder="Cadde, sokak, bina ve daire numarası" required maxlength="500"><?= old_value('address') ?></textarea>
                            <?= field_error('address') ?>
                        </div>
                        <div class="field">
                            <label for="postal_code">Posta Kodu</label>
                            <input id="postal_code" name="postal_code" type="text" value="<?= old_value('postal_code') ?>" autocomplete="postal-code" inputmode="numeric" placeholder="34000" maxlength="10">
                        </div>
                        <div class="field">
                            <label for="note">Sipariş Notu</label>
                            <input id="note" name="note" type="text" value="<?= old_value('note') ?>" placeholder="Varsa teslimat notunuz" maxlength="250">
                        </div>
                    </div>
                </section>

                <section class="form-section">
                    <h2><i class="bi bi-file-earmark-check"></i> Onaylar</h2>
                    <div class="checkbox-list">
                        <label class="check-row <?= isset($errors['contract_accepted']) ? 'has-error' : '' ?>">
                            <input type="checkbox" name="contract_accepted" value="1" <?= !empty($old['contract_accepted']) ? 'checked' : '' ?> required>
                            <span><a href="legal.php?doc=preinfo" target="_blank">Ön Bilgilendirme Formu</a> ile <a href="legal.php?doc=distance" target="_blank">Mesafeli Satış Sözleşmesi</a>’ni okudum ve kabul ediyorum. <span class="required">*</span><?= field_error('contract_accepted') ?></span>
                        </label>
                        <label class="check-row <?= isset($errors['privacy_acknowledged']) ? 'has-error' : '' ?>">
                            <input type="checkbox" name="privacy_acknowledged" value="1" <?= !empty($old['privacy_acknowledged']) ? 'checked' : '' ?> required>
                            <span><a href="legal.php?doc=privacy" target="_blank">KVKK Aydınlatma Metni</a>’ni okuduğumu onaylıyorum. <span class="required">*</span><?= field_error('privacy_acknowledged') ?></span>
                        </label>
                        <label class="check-row">
                            <input type="checkbox" name="commercial_consent" value="1" <?= !empty($old['commercial_consent']) ? 'checked' : '' ?>>
                            <span>Kampanya ve fırsatlardan elektronik ileti yoluyla haberdar olmak istiyorum. (İsteğe bağlı)</span>
                        </label>
                    </div>
                    <button class="submit-order" type="submit">SİPARİŞİ OLUŞTUR — ÖDEME YÜKÜMLÜLÜĞÜ DOĞURUR <i class="bi bi-arrow-right"></i></button>
                </section>
            </form>

            <aside class="summary-card">
                <div class="summary-head-row">
                    <div><span>SEÇİMİNİZ</span><h2>Sipariş Özeti</h2></div>
                    <i class="bi bi-bag-check"></i>
                </div>
                <div class="summary-status"><span></span><?= e(cfg('shipping.badge')) ?></div>
                <div class="summary-product">
                    <img src="<?= e(cfg('product.images.0')) ?>" alt="<?= e(cfg('product.name')) ?>" width="140" height="140">
                    <div>
                        <strong><?= e(cfg('product.name')) ?></strong>
                        <span><?= (int) $quantity ?> adet paket</span>
                        <span class="summary-product-price"><?= money($package['price']) ?></span>
                    </div>
                </div>
                <div class="summary-lines">
                    <div class="summary-line"><span>Ara toplam</span><strong><?= money($package['price']) ?></strong></div>
                    <div class="summary-line"><span><?= e(cfg('shipping.company')) ?></span><span class="free">Ücretsiz</span></div>
                </div>
                <div class="summary-total summary-total-vip"><span><small>ÖDENECEK TUTAR</small>Toplam</span><strong><?= money($package['price']) ?></strong></div>
                <div class="summary-trust">
                    <span><i class="bi bi-lightning-charge-fill"></i> <?= e(cfg('shipping.badge')) ?></span>
                    <span><i class="bi bi-truck"></i> <?= e(cfg('shipping.company')) ?> ile ücretsiz gönderim</span>
                    <span><i class="bi bi-bank"></i> Güvenli Havale/EFT ödeme</span>
                </div>
                <div class="summary-support"><i class="bi bi-headset"></i><div><strong>Sipariş desteği</strong><span><?= e(cfg('site.support_phone')) ?></span></div></div>
            </aside>
        </div>
    </div>
</section>
<script src="assets/js/address-picker.js?v=1.0.0" defer></script>
<?php require __DIR__ . '/app/footer.php'; ?>
