<?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'];

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

// Müşterinin TÜM Siparişlerini Çek 
// GÜNCELLEME: 'receipt_file_path' sorguya eklendi (Dekont kontrolü için)
$siparisler_stmt = $db->prepare("
    SELECT o.id, o.order_number, o.total_amount, o.status, o.created_at, o.tracking_code, o.is_cancel_requested,
    (SELECT payment_method FROM payments WHERE order_id = o.id LIMIT 1) as payment_method,
    (SELECT receipt_file_path FROM payments WHERE order_id = o.id LIMIT 1) as receipt_file_path,
    (SELECT status FROM order_returns WHERE order_id = o.id ORDER BY id DESC LIMIT 1) as talep_durumu,
    (SELECT request_type FROM order_returns WHERE order_id = o.id ORDER BY id DESC LIMIT 1) as talep_tipi,
    (SELECT COUNT(id) FROM order_deliveries WHERE order_id = o.id) as toplam_kutu_sayisi,
    (SELECT COUNT(id) FROM order_deliveries WHERE order_id = o.id AND status = 'shipped') as kargolanan_kutu_sayisi,
    (SELECT planned_date FROM order_deliveries WHERE order_id = o.id AND status = 'pending' ORDER BY planned_date ASC LIMIT 1) as siradaki_kargo_tarihi,
    (SELECT GROUP_CONCAT(p.exam_publication_date) FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.order_id = o.id AND p.type = 'single_exam') as exam_dates
    FROM orders o
    WHERE o.user_id = ? 
    ORDER BY o.id DESC
");
$siparisler_stmt->execute([$user_id]);
$siparisler = $siparisler_stmt->fetchAll();

/**
 * Müşteri için özelleştirilmiş Durum Çevirici
 */
function getMusteriSiparisDurumuGelismiş($siparis) {
    if ($siparis['is_cancel_requested'] == 1 && $siparis['status'] != 'cancelled') {
        return '<span class="badge bg-danger bg-opacity-10 text-danger px-3 py-2 rounded-pill border border-danger border-opacity-25"><i class="bi bi-x-circle-fill me-1"></i> İptal Talebi İnceleniyor</span>';
    }

    if ($siparis['talep_tipi'] == 'return' && $siparis['talep_durumu'] != 'completed' && $siparis['talep_durumu'] != 'rejected') {
        return '<span class="badge bg-info bg-opacity-10 text-info px-3 py-2 rounded-pill border border-info border-opacity-25"><i class="bi bi-arrow-counterclockwise me-1"></i> İade Sürecinde</span>';
    }

    switch ($siparis['status']) {
        case 'pending': return '<span class="badge bg-warning text-dark px-3 py-2 rounded-pill"><i class="bi bi-hourglass-split me-1"></i> Onay Bekliyor</span>';
        case 'processing': return '<span class="badge bg-info text-dark px-3 py-2 rounded-pill"><i class="bi bi-box-seam me-1"></i> Hazırlanıyor / Parçalı Gönderim</span>';
        case 'shipped': return '<span class="badge bg-primary px-3 py-2 rounded-pill"><i class="bi bi-truck me-1"></i> Tümü Kargolandı</span>';
        case 'delivered': return '<span class="badge bg-success px-3 py-2 rounded-pill"><i class="bi bi-check-circle-fill me-1"></i> Teslim Edildi</span>';
        case 'cancelled': return '<span class="badge bg-secondary px-3 py-2 rounded-pill"><i class="bi bi-x-circle me-1"></i> İptal Edildi</span>';
        default: return '<span class="badge bg-secondary px-3 py-2 rounded-pill">Bilinmiyor</span>';
    }
}

/**
 * GÜNCELLEME: Siparişteki Denemelerin Kargo Tarihini Hesaplayan Akıllı Motor (Salı Günü Formatı)
 */
function getKargoTarihiRozeti($siparis) {
    if (in_array($siparis['status'], ['shipped', 'delivered', 'cancelled'])) {
        return '';
    }

    // 1. Abonelik veya Hazır Paket İse (order_deliveries'den çeker)
    if ($siparis['toplam_kutu_sayisi'] > 0 && !empty($siparis['siradaki_kargo_tarihi'])) {
        return '<div class="mt-1 text-primary fw-bold" style="font-size: 0.65rem;"><i class="bi bi-calendar-event me-1"></i>Sıradaki Kargo: ' . date('d.m.Y', strtotime($siparis['siradaki_kargo_tarihi'])) . '</div>';
    }

    // 2. Özel Paket (Kendi Paketini Oluştur) ise (Tarihleri kontrol edip Salı gününe atar)
    if (!empty($siparis['exam_dates'])) {
        $bugun = new DateTime('midnight');
        $tarihler = explode(',', $siparis['exam_dates']);
        $gelecek_tarihler = [];
        $gecmis_var = false;

        foreach ($tarihler as $t) {
            $t = trim($t);
            if (empty($t)) {
                $gecmis_var = true; 
                continue;
            }
            
            $d = DateTime::createFromFormat('d.m.Y', $t);
            if ($d) {
                $d->setTime(0, 0, 0); 
                if ($d < $bugun) {
                    $gecmis_var = true; // Sınav tarihi geçmiş, anında kargo!
                } else {
                    // Sınav gelecekte, yayın tarihinden sonraki "İlk Salı" gününe ayarla
                    $d->modify('next tuesday');
                    $gelecek_tarihler[] = $d->getTimestamp();
                }
            } else {
                $gecmis_var = true;
            }
        }

        $html = '';
        if (!empty($gelecek_tarihler)) {
            sort($gelecek_tarihler);
            $ilk_kargo = date('d.m.Y', $gelecek_tarihler[0]); // En yakın Salı gününü alır
            
            if ($gecmis_var) {
                $html .= '<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 d-block mb-1" style="font-size: 0.65rem;"><i class="bi bi-box-seam me-1"></i>Kısmi Hazır (Hemen)</span>';
            }
            $html .= '<span class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 d-block" style="font-size: 0.65rem;"><i class="bi bi-truck me-1"></i>Planlı Kargo: ' . $ilk_kargo . ' (Salı)</span>';
            return $html;
        } elseif ($gecmis_var) {
            return '<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 d-block" style="font-size: 0.65rem;"><i class="bi bi-box-seam me-1"></i>Hemen Kargoya Hazır</span>';
        }
    }
    
    // 3. Normal kitap/kırtasiye ürünü vs. ise doğrudan "Hemen Kargoya Hazır" döndürür
    return '<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 d-block" style="font-size: 0.65rem;"><i class="bi bi-box-seam me-1"></i>Hemen Kargoya Hazır</span>';
}

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

<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">
                <h2 class="h4 fw-bold mb-0"><i class="bi bi-bag-check-fill text-primary me-2"></i>Tüm Siparişlerim</h2>
                <span class="badge bg-light text-dark border fs-6 shadow-sm"><?= count($siparisler) ?> Sipariş</span>
            </div>

            <div class="card shadow-sm border-0 rounded-4 overflow-hidden">
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light text-muted small">
                                <tr>
                                    <th class="ps-4 py-3 text-uppercase">Sipariş No</th>
                                    <th class="text-uppercase">Tarih</th>
                                    <th class="text-uppercase text-center">Kargo Özeti</th>
                                    <th class="text-uppercase text-end">Tutar</th>
                                    <th class="text-uppercase text-center">Durum</th>
                                    <th class="text-end pe-4 text-uppercase">İşlem</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(count($siparisler) > 0): ?>
                                    <?php foreach($siparisler as $siparis): ?>
                                    <tr class="<?= $siparis['is_cancel_requested'] ? 'table-light' : '' ?>">
                                        <td class="ps-4 fw-bold">
                                            <a href="siparis-detay.php?id=<?= $siparis['id'] ?>" class="text-primary text-decoration-none">
                                                #<?= htmlspecialchars($siparis['order_number']) ?>
                                            </a>
                                        </td>
                                        <td class="text-muted small fw-bold">
                                            <?= date('d.m.Y', strtotime($siparis['created_at'])) ?>
                                        </td>
                                        <td class="text-center align-middle">
                                            <?php if ($siparis['toplam_kutu_sayisi'] > 0): ?>
                                                <?php if ($siparis['toplam_kutu_sayisi'] == $siparis['kargolanan_kutu_sayisi']): ?>
                                                    <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25" style="font-size: 0.7rem;" title="Tüm kutularınız kargoya verilmiştir.">
                                                        <i class="bi bi-boxes"></i> Gönderim Tamam (<?= $siparis['toplam_kutu_sayisi'] ?>/<?= $siparis['toplam_kutu_sayisi'] ?>)
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 d-block mb-1" style="font-size: 0.7rem;" title="Bazı kutularınızın kargo zamanı bekleniyor.">
                                                        <i class="bi bi-boxes"></i> Planlı Paketler (<?= $siparis['kargolanan_kutu_sayisi'] ?>/<?= $siparis['toplam_kutu_sayisi'] ?>)
                                                    </span>
                                                    <?= getKargoTarihiRozeti($siparis) ?>
                                                <?php endif; ?>
                                            <?php elseif($siparis['status'] == 'shipped'): ?>
                                                 <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25" style="font-size: 0.7rem;"><i class="bi bi-truck"></i> Standart Kargo Yolda</span>
                                            <?php elseif($siparis['status'] == 'delivered' || $siparis['status'] == 'cancelled'): ?>
                                                 <span class="text-muted small fw-bold">-</span>
                                            <?php else: ?>
                                                <?= getKargoTarihiRozeti($siparis) ?>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end fw-bold text-success fs-6"><?= number_format($siparis['total_amount'], 2, ',', '.') ?> ₺</td>
                                        <td class="text-center"><?= getMusteriSiparisDurumuGelismiş($siparis) ?></td>
                                        <td class="text-end pe-4">
                                            <?php if($siparis['status'] == 'pending' && $siparis['payment_method'] == 'bank_transfer'): ?>
                                                <?php if(empty($siparis['receipt_file_path'])): ?>
                                                    <a href="kullanici/odeme-bildirimi.php?siparis_no=<?= $siparis['order_number'] ?>" class="btn btn-sm btn-warning shadow-sm fw-bold rounded-pill px-3 mb-2 d-block text-dark" title="Ödemeniz bekleniyor.">
                                                        <i class="bi bi-upload"></i> Dekont İlet
                                                    </a>
                                                <?php else: ?>
                                                    <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 d-block mb-2 py-2 rounded-pill w-100 text-center" style="font-size: 0.75rem;">
                                                        <i class="bi bi-check2-all"></i> İnceleniyor
                                                    </span>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                            
                                            <a href="kullanici/siparis-detay.php?id=<?= $siparis['id'] ?>" class="btn btn-sm btn-dark shadow-sm fw-bold rounded-pill px-3 d-block w-100">
                                                Detay <i class="bi bi-chevron-right ms-1"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="6" class="text-center py-5">
                                            <div class="text-muted mb-3"><i class="bi bi-cart-x" style="font-size: 3rem;"></i></div>
                                            <h5 class="fw-bold">Kayıtlı hiçbir siparişiniz bulunamadı.</h5>
                                            <p class="text-muted small">Sınav Koçu ile başarıya giden yolda ilk adımınızı atın.</p>
                                            <a href="<?= $kok_dizin ?>index.php" class="btn btn-primary mt-2 fw-bold px-4 rounded-pill shadow-sm">Alışverişe Başla</a>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

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

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