<?php
session_start();
require_once '../includes/db.php';
require_once '../includes/functions.php';

// Proje ana dizinini belirle
$kok_dizin = "/magaza/";

// Oturum Güvenliği
if (!isset($_SESSION['user_id'])) {
    header("Location: " . $kok_dizin . "giris.php");
    exit;
}

$user_id = (int)$_SESSION['user_id'];

// URL'den ID Kontrolü
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: siparisler.php");
    exit;
}
$siparis_id = (int)$_GET['id'];

// 1. GÜVENLİK (IDOR) KONTROLÜ: Sipariş gerçekten bu kullanıcıya mı ait?
$stmt = $db->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ?");
$stmt->execute([$siparis_id, $user_id]);
$siparis = $stmt->fetch();

if (!$siparis) {
    header("Location: siparisler.php");
    exit;
}

// 2. MEVCUT TALEPLERİ KONTROL ET (İptal veya İade isteği var mı?)
$talep_stmt = $db->prepare("SELECT * FROM order_returns WHERE order_id = ? ORDER BY id DESC LIMIT 1");
$talep_stmt->execute([$siparis_id]);
$mevcut_talep = $talep_stmt->fetch();

// 3. Müşteri Bilgisi (Sol Menü İçin)
$user_stmt = $db->prepare("SELECT name, surname, email FROM users WHERE id = ?");
$user_stmt->execute([$user_id]);
$musteri = $user_stmt->fetch();

