<?php
/**
 * Kullanıcı Paneli - Deneme Paketlerim ve Kutu Takvimi (İptal/İade Entegreli)
 * Konum: /magaza/kullanici/denemepaketim.php
 */

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

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

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

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

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

// 1. Kullanıcının Aldığı Deneme Paketlerini Çek (İptal/İade Durumları Dahil)
// is_cancel_requested: Kargo öncesi iptal kilidi
// talep_durumu: order_returns tablosundaki son durum
$sql = "
    SELECT 
        o.id as order_id, o.order_number, o.created_at, o.status as order_status, o.is_cancel_requested,
        pkg.id as package_id, pkg.name as package_name,
        (SELECT image_path FROM product_images WHERE product_id = pkg.id AND is_main = 1 LIMIT 1) as main_image,
        (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,
        COUNT(DISTINCT od.delivery_sequence) as total_boxes,
        COUNT(DISTINCT CASE WHEN od.status IN ('shipped', 'delivered') THEN od.delivery_sequence END) as shipped_boxes
    FROM order_deliveries od
    JOIN orders o ON od.order_id = o.id
    JOIN products pkg ON od.package_id = pkg.id
    WHERE o.user_id = ? AND o.status != 'cancelled'
    GROUP BY o.id, o.order_number, o.created_at, o.status, o.is_cancel_requested, pkg.id, pkg.name
    ORDER BY o.id DESC
";

$stmt = $db->prepare($sql);
$stmt->execute([$user_id]);
$paketlerim = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 2. Her Sipariş İçin Kutu Detaylarını Çek
$detay_stmt = $db->prepare("
    SELECT 
        od.order_id, od.delivery_sequence, od.planned_date, od.status, od.shipping_company, od.tracking_code,
        GROUP_CONCAT(p.name SEPARATOR '<br>• ') as exam_list
    FROM order_deliveries od
    JOIN products p ON od.exam_id = p.id
    WHERE od.order_id IN (SELECT id FROM orders WHERE user_id = ?)
    GROUP BY od.order_id, od.delivery_sequence, od.planned_date, od.status, od.shipping_company, od.tracking_code
    ORDER BY od.delivery_sequence ASC
");
$detay_stmt->execute([$user_id]);
$tum_detaylar = $detay_stmt->fetchAll(PDO::FETCH_ASSOC);

$kutu_detaylari = [];
foreach($tum_detaylar as $d) {
    $kutu_detaylari[$d['order_id']][] = $d;
}

$page_title = "Özel Deneme Paketlerim";
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 flex-wrap gap-2">
                <div>
                    <h2 class="h4 fw-bold mb-0 text-primary"><i class="bi bi-box2-heart-fill me-2"></i>Özel Deneme Paketlerim</h2>
                    <p class="text-muted small mt-1 mb-0">Paketlerinizin kargo takvimini ve güncel durumlarını buradan izleyebilirsiniz.</p>
                </div>
                <a href="<?= $kok_dizin ?>deneme-paketi-olustur.php" class="btn btn-primary shadow-sm fw-bold rounded-pill"><i class="bi bi-plus-lg me-1"></i> Yeni Paket</a>
            </div>

            <?php if (count($paketlerim) > 0): ?>
                
                <?php foreach ($paketlerim as $paket): 
                    $yuzde = ($paket['total_boxes'] > 0) ? round(($paket['shipped_boxes'] / $paket['total_boxes']) * 100) : 0;
                    $is_on_hold = ($paket['is_cancel_requested'] == 1);
                    $is_returning = ($paket['talep_tipi'] == 'return' && $paket['talep_durumu'] != 'completed');
                    
                    $renk = $yuzde == 100 ? "success" : "primary";
                    if ($is_on_hold) $renk = "danger";
                ?>
                    <div class="card border-0 shadow-sm rounded-4 mb-5 overflow-hidden">
                        
                        <div class="card-body p-4 bg-light border-bottom border-<?= $renk ?> border-2">
                            <div class="row align-items-center">
                                <div class="col-md-2 text-center mb-3 mb-md-0">
                                    <img src="<?= $kok_dizin ?><?= htmlspecialchars($paket['main_image'] ?: 'assets/img/no-image.jpg') ?>" class="img-fluid rounded shadow-sm border border-white border-4" style="max-height: 90px; object-fit: cover;">
                                </div>
                                <div class="col-md-6">
                                    <h5 class="fw-bold mb-1 text-dark"><?= htmlspecialchars($paket['package_name']) ?></h5>
                                    <div class="small text-muted mb-2">
                                        <i class="bi bi-hash me-1"></i> Sipariş: #<?= $paket['order_number'] ?> | <i class="bi bi-calendar-check me-1"></i> <?= date('d.m.Y', strtotime($paket['created_at'])) ?>
                                    </div>
                                    
                                    <?php if($is_on_hold): ?>
                                        <span class="badge bg-danger px-3 py-2 rounded-pill shadow-sm d-inline-block mt-1"><i class="bi bi-exclamation-octagon-fill me-1"></i> İptal Talebi İnceleniyor</span>
                                    <?php elseif($is_returning): ?>
                                        <span class="badge bg-info text-dark px-3 py-2 rounded-pill shadow-sm d-inline-block mt-1"><i class="bi bi-arrow-counterclockwise me-1"></i> İade Süreci Başlatıldı</span>
                                    <?php else: ?>
                                        <a href="<?= $kok_dizin ?>kullanici/siparis-detay.php?id=<?= $paket['order_id'] ?>" class="btn btn-sm btn-outline-dark fw-bold rounded-pill px-3 mt-1" style="font-size: 11px;">Detayları ve Faturayı Gör</a>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="col-md-4 mt-3 mt-md-0 text-md-end">
                                    <span class="fw-bold text-dark small text-uppercase d-block mb-1">Paket İlerlemesi</span>
                                    <span class="badge bg-<?= $renk ?> fs-6 py-1 px-3 rounded-pill mb-2"><?= $paket['shipped_boxes'] ?> / <?= $paket['total_boxes'] ?> Kutu</span>
                                    
                                    <div class="progress" style="height: 10px; background-color: #dee2e6; border-radius: 10px;">
                                        <div class="progress-bar progress-bar-striped <?= (!$is_on_hold && $yuzde < 100) ? 'progress-bar-animated' : '' ?> bg-<?= $renk ?>" role="progressbar" style="width: <?= $yuzde ?>%"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="card-body p-4 bg-white">
                            <?php if($is_on_hold): ?>
                                <div class="alert alert-danger border-0 small py-2 mb-4">
                                    <i class="bi bi-info-circle-fill me-2"></i> İptal talebiniz nedeniyle bu paketin gönderim işlemleri geçici olarak durdurulmuştur.
                                </div>
                            <?php endif; ?>

                            <h6 class="fw-bold text-uppercase text-muted mb-4 small"><i class="bi bi-truck me-2"></i> Gönderim Takvimi ve İçerikler</h6>
                            
                            <div class="row row-cols-1 row-cols-md-2 g-4">
                                <?php 
                                $detaylar = $kutu_detaylari[$paket['order_id']] ?? [];
                                foreach($detaylar as $kutu): 
                                    $kargolandi = in_array($kutu['status'], ['shipped', 'delivered']);
                                ?>
                                    <div class="col">
                                        <div class="card h-100 border shadow-none rounded-4 <?= $kargolandi ? 'bg-success bg-opacity-10 border-success' : 'bg-light border-secondary border-opacity-25' ?> <?= $is_on_hold ? 'opacity-50' : '' ?>">
                                            <div class="card-body p-3 d-flex flex-column">
                                                
                                                <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2 <?= $kargolandi ? 'border-success border-opacity-25' : '' ?>">
                                                    <span class="fw-bold fs-6 <?= $kargolandi ? 'text-success' : 'text-dark' ?>"><?= $kutu['delivery_sequence'] ?>. Gönderim Kutusu</span>
                                                    <?php if($kargolandi): ?>
                                                        <span class="badge bg-success rounded-pill px-3">Gönderildi</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-secondary text-white rounded-pill px-3"><?= $is_on_hold ? 'Durduruldu' : 'Bekliyor' ?></span>
                                                    <?php endif; ?>
                                                </div>
                                                
                                                <div class="small fw-bold text-secondary mb-3 lh-sm" style="min-height: 45px;">
                                                    <span class="text-muted d-block mb-1" style="font-size: 0.65rem;">BU KUTUDAKİ YAYINLAR:</span>
                                                    • <?= $kutu['exam_list'] ?>
                                                </div>

                                                <?php if($kargolandi): ?>
                                                    <div class="mt-auto p-2 bg-white rounded border border-success border-opacity-50">
                                                        <div class="d-flex justify-content-between align-items-center">
                                                            <div class="small">
                                                                <small class="text-muted d-block" style="font-size: 9px;">KARGO BİLGİSİ</small>
                                                                <span class="fw-bold text-success d-block lh-1 mb-1" style="font-size: 0.75rem;"><?= htmlspecialchars($kutu['shipping_company']) ?> Takip Kodu</span>
                                                                <span class="fw-bold text-dark user-select-all fs-6"><?= htmlspecialchars($kutu['tracking_code']) ?></span>
                                                            </div>
                                                            <a href="<?= getKargoTakipLink($kutu['shipping_company'], $kutu['tracking_code']) ?>" target="_blank" class="btn btn-sm btn-success fw-bold px-3 rounded-pill shadow-sm">Takip Et</a>
                                                        </div>
                                                    </div>
                                                <?php else: ?>
                                                    <div class="mt-auto p-2 bg-white rounded border border-secondary border-opacity-25 text-center">
                                                        <span class="text-muted small fw-bold text-uppercase" style="font-size: 0.6rem;"><i class="bi bi-calendar-event text-warning me-1"></i> Planlanan Gönderim</span>
                                                        <div class="fw-bold text-dark"><?= $kutu['planned_date'] ? date('d.m.Y', strtotime($kutu['planned_date'])) : 'Onay Bekliyor' ?></div>
                                                    </div>
                                                <?php endif; ?>

                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>

            <?php else: ?>
                <div class="text-center py-5 bg-white rounded-4 shadow-sm border mt-4">
                    <i class="bi bi-box-seam text-muted opacity-25" style="font-size: 4rem;"></i>
                    <h4 class="fw-bold mt-3 text-dark">Henüz bir deneme paketiniz yok.</h4>
                    <p class="text-muted">Size özel hazırlanan deneme paketleriyle sınav maratonuna hazırlanın.</p>
                    <a href="<?= $kok_dizin ?>deneme-paketi-olustur.php" class="btn btn-primary px-5 py-2 rounded-pill fw-bold mt-3 shadow-sm">İlk Paketimi Oluşturayım</a>
                </div>
            <?php endif; ?>

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

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