<?php
/**
 * Kullanıcı Paneli - Aboneliklerim ve Teslimat Takvimi
 * Konum: /magaza/kullanici/abonelikler.php
 */

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

// Oturum Kontrolü
if (!isset($_SESSION['user_id'])) {
    header("Location: ../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 Aboneliklerini Çek
$stmt = $db->prepare("
    SELECT s.*, p.name as product_name, p.total_deliveries,
    (SELECT image_path FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1) as main_image
    FROM subscriptions s
    JOIN products p ON s.product_id = p.id
    WHERE s.user_id = ?
    ORDER BY s.id DESC
");
$stmt->execute([$user_id]);
$abonelikler = $stmt->fetchAll();

/**
 * Abonelik Durumu İçin Türkçe Etiket Fonksiyonu
 */
function getAbonelikDurumBadge($status) {
    switch ($status) {
        case 'active':
            return '<span class="badge bg-success px-3 py-2 rounded-pill shadow-sm"><i class="bi bi-check-circle-fill me-1"></i> Aktif Abonelik</span>';
        case 'cancelled':
            return '<span class="badge bg-danger px-3 py-2 rounded-pill shadow-sm"><i class="bi bi-x-octagon-fill me-1"></i> İptal Edildi</span>';
        case 'completed':
            return '<span class="badge bg-secondary px-3 py-2 rounded-pill shadow-sm"><i class="bi bi-flag-fill me-1"></i> Tamamlandı</span>';
        default:
            return '<span class="badge bg-light text-dark border px-3 py-2 rounded-pill shadow-sm">Bilinmiyor</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">
                <div>
                    <h2 class="h4 fw-bold mb-0 text-dark"><i class="bi bi-calendar-check text-primary me-2"></i>Abonelik Takibim</h2>
                    <p class="text-muted small mt-1 mb-0">Abonelik durumunuzu ve aylık periyodik gönderimlerinizi buradan takip edin.</p>
                </div>
                <a href="../index.php" class="btn btn-outline-dark btn-sm fw-bold px-3 rounded-pill shadow-sm">Mağazaya Dön</a>
            </div>

            <?php if (count($abonelikler) > 0): ?>
                <div class="row">
                    <?php foreach ($abonelikler as $a): 
                        $is_cancelled = ($a['status'] == 'cancelled');
                    ?>
                        <div class="col-12 mb-5">
                            <div class="card border-0 shadow-sm rounded-4 overflow-hidden mb-4 <?= $is_cancelled ? 'opacity-75' : '' ?>">
                                <div class="card-body p-4 bg-white border-start border-5 <?= $a['status'] == 'active' ? 'border-success' : ($is_cancelled ? 'border-danger' : 'border-secondary') ?>">
                                    <div class="row align-items-center">
                                        <div class="col-md-2 text-center mb-3 mb-md-0">
                                            <img src="../<?= htmlspecialchars($a['main_image'] ?: 'assets/img/no-image.jpg') ?>" class="img-fluid rounded border" style="max-height: 100px; object-fit: contain;">
                                        </div>
                                        <div class="col-md-6">
                                            <div class="badge bg-light text-dark border mb-2 px-3 fw-bold"><?= $a['total_deliveries'] ?> Aylık Gönderim Planı</div>
                                            <h5 class="fw-bold mb-1 text-dark"><?= htmlspecialchars($a['product_name']) ?></h5>
                                            <div class="small text-muted mt-2">
                                                <i class="bi bi-calendar3 me-1"></i> 
                                                <b>Dönem:</b> <?= date('d.m.Y', strtotime($a['start_date'])) ?> - <?= date('d.m.Y', strtotime($a['end_date'])) ?>
                                            </div>
                                        </div>
                                        <div class="col-md-4 text-md-end mt-3 mt-md-0">
                                            <div class="mb-2"><?= getAbonelikDurumBadge($a['status']) ?></div>
                                            <div class="small text-muted font-monospace">ABONE ID: #SUB-<?= $a['id'] ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="ps-md-4">
                                <h6 class="fw-bold text-uppercase text-muted mb-3 small"><i class="bi bi-truck-flatbed me-2"></i> Aylık Gönderim Detayları</h6>
                                <div class="row g-3">
                                    <?php
                                    $d_stmt = $db->prepare("SELECT * FROM subscription_deliveries WHERE subscription_id = ? ORDER BY delivery_month ASC");
                                    $d_stmt->execute([$a['id']]);
                                    $teslimatlar = $d_stmt->fetchAll();

                                    foreach ($teslimatlar as $index => $t):
                                        $ay_adi = date('F Y', strtotime($t['delivery_month'] . "-01"));
                                        $aylar = ['January'=>'Ocak','February'=>'Şubat','March'=>'Mart','April'=>'Nisan','May'=>'Mayıs','June'=>'Haziran','July'=>'Temmuz','August'=>'Ağustos','September'=>'Eylül','October'=>'Ekim','November'=>'Kasım','December'=>'Aralık'];
                                        $gosterim_ayi = strtr($ay_adi, $aylar);
                                        $kargolandi = ($t['status'] == 'shipped');
                                    ?>
                                        <div class="col-md-6 col-xl-4">
                                            <div class="card border shadow-none rounded-4 h-100 <?= $kargolandi ? 'bg-success bg-opacity-10 border-success border-opacity-25' : ($is_cancelled ? 'bg-light text-muted' : 'bg-white') ?>">
                                                <div class="card-body p-3">
                                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                                        <span class="fw-bold small text-dark"><?= $index + 1 ?>. Gönderim</span>
                                                        <?php if($kargolandi): ?>
                                                            <span class="badge bg-success rounded-pill small px-2"><i class="bi bi-check-lg"></i> Yolda</span>
                                                        <?php elseif($is_cancelled): ?>
                                                            <span class="badge bg-secondary rounded-pill small px-2">Durduruldu</span>
                                                        <?php else: ?>
                                                            <span class="badge bg-warning text-dark rounded-pill small px-2">Bekliyor</span>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="h5 fw-bold text-primary mb-2"><?= $gosterim_ayi ?></div>
                                                    
                                                    <?php if($kargolandi): ?>
                                                        <div class="mt-3 p-2 bg-white border border-success border-opacity-50 rounded-3">
                                                            <small class="text-muted d-block fw-bold" style="font-size: 10px;">TAKİP NUMARASI</small>
                                                            <div class="d-flex justify-content-between align-items-center">
                                                                <span class="fw-bold text-dark small"><?= htmlspecialchars($t['tracking_code']) ?></span>
                                                                <a href="https://kargotakip.com/?kod=<?= htmlspecialchars($t['tracking_code']) ?>" target="_blank" class="btn btn-sm btn-link p-0 text-success fw-bold text-decoration-none">İzle</a>
                                                            </div>
                                                        </div>
                                                    <?php else: ?>
                                                        <div class="small text-muted mt-2 fst-italic border-top pt-2">
                                                            <i class="bi bi-clock me-1"></i> 
                                                            <?= $is_cancelled ? 'Abonelik iptal edildiği için gönderilmeyecektir.' : 'Gönderim hazırlığı ay sonunda başlayacaktır.' ?>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="text-center py-5 bg-white rounded-4 shadow-sm border mt-4">
                    <i class="bi bi-calendar-x text-muted opacity-50" style="font-size: 4rem;"></i>
                    <h4 class="fw-bold mt-3 text-dark">Aktif bir aboneliğiniz bulunmuyor.</h4>
                    <p class="text-muted">Aylık periyodik deneme setleri için mağazamızı ziyaret edebilirsiniz.</p>
                    <a href="../index.php" class="btn btn-primary px-5 py-2 rounded-pill fw-bold mt-3 shadow-sm">Paketleri Keşfet</a>
                </div>
            <?php endif; ?>

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

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