<?php
/**
 * Müşteri Paneli Ana Sayfa (Her Kategoriden 1 Ürün Zekası)
 * Konum: /magaza/kullanici/index.php
 */

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

// 1. OTURUM GÜVENLİĞİ
if (!isset($_SESSION['user_id'])) {
    header("Location: ../giris.php");
    exit;
}

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

// 2. MÜŞTERİ BİLGİLERİNİ ÇEK
$user_stmt = $db->prepare("SELECT name, surname, email, phone FROM users WHERE id = ?");
$user_stmt->execute([$user_id]);
$musteri = $user_stmt->fetch();

if (!$musteri) {
    session_destroy();
    header("Location: ../giris.php");
    exit;
}

// 3. İSTATİSTİKLER
$siparis_sayisi = $db->prepare("SELECT COUNT(id) FROM orders WHERE user_id = ?");
$siparis_sayisi->execute([$user_id]);
$toplam_siparis = $siparis_sayisi->fetchColumn();

$paket_sayisi = $db->prepare("
    SELECT COUNT(DISTINCT od.order_id) 
    FROM order_deliveries od 
    JOIN orders o ON od.order_id = o.id 
    WHERE o.user_id = ? AND o.status != 'cancelled'
");
$paket_sayisi->execute([$user_id]);
$aktif_paket = $paket_sayisi->fetchColumn();

// 4. SON SİPARİŞLER
$son_siparisler = $db->prepare("
    SELECT o.id, o.order_number, o.total_amount, o.status, o.created_at, o.is_cancel_requested,
    (SELECT request_type FROM order_returns WHERE order_id = o.id ORDER BY id DESC LIMIT 1) as talep_tipi,
    (SELECT status FROM order_returns WHERE order_id = o.id ORDER BY id DESC LIMIT 1) as talep_durumu
    FROM orders o 
    WHERE o.user_id = ? 
    ORDER BY o.id DESC LIMIT 3
");
$son_siparisler->execute([$user_id]);
$siparisler = $son_siparisler->fetchAll();

// 5. HER KATEGORİDEN EN SON 1 ÜRÜN ÇEK
$yeni_urunler = $db->query("
    SELECT p.id, p.name, p.slug, p.price, p.discount_price, p.type,
    b.logo as brand_logo, b.name as brand_name,
    COALESCE(
        (SELECT image_path FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1),
        (SELECT default_cover FROM brands WHERE id = p.brand_id),
        'assets/img/no-image.jpg'
    ) as main_image
    FROM products p 
    LEFT JOIN brands b ON p.brand_id = b.id
    WHERE p.status = 1 
    GROUP BY p.category_id 
    ORDER BY p.id DESC 
    LIMIT 4
")->fetchAll(PDO::FETCH_ASSOC);

/**
 * Gelişmiş Durum Çevirici
 */
function getKullaniciSiparisDurumu($s) {
    if ($s['is_cancel_requested'] == 1 && $s['status'] != 'cancelled') {
        return '<span class="badge bg-danger bg-opacity-10 text-danger border border-danger"><i class="bi bi-slash-circle me-1"></i> İptal İsteniyor</span>';
    }
    if ($s['talep_tipi'] == 'return' && !in_array($s['talep_durumu'], ['completed', 'rejected'])) {
        return '<span class="badge bg-info bg-opacity-10 text-info border border-info"><i class="bi bi-arrow-counterclockwise me-1"></i> İade Sürecinde</span>';
    }
    switch ($s['status']) {
        case 'pending': return '<span class="badge bg-warning text-dark"><i class="bi bi-hourglass-split me-1"></i> Onay Bekliyor</span>';
        case 'processing': return '<span class="badge bg-info text-dark"><i class="bi bi-box-seam me-1"></i> Hazırlanıyor</span>';
        case 'shipped': return '<span class="badge bg-primary"><i class="bi bi-truck me-1"></i> Kargolandı</span>';
        case 'delivered': return '<span class="badge bg-success"><i class="bi bi-check-circle-fill me-1"></i> Teslim Edildi</span>';
        case 'cancelled': return '<span class="badge bg-secondary"><i class="bi bi-x-circle me-1"></i> İptal Edildi</span>';
        default: return '<span class="badge bg-secondary">Bilinmiyor</span>';
    }
}

/**
 * Görsel Yolu Çözücü (Kesin Çözüm)
 */
function resolveImageUrl($path) {
    if (empty($path) || $path == 'assets/img/no-image.jpg') return '/magaza/assets/img/no-image.jpg';
    if (strpos($path, 'http') === 0) return $path;
    $path = ltrim($path, '/');
    if (strpos($path, 'magaza/') === 0) return '/' . $path;
    return '/magaza/' . $path;
}

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-end mb-4 border-bottom pb-3">
                <div>
                    <h2 class="fw-bold mb-1">Hoş Geldin, <span class="text-primary"><?= htmlspecialchars($musteri['name']) ?>!</span> 👋</h2>
                    <p class="text-muted small mb-0">Sınav maratonundaki yolculuğunda Sınav Koçu her zaman yanında.</p>
                </div>
                <a href="../deneme-paketi-olustur.php" class="btn btn-dark fw-bold shadow-sm rounded-pill px-4">
                    <i class="bi bi-boxes me-1"></i> Yeni Paket Oluştur
                </a>
            </div>

            <div class="row g-4 mb-4">
                <div class="col-md-6">
                    <div class="card bg-white shadow-sm border-0 h-100 rounded-4">
                        <div class="card-body p-4 d-flex align-items-center">
                            <div class="bg-primary bg-opacity-10 text-primary rounded-circle d-flex align-items-center justify-content-center me-4" style="width: 60px; height: 60px;">
                                <i class="bi bi-bag-check-fill fs-3"></i>
                            </div>
                            <div>
                                <h6 class="text-muted fw-bold mb-1 text-uppercase small">Toplam Siparişlerim</h6>
                                <h3 class="fw-bold mb-0 text-dark"><?= $toplam_siparis ?> <small class="text-muted fs-6">Sipariş</small></h3>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card bg-white shadow-sm border-0 h-100 rounded-4 position-relative">
                        <div class="card-body p-4 d-flex align-items-center">
                            <div class="bg-success bg-opacity-10 text-success rounded-circle d-flex align-items-center justify-content-center me-4" style="width: 60px; height: 60px;">
                                <i class="bi bi-box2-heart-fill fs-3"></i>
                            </div>
                            <div>
                                <h6 class="text-muted fw-bold mb-1 text-uppercase small">Aktif Deneme Paketlerim</h6>
                                <h3 class="fw-bold mb-0 text-dark"><?= $aktif_paket ?> <small class="text-muted fs-6">Paket</small></h3>
                            </div>
                        </div>
                        <?php if($aktif_paket > 0): ?>
                            <a href="denemepaketim.php" class="stretched-link"></a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm border-0 rounded-4 mb-5 overflow-hidden">
                <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center border-bottom">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-clock-history text-primary me-2"></i>Son Siparişlerim</h5>
                    <?php if($toplam_siparis > 3): ?>
                        <a href="siparisler.php" class="btn btn-sm btn-outline-dark rounded-pill px-3 fw-bold">Tümünü Gör</a>
                    <?php endif; ?>
                </div>
                <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 text-uppercase">
                                <tr>
                                    <th class="ps-4">Sipariş No</th>
                                    <th>Tarih</th>
                                    <th>Tutar</th>
                                    <th class="text-center">Durum</th>
                                    <th class="text-end pe-4">Detay</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(count($siparisler) > 0): ?>
                                    <?php foreach($siparisler as $s): ?>
                                    <tr>
                                        <td class="ps-4 fw-bold">
                                            <a href="kullanici/siparis-detay.php?id=<?= $s['id'] ?>" class="text-primary text-decoration-none">#<?= $s['order_number'] ?></a>
                                        </td>
                                        <td class="small fw-bold text-muted"><?= date('d.m.Y', strtotime($s['created_at'])) ?></td>
                                        <td class="fw-bold text-success"><?= number_format($s['total_amount'], 2, ',', '.') ?> ₺</td>
                                        <td class="text-center"><?= getKullaniciSiparisDurumu($s) ?></td>
                                        <td class="text-end pe-4">
                                            <a href="kullanici/siparis-detay.php?id=<?= $s['id'] ?>" class="btn btn-sm btn-light border shadow-sm rounded-circle">
                                                <i class="bi bi-chevron-right"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="5" class="text-center py-5 text-muted small">Henüz siparişiniz bulunmuyor.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <?php if(count($yeni_urunler) > 0): ?>
    <div class="d-flex justify-content-between align-items-center mb-3 mt-5">
        <h5 class="fw-bold mb-0"><i class="bi bi-collection text-warning me-2"></i>Senin İçin Seçtiklerimiz</h5>
        <a href="<?= $kok_dizin ?>yeni-eklenen-urunler.php" class="text-primary text-decoration-none small fw-bold">Tümünü Gör <i class="bi bi-arrow-right"></i></a>
    </div>
    
    <div class="row row-cols-1 row-cols-md-2 row-cols-xl-4 g-4">
        <?php foreach($yeni_urunler as $u): ?>
            <?php 
                $brand_logo_src = resolveImageUrl($u['brand_logo']);
                $main_image_src = resolveImageUrl($u['main_image']);
            ?>
            <div class="col">
                <div class="card h-100 border-0 shadow-sm rounded-4 overflow-hidden product-card position-relative bg-white">
                    
                    <?php if(!empty($u['brand_logo']) && $u['brand_logo'] != 'assets/img/no-image.jpg'): ?>
                        <div class="position-absolute top-0 end-0 m-2 bg-white rounded shadow-sm d-flex align-items-center justify-content-center p-1" style="width: 35px; height: 20px; z-index: 5;">
                            <img src="<?= htmlspecialchars($brand_logo_src) ?>" class="img-fluid" style="max-height: 100%; max-width: 100%; object-fit: contain;">
                        </div>
                    <?php endif; ?>

                    <a href="<?= $kok_dizin ?>urun/<?= $u['slug'] ?>" class="text-decoration-none">
                        <div class="position-relative bg-light text-center p-2" style="height: 180px;">
                            <img src="<?= htmlspecialchars($main_image_src) ?>" class="img-fluid h-100" style="object-fit: contain;">
                            
                            <div class="position-absolute top-0 start-0 m-2 d-flex flex-column gap-1 align-items-start" style="z-index: 5;">
                                <?php if ($u['discount_price'] > 0): ?>
                                    <span class="badge bg-danger shadow-sm px-2 py-1" style="font-size:0.7rem; border-radius: 4px;">-%<?= round((($u['price'] - $u['discount_price']) / $u['price']) * 100) ?> İndirimli</span>
                                <?php endif; ?>

                                <?php if($u['type'] == 'exam_package'): ?>
                                    <span class="badge bg-warning text-dark shadow-sm px-2 py-1" style="font-size:0.65rem; border-radius: 4px;">Özel Deneme Paketi</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="card-body p-3 text-center d-flex flex-column justify-content-between" style="height: 110px;">
                            <h6 class="card-title text-dark fw-bold mb-1 text-truncate-2" style="font-size: 0.85rem; height: 2.4rem;" title="<?= htmlspecialchars($u['name']) ?>">
                                <?= htmlspecialchars($u['name']) ?>
                            </h6>
                            
                            <div class="mt-auto">
                                <?php if ($u['discount_price'] > 0): ?>
                                    <div class="text-muted text-decoration-line-through small" style="font-size:0.7rem;"><?= number_format($u['price'], 2, ',', '.') ?> ₺</div>
                                    <div class="text-danger fw-bold" style="font-size:1rem;"><?= number_format($u['discount_price'], 2, ',', '.') ?> ₺</div>
                                <?php else: ?>
                                    <div class="text-primary fw-bold" style="font-size:1rem;"><?= number_format($u['price'], 2, ',', '.') ?> ₺</div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </a>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>
        </div>
    </div>
</main>

<style>
    .product-card { transition: all 0.3s ease; border: 1px solid #f0f0f0 !important; }
    .product-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.1) !important; }
    .text-truncate-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
</style>

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