// 4. Sipariş İçeriği (GÜNCELLEME: exam_publication_date SÜTUNU EKLENDİ)
try {
    $items_stmt = $db->prepare("
        SELECT oi.*, p.name, p.slug, p.type, p.exam_publication_date, b.logo as brand_logo, b.default_cover,
        COALESCE(
            (SELECT image_path FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1),
            b.default_cover,
            'assets/img/no-image.jpg'
        ) as main_image
        FROM order_items oi
        JOIN products p ON oi.product_id = p.id
        LEFT JOIN brands b ON p.brand_id = b.id
        WHERE oi.order_id = ?
    ");
    $items_stmt->execute([$siparis_id]);
    $urunler = $items_stmt->fetchAll();
} catch (PDOException $e) {
    die("<div class='alert alert-danger m-5 p-4 text-center fw-bold shadow'><h4>Güncelleme Gerekiyor</h4>Lütfen veritabanı güncelleme işlemini (ALTER TABLE order_items) tamamlayın.</div>");
}

// Ürünleri Standart ve Paket olarak ikiye ayıralım
$standart_urunler = [];
$paket_urunler = [];

foreach($urunler as $urun) {
    if($urun['type'] == 'exam_package') {
        $paket_urunler[] = $urun;
    } else if($urun['type'] != 'digital') { 
        $standart_urunler[] = $urun;
    }
}

// 5. Özel Paket (Kutu) Gönderim Takvimi (MÜŞTERİ İÇİN)
$kutular = [];
$toplam_kutu = 0;
$kargolanan_kutu = 0;

if(count($paket_urunler) > 0) {
    $del_stmt = $db->prepare("
        SELECT 
            od.delivery_sequence, od.planned_date, od.status, od.shipping_company, od.tracking_code,
            pkg.name as package_name,
            GROUP_CONCAT(p.name SEPARATOR '<br>• ') as exam_list
        FROM order_deliveries od
        JOIN products pkg ON od.package_id = pkg.id
        JOIN products p ON od.exam_id = p.id
        WHERE od.order_id = ?
        GROUP BY od.delivery_sequence, od.planned_date, od.status, od.shipping_company, od.tracking_code, pkg.name
        ORDER BY od.delivery_sequence ASC
    ");
    $del_stmt->execute([$siparis_id]);
    $kutular = $del_stmt->fetchAll(PDO::FETCH_ASSOC);

    $toplam_kutu = count($kutular);
    foreach($kutular as $k) {
        if(in_array($k['status'], ['shipped', 'delivered'])) $kargolanan_kutu++;
    }
}
$ilerleme_yuzdesi = ($toplam_kutu > 0) ? round(($kargolanan_kutu / $toplam_kutu) * 100) : 0;

// 6. Adres Bilgileri
$teslimat = null;
if ($siparis['shipping_address_id']) {
    $addr = $db->prepare("SELECT * FROM user_addresses WHERE id = ?");
    $addr->execute([$siparis['shipping_address_id']]);
    $teslimat = $addr->fetch();
}
$fatura = null;
if ($siparis['billing_address_id']) {
    $addr = $db->prepare("SELECT * FROM user_addresses WHERE id = ?");
    $addr->execute([$siparis['billing_address_id']]);
    $fatura = $addr->fetch();
}

// 7. Ödeme Bilgileri
$pay_stmt = $db->prepare("SELECT payment_method, status, receipt_file_path FROM payments WHERE order_id = ?");
$pay_stmt->execute([$siparis_id]);
$odeme = $pay_stmt->fetch();

/**
 * GÜNCELLEME: Ürün Bazlı Kargo Tarihi Hesaplama Fonksiyonu
 */
function getItemKargoTarihi($urun) {
    if ($urun['type'] == 'single_exam' && !empty($urun['exam_publication_date'])) {
        $bugun = new DateTime('midnight');
        $d = DateTime::createFromFormat('d.m.Y', $urun['exam_publication_date']);
        if ($d) {
            $d->setTime(0, 0, 0);
            if ($d < $bugun) {
                return '<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 px-2 py-1"><i class="bi bi-box-seam me-1"></i>Hemen Kargoya Hazır</span>';
            } else {
                $d->modify('next tuesday');
                return '<span class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 px-2 py-1"><i class="bi bi-calendar-event me-1"></i>Planlı Kargo: ' . $d->format('d.m.Y') . ' (Salı)</span>';
            }
        }
    }
    return '<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 px-2 py-1"><i class="bi bi-box-seam me-1"></i>Hemen Kargoya Hazır</span>';
}

require_once '../header.php';
?>

<style>
    @keyframes pulse-red {
        0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.7); }
        70% { transform: scale(1.02); box-shadow: 0 0 0 10px rgba(220, 53, 69, 0); }
        100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0); }
    }
    .pulse-warning { animation: pulse-red 2s infinite; }
    .box-card { border-left: 4px solid #0d6efd; transition: 0.3s; }
    .box-card:hover { box-shadow: 0 10px 15px rgba(0,0,0,0.1); }
    .std-card { border-left: 4px solid #198754; transition: 0.3s; }
    .std-card:hover { box-shadow: 0 10px 15px rgba(0,0,0,0.1); }
</style>

<main class="container py-5 text-dark">
    <div class="row">
        <div class="col-lg-3 mb-4">
            <?php include 'sidebar.php'; ?>
        </div>

        <div class="col-lg-9">
            
            <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
                <h2 class="h4 fw-bold mb-0">
                    <a href="siparisler.php" class="btn btn-sm btn-outline-secondary me-2"><i class="bi bi-arrow-left"></i></a>
                    Sipariş No: <span class="text-primary">#<?= htmlspecialchars($siparis['order_number']) ?></span>
                </h2>
                
                <div class="d-flex gap-2">
                    <?php if ($odeme['payment_method'] == 'bank_transfer' && $siparis['status'] == 'pending'): ?>
                        <?php if (empty($odeme['receipt_file_path'])): ?>
                            <a href="kullanici/odeme-bildirimi.php?siparis_no=<?= htmlspecialchars($siparis['order_number']) ?>" class="btn btn-warning fw-bold rounded-pill px-4 shadow-sm pulse-warning text-dark">
                                <i class="bi bi-upload me-1"></i> Dekont İlet
                            </a>
                        <?php else: ?>
                            <div class="btn-group shadow-sm rounded-pill">
                                <span class="btn btn-success fw-bold px-4" style="cursor: default;">
                                    <i class="bi bi-check2-all me-1"></i> İnceleniyor
                                </span>
                                <a href="kullanici/odeme-bildirimi.php?siparis_no=<?= htmlspecialchars($siparis['order_number']) ?>" class="btn btn-outline-success fw-bold px-3" title="Yanlış dekont yüklediyseniz değiştirebilirsiniz">
                                    <i class="bi bi-arrow-repeat"></i>
                                </a>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>

                    <?php if (!$mevcut_talep && !in_array($siparis['status'], ['cancelled', 'delivered'])): ?>
                        <?php if (in_array($siparis['status'], ['pending', 'processing'])): ?>
                            <button class="btn btn-outline-danger fw-bold rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#talepModal" onclick="setTalepType('cancellation')">
                                <i class="bi bi-x-circle me-1"></i> Siparişi İptal Et
                            </button>
                        <?php elseif ($siparis['status'] == 'shipped'): ?>
                            <button class="btn btn-outline-primary fw-bold rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#talepModal" onclick="setTalepType('return')">
                                <i class="bi bi-arrow-counterclockwise me-1"></i> İade Talebi Oluştur
                            </button>
                        <?php endif; ?>
                    <?php endif; ?>

                    <?php if($siparis['invoice_path']): ?>
                        <a href="<?= $kok_dizin ?><?= htmlspecialchars($siparis['invoice_path']) ?>" target="_blank" class="btn btn-danger fw-bold rounded-pill shadow-sm">
                            <i class="bi bi-file-earmark-pdf"></i> E-Faturayı İndir
                        </a>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($mevcut_talep): ?>
                <div class="alert alert-<?= ($mevcut_talep['status'] == 'rejected') ? 'secondary' : 'info' ?> shadow-sm border-0 rounded-4 p-3 mb-4">
                    <div class="d-flex align-items-center">
                        <i class="bi bi-info-circle-fill fs-3 me-3 text-primary"></i>
                        <div>
                            <div class="fw-bold text-uppercase small" style="letter-spacing: 1px;">
                                <?= $mevcut_talep['request_type'] == 'cancellation' ? 'İptal Talebiniz' : 'İade Talebiniz' ?>
                            </div>
                            <div class="fw-bold fs-6">
                                Durum: 
                                <?php 
                                    if($mevcut_talep['status'] == 'pending') echo '<span class="text-primary">İnceleniyor</span>';
                                    elseif($mevcut_talep['status'] == 'approved' && $mevcut_talep['request_type'] == 'return') echo '<span class="text-success">Onaylandı (Kargo Kodunuz: '.$mevcut_talep['return_tracking_code'].')</span>';
                                    elseif($mevcut_talep['status'] == 'approved') echo '<span class="text-success">Onaylandı, İade Sürecinde</span>';
                                    elseif($mevcut_talep['status'] == 'rejected') echo '<span class="text-danger">Reddedildi</span>';
                                    elseif($mevcut_talep['status'] == 'completed') echo '<span class="text-success">İade Tamamlandı</span>';
                                ?>
                            </div>
                            <?php if($mevcut_talep['admin_note']): ?>
                                <div class="small mt-1 text-muted"><b>Mağaza Notu:</b> <?= htmlspecialchars($mevcut_talep['admin_note']) ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <div class="card shadow-sm border-0 bg-light mb-4 rounded-4">
                <div class="card-body p-4">
                    <div class="row text-center text-md-start align-items-center">
                        <div class="col-md-3 border-end mb-3 mb-md-0">
                            <span class="d-block text-muted small fw-bold text-uppercase">Sipariş Tarihi</span>
                            <span class="fw-bold text-dark"><?= date('d.m.Y - H:i', strtotime($siparis['created_at'])) ?></span>
                        </div>
                        <div class="col-md-3 border-end mb-3 mb-md-0">
                            <span class="d-block text-muted small fw-bold text-uppercase">Tutar</span>
                            <span class="fw-bold text-danger fs-5"><?= number_format($siparis['total_amount'], 2, ',', '.') ?> ₺</span>
                        </div>
                        <div class="col-md-3 border-end mb-3 mb-md-0">
                            <span class="d-block text-muted small fw-bold text-uppercase mb-1">Ödeme</span>
                            <span class="badge bg-white text-dark border"><?= $odeme['payment_method'] == 'credit_card' ? 'Kredi Kartı' : 'Havale/EFT' ?></span>
                            <?php if(!empty($odeme['receipt_file_path'])): ?>
                                <a href="<?= $kok_dizin ?><?= htmlspecialchars($odeme['receipt_file_path']) ?>" target="_blank" class="d-block mt-2 small text-primary text-decoration-none fw-bold">
                                    <i class="bi bi-file-earmark-check"></i> Dekontu Gör
                                </a>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-3">
                            <span class="d-block text-muted small fw-bold text-uppercase mb-1">Genel Durum</span>
                            <?php if($siparis['status'] == 'delivered'): ?>
                                <span class="badge bg-success fs-6 rounded-pill"><i class="bi bi-check2-all"></i> Teslim Edildi</span>
                            <?php elseif($siparis['status'] == 'shipped'): ?>
                                <span class="badge bg-primary fs-6 rounded-pill"><i class="bi bi-truck"></i> Tümü Kargolandı</span>
                            <?php elseif($siparis['status'] == 'pending'): ?>
                                <span class="badge bg-warning text-dark fs-6 rounded-pill">Onay Bekliyor</span>
                            <?php elseif($siparis['status'] == 'cancelled'): ?>
                                <span class="badge bg-danger fs-6 rounded-pill">İptal Edildi</span>
                            <?php else: ?>
                                <span class="badge bg-info text-dark fs-6 rounded-pill">Hazırlanıyor / Parçalı</span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <?php if(count($standart_urunler) > 0): ?>
            <div class="card shadow-sm border-0 mb-4 rounded-4 overflow-hidden">
                <div class="card-header bg-success text-white py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-bold text-uppercase"><i class="bi bi-box-seam me-2"></i>Standart Ürünlerinizin Kargo Durumu</h6>
                    <span class="badge bg-white text-success rounded-pill"><?= count($standart_urunler) ?> Ürün</span>
                </div>
                <div class="card-body p-4 bg-light">
                    <div class="row row-cols-1 row-cols-md-2 g-3">
                        <?php foreach($standart_urunler as $s_urun): 
                            $s_status = isset($s_urun['shipping_status']) ? $s_urun['shipping_status'] : 'pending';
                            $s_company = isset($s_urun['shipping_company']) ? $s_urun['shipping_company'] : '';
                            $s_tracking = isset($s_urun['tracking_number']) ? $s_urun['tracking_number'] : '';
                        ?>
                        <div class="col">
                            <div class="card std-card shadow-sm border-0 h-100">
                                <div class="card-header bg-white py-2 d-flex justify-content-between align-items-center">
                                    <div class="fw-bold text-dark text-truncate" title="<?= htmlspecialchars($s_urun['name']) ?>" style="max-width: 70%;">
                                        <i class="bi bi-check2-square me-1 text-success"></i> <?= htmlspecialchars($s_urun['name']) ?>
                                    </div>
                                    <div>
                                        <?php if($s_status == 'shipped'): ?>
                                            <span class="badge bg-success"><i class="bi bi-truck"></i> Kargolandı</span>
                                        <?php else: ?>
                                            <span class="badge bg-warning text-dark"><i class="bi bi-hourglass-split"></i> Bekliyor</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php if($s_status == 'shipped'): ?>
                                        <div class="d-flex justify-content-between align-items-center mt-2">
                                            <div>
                                                <small class="text-success fw-bold d-block" style="font-size: 0.75rem;"><?= htmlspecialchars($s_company) ?> Takip Kodu</small>
                                                <span class="small fw-bold text-dark user-select-all"><?= htmlspecialchars($s_tracking) ?></span>
                                            </div>
                                            <a href="<?= getKargoTakipLink($s_company, $s_tracking) ?>" target="_blank" class="btn btn-sm btn-success py-1 px-3 rounded-pill fw-bold" style="font-size:0.75rem;">Kargo Takip Et</a>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center mt-2 pt-1">
                                            <i class="bi bi-box-seam fs-3 d-block mb-1 text-secondary opacity-50"></i>
                                            <div class="small text-muted mb-2">Paketiniz hazırlanıyor...</div>
                                            <?= getItemKargoTarihi($s_urun) ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>


            <?php if($toplam_kutu > 0): ?>
            <div class="card shadow-sm border-primary border-opacity-25 border-2 mb-4 rounded-4 overflow-hidden">
                <div class="card-header bg-primary bg-opacity-10 py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold text-primary small text-uppercase"><i class="bi bi-calendar3 me-2"></i> Özel Deneme Gönderim Takviminiz</h5>
                    <span class="badge bg-primary rounded-pill"><?= $kargolanan_kutu ?> / <?= $toplam_kutu ?> Kutu Kargolandı</span>
                </div>
                <div class="card-body p-4">
                    <div class="progress mb-4" style="height: 10px; border-radius: 10px;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated bg-primary" style="width: <?= $ilerleme_yuzdesi ?>%"></div>
                    </div>
                    <div class="row row-cols-1 row-cols-md-2 g-3">
                        <?php foreach($kutular as $kutu): 
                            $kargolandi = in_array($kutu['status'], ['shipped', 'delivered']);
                        ?>
                            <div class="col">
                                <div class="box-card p-3 border rounded-4 <?= $kargolandi ? 'bg-success bg-opacity-10 border-success' : 'bg-white' ?>">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span class="fw-bold small text-dark"><i class="bi bi-box-seam me-1"></i> <?= $kutu['delivery_sequence'] ?>. Gönderim Kutusu</span>
                                        <span class="badge <?= $kargolandi ? 'bg-success' : 'bg-secondary' ?> rounded-pill small">
                                            <?= $kargolandi ? 'Yolda' : 'Bekliyor' ?>
                                        </span>
                                    </div>
                                    
                                    <div class="small text-secondary mb-2 lh-sm border-bottom pb-2">
                                        <span class="d-block fw-bold text-dark mb-1" style="font-size: 0.7rem;">KUTU İÇERİĞİ:</span>
                                        • <?= $kutu['exam_list'] ?>
                                    </div>

                                    <?php if($kargolandi): ?>
                                        <div class="d-flex justify-content-between align-items-center mt-2 pt-1">
                                            <div>
                                                <small class="text-success fw-bold d-block" style="font-size: 0.65rem;"><?= htmlspecialchars($kutu['shipping_company']) ?> Takip Kodu</small>
                                                <span class="small fw-bold text-dark user-select-all"><?= htmlspecialchars($kutu['tracking_code']) ?></span>
                                            </div>
                                            <a href="<?= getKargoTakipLink($kutu['shipping_company'], $kutu['tracking_code']) ?>" target="_blank" class="btn btn-sm btn-success py-1 px-3 rounded-pill fw-bold" style="font-size:0.75rem;">Kargo Takip Et</a>
                                        </div>
                                    <?php else: ?>
                                        <div class="small text-muted mt-2 pt-1">
                                            <i class="bi bi-clock text-warning me-1"></i> Planlanan Kargo Tarihi:<br>
                                            <strong class="text-dark"><?= $kutu['planned_date'] ? date('d.m.Y', strtotime($kutu['planned_date'])) : 'Bekliyor' ?></strong>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div class="card shadow-sm border-0 mb-4 rounded-4 overflow-hidden">
                <div class="card-header bg-white py-3 border-bottom"><h6 class="mb-0 fw-bold"><i class="bi bi-bag-check me-2"></i> Sipariş İçeriği</h6></div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th class="ps-4 py-3">Ürün Adı</th>
                                    <th class="text-center">Miktar</th>
                                    <th class="text-end">Birim Fiyat</th>
                                    <th class="text-end pe-4">Toplam</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($urunler as $urun): 
                                    $gorsel = $urun['main_image'];
                                    if ($gorsel == 'assets/img/no-image.jpg' && !empty($urun['brand_logo'])) {
                                        $gorsel = $urun['brand_logo']; 
                                    }
                                ?>
                                <tr>
                                    <td class="ps-4 fw-bold text-primary">
                                        <div class="d-flex align-items-center">
                                            <img src="<?= $kok_dizin ?><?= htmlspecialchars($gorsel) ?>" class="img-fluid rounded border bg-light me-3" style="width: 40px; height: 50px; object-fit: contain;">
                                            <div>
                                                <a href="<?= $kok_dizin ?>urun/<?= $urun['slug'] ?>" target="_blank" class="text-dark text-decoration-none"><?= htmlspecialchars($urun['name']) ?></a>
                                                <?php if($urun['type'] == 'exam_package'): ?>
                                                    <br><span class="badge bg-warning text-dark" style="font-size:0.6rem;"><i class="bi bi-calendar3 me-1"></i>Aşamalı Gönderim Paketi</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="text-center"><span class="badge bg-secondary px-3"><?= $urun['quantity'] ?> Adet</span></td>
                                    <td class="text-end text-muted small"><?= formatPrice($urun['unit_price']) ?></td>
                                    <td class="text-end pe-4 fw-bold text-dark"><?= formatPrice($urun['unit_price'] * $urun['quantity']) ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                            <tfoot class="table-light border-top">
                                <?php if($siparis['shipping_amount'] > 0): ?>
                                <tr><td colspan="3" class="text-end text-muted small py-2">Kargo Ücreti:</td><td class="text-end pe-4 text-muted small py-2">+ <?= formatPrice($siparis['shipping_amount']) ?></td></tr>
                                <?php else: ?>
                                <tr><td colspan="3" class="text-end text-muted small py-2">Kargo Ücreti:</td><td class="text-end pe-4 text-success fw-bold small py-2">ÜCRETSİZ</td></tr>
                                <?php endif; ?>
                                <tr>
                                    <td colspan="3" class="text-end fw-bold py-3 text-uppercase">Ödenen Toplam:</td>
                                    <td class="text-end pe-4 fw-bold text-success fs-5 py-3"><?= formatPrice($siparis['total_amount']) ?></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>

            <div class="row g-4">
                <div class="col-md-6">
                    <div class="card shadow-sm border-0 rounded-4 h-100">
                        <div class="card-header bg-white py-3"><h6 class="mb-0 fw-bold">Fatura Adresi</h6></div>
                        <div class="card-body bg-light small">
                            <?php if($fatura): ?>
                                <p class="mb-1 fw-bold text-dark"><?= htmlspecialchars($fatura['title']) ?></p>
                                <p class="mb-0 text-muted"><?= nl2br(htmlspecialchars($fatura['full_address'])) ?><br><?= $fatura['district'] ?> / <?= $fatura['city'] ?></p>
                            <?php else: ?>
                                <p class="text-muted fst-italic">Bireysel fatura oluşturulacaktır.</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card shadow-sm border-0 rounded-4 h-100">
                        <div class="card-header bg-white py-3"><h6 class="mb-0 fw-bold">Teslimat Adresi</h6></div>
                        <div class="card-body bg-light small">
                            <?php if($teslimat): ?>
                                <p class="mb-1 fw-bold text-dark"><?= htmlspecialchars($teslimat['title']) ?></p>
                                <p class="mb-0 text-muted"><?= nl2br(htmlspecialchars($teslimat['full_address'])) ?><br><?= $teslimat['district'] ?> / <?= $teslimat['city'] ?></p>
                            <?php else: ?>
                                <p class="text-muted fst-italic">Fiziksel gönderimi olmayan sipariş.</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div> 

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

<div class="modal fade" id="talepModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg rounded-4">
            <form action="talep-ilet.php" method="POST">
                <div class="modal-header bg-dark text-white">
                    <h5 class="modal-title fw-bold" id="modalTitle">Talep Formu</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <input type="hidden" name="order_id" value="<?= $siparis_id ?>">
                    <input type="hidden" name="request_type" id="modalRequestType">
                    
                    <div class="mb-3">
                        <label class="form-label small fw-bold text-muted">NEDENİNİ SEÇİN</label>
                        <select name="reason" class="form-select border-2 shadow-none" required>
                            <option value="">Lütfen seçiniz...</option>
                            <option value="Vazgeçtim / İhtiyacım kalmadı">Vazgeçtim / İhtiyacım kalmadı</option>
                            <option value="Yanlış ürün satın aldım">Yanlış ürün satın aldım</option>
                            <option value="Teslimat süresi çok uzun">Teslimat süresi çok uzun</option>
                            <option value="Farklı bir paket alacağım">Farklı bir paket alacağım</option>
                            <option value="Diğer">Diğer (Not kısmında belirtin)</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-bold text-muted">EK NOTUNUZ (OPSİYONEL)</label>
                        <textarea name="customer_note" class="form-control border-2 shadow-none" rows="3" placeholder="Mağazaya iletmek istediğiniz detayları yazın..."></textarea>
                    </div>
                    
                    <div class="alert alert-warning border-0 small py-2">
                        <i class="bi bi-info-circle me-1"></i> Talebiniz onaylandıktan sonra para iadesi bankanıza iletilecektir.
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="submit" class="btn btn-dark fw-bold rounded-pill px-4">Talebi Gönder</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function setTalepType(type) {
    document.getElementById('modalRequestType').value = type;
    document.getElementById('modalTitle').innerText = (type == 'cancellation') ? 'Siparişi İptal Et' : 'İade Talebi Oluştur';
}
</script>

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