<?php
/**
 * Widget (Vitrin) Render Motoru
 * Konum: /magaza/widget-render.php
 * Kullanım: İframe ile dışarıdan veya ana siteden çağrılır.
 */

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

$widget_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($widget_id <= 0) {
    die("<div style='font-family:sans-serif; text-align:center; padding:20px; color:#666;'>Geçersiz Widget ID.</div>");
}

// 1. Widget Ayarlarını Çek
$w_stmt = $db->prepare("SELECT * FROM widgets WHERE id = ? AND status = 1");
$w_stmt->execute([$widget_id]);
$widget = $w_stmt->fetch(PDO::FETCH_ASSOC);

if (!$widget) {
    die("<div style='font-family:sans-serif; text-align:center; padding:20px; color:#666;'>Bu vitrin yayından kaldırılmış veya bulunamıyor.</div>");
}

// 2. Ürünleri Çek (Kategoriye Göre ve Limite Göre)
$limit = (int)$widget['item_limit'];
$kategori_sarti = "";
$params = [];

if (!empty($widget['category_id'])) {
    $kategori_sarti = "AND p.category_id = ?";
    $params[] = $widget['category_id'];
}

// GÜNCELLEME: ORDER BY p.id DESC yerine ORDER BY RAND() eklendi.
$sql = "
    SELECT 
        p.id, p.name, p.slug, p.price, p.discount_price, p.type,
        b.name as brand_name, 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 products p
    LEFT JOIN brands b ON p.brand_id = b.id
    WHERE p.status = 1 $kategori_sarti
    ORDER BY RAND()
    LIMIT $limit
";

$p_stmt = $db->prepare($sql);
$p_stmt->execute($params);
$urunler = $p_stmt->fetchAll(PDO::FETCH_ASSOC);

// Site URL (Görsel ve link yolları için)
$site_url = "https://" . $_SERVER['HTTP_HOST'] . "/magaza";
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($widget['title']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />
    
    <style>
        body { background-color: transparent; font-family: 'Poppins', sans-serif; overflow-x: hidden; }
        
        /* Modern Ürün Kartı Tasarımı */
        .product-card {
            border: 1px solid #ebebeb;
            border-radius: 16px;
            transition: all 0.3s ease;
            background: #fff;
            height: 100%;
            display: flex;
            flex-direction: column;
            text-decoration: none !important;
            overflow: hidden;
        }
        .product-card:hover {
            border-color: #0d6efd;
            box-shadow: 0 10px 20px rgba(13, 110, 253, 0.1);
            transform: translateY(-3px);
        }
        .img-wrapper {
            position: relative;
            padding-top: 100%; /* 1:1 Aspect Ratio */
            background-color: #f8f9fa;
            border-bottom: 1px solid #f1f1f1;
        }
        .img-wrapper img {
            position: absolute;
            top: 0; left: 0; right: 0; bottom: 0;
            width: 100%; height: 100%;
            object-fit: contain;
            padding: 1rem;
        }
        .discount-badge {
            position: absolute;
            top: 10px; left: 10px;
            background: #dc3545;
            color: #fff;
            padding: 4px 8px;
            border-radius: 8px;
            font-size: 0.75rem;
            font-weight: bold;
            z-index: 2;
        }
        .card-body-custom { padding: 1rem; flex-grow: 1; display: flex; flex-direction: column; }
        .product-brand { font-size: 0.7rem; color: #6c757d; text-transform: uppercase; font-weight: 700; margin-bottom: 0.25rem; }
        .product-title { 
            font-size: 0.9rem; 
            font-weight: 600; 
            color: #212529; 
            margin-bottom: 0.5rem;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            line-height: 1.3;
        }
        .price-wrapper { margin-top: auto; }
        .old-price { font-size: 0.8rem; color: #adb5bd; text-decoration: line-through; margin-right: 5px; }
        .new-price { font-size: 1.1rem; color: #0d6efd; font-weight: 800; }
        
        .btn-view {
            width: 100%;
            padding: 8px;
            border-radius: 8px;
            font-weight: bold;
            font-size: 0.85rem;
            margin-top: 10px;
            background: #f0f7ff;
            color: #0d6efd;
            border: none;
            transition: 0.2s;
        }
        .product-card:hover .btn-view { background: #0d6efd; color: #fff; }

        /* Swiper Özelleştirmeleri */
        .swiper { padding: 10px 5px 40px 5px !important; }
        .swiper-pagination-bullet-active { background: #0d6efd !important; }
        .swiper-button-next, .swiper-button-prev {
            background: #fff;
            width: 40px; height: 40px;
            border-radius: 50%;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
            color: #0d6efd;
        }
        .swiper-button-next:after, .swiper-button-prev:after { font-size: 1.2rem; font-weight: bold; }
        
        /* Eğer widget boşsa */
        .empty-state { text-align: center; padding: 2rem; background: #f8f9fa; border-radius: 1rem; color: #6c757d; }
    </style>
</head>
<body>

<div class="container-fluid px-0">
    
    <?php if(count($urunler) == 0): ?>
        <div class="empty-state">
            <i class="bi bi-box-seam fs-2 d-block mb-2 opacity-50"></i>
            <span class="fw-bold">Bu vitrinde henüz ürün bulunmuyor.</span>
        </div>
    <?php else: ?>

        <?php if($widget['layout_type'] == 'slider'): ?>
            <div class="swiper widgetSwiper">
                <div class="swiper-wrapper">
                    <?php foreach($urunler as $urun): 
                        $link = $site_url . '/urun/' . $urun['slug'];
                        $gorsel = $site_url . '/' . ($urun['main_image'] == 'assets/img/no-image.jpg' && !empty($urun['brand_logo']) ? $urun['brand_logo'] : $urun['main_image']);
                    ?>
                        <div class="swiper-slide h-auto">
                            <a href="<?= $link ?>" target="_parent" class="product-card">
                                <div class="img-wrapper">
                                    <?php if($urun['discount_price'] > 0): 
                                        $indirim_orani = round((($urun['price'] - $urun['discount_price']) / $urun['price']) * 100);
                                    ?>
                                        <div class="discount-badge">%<?= $indirim_orani ?> İndirim</div>
                                    <?php endif; ?>
                                    <img src="<?= $gorsel ?>" alt="<?= htmlspecialchars($urun['name']) ?>">
                                </div>
                                <div class="card-body-custom">
                                    <div class="product-brand"><?= htmlspecialchars($urun['brand_name'] ?? 'Genel') ?></div>
                                    <div class="product-title"><?= htmlspecialchars($urun['name']) ?></div>
                                    <div class="price-wrapper">
                                        <?php if($urun['discount_price'] > 0): ?>
                                            <span class="old-price"><?= number_format($urun['price'], 2, ',', '.') ?> ₺</span>
                                            <span class="new-price"><?= number_format($urun['discount_price'], 2, ',', '.') ?> ₺</span>
                                        <?php else: ?>
                                            <span class="new-price"><?= number_format($urun['price'], 2, ',', '.') ?> ₺</span>
                                        <?php endif; ?>
                                    </div>
                                    <button class="btn-view">Hemen İncele</button>
                                </div>
                            </a>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="swiper-pagination"></div>
                <div class="swiper-button-next d-none d-md-flex"></div>
                <div class="swiper-button-prev d-none d-md-flex"></div>
            </div>

        <?php else: ?>
            <div class="row row-cols-2 row-cols-md-3 row-cols-lg-4 g-3 g-md-4 p-2">
                <?php foreach($urunler as $urun): 
                    $link = $site_url . '/urun/' . $urun['slug'];
                    $gorsel = $site_url . '/' . ($urun['main_image'] == 'assets/img/no-image.jpg' && !empty($urun['brand_logo']) ? $urun['brand_logo'] : $urun['main_image']);
                ?>
                    <div class="col">
                        <a href="<?= $link ?>" target="_parent" class="product-card">
                            <div class="img-wrapper">
                                <?php if($urun['discount_price'] > 0): 
                                    $indirim_orani = round((($urun['price'] - $urun['discount_price']) / $urun['price']) * 100);
                                ?>
                                    <div class="discount-badge">%<?= $indirim_orani ?></div>
                                <?php endif; ?>
                                <img src="<?= $gorsel ?>" alt="<?= htmlspecialchars($urun['name']) ?>">
                            </div>
                            <div class="card-body-custom">
                                <div class="product-brand"><?= htmlspecialchars($urun['brand_name'] ?? 'Genel') ?></div>
                                <div class="product-title"><?= htmlspecialchars($urun['name']) ?></div>
                                <div class="price-wrapper">
                                    <?php if($urun['discount_price'] > 0): ?>
                                        <span class="old-price"><?= number_format($urun['price'], 2, ',', '.') ?> ₺</span>
                                        <span class="new-price"><?= number_format($urun['discount_price'], 2, ',', '.') ?> ₺</span>
                                    <?php else: ?>
                                        <span class="new-price"><?= number_format($urun['price'], 2, ',', '.') ?> ₺</span>
                                    <?php endif; ?>
                                </div>
                                <button class="btn-view">İncele</button>
                            </div>
                        </a>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>

<script>
    <?php if($widget['layout_type'] == 'slider'): ?>
    document.addEventListener('DOMContentLoaded', function() {
        var swiper = new Swiper(".widgetSwiper", {
            slidesPerView: 2, 
            spaceBetween: 15,
            loop: false,
            pagination: {
                el: ".swiper-pagination",
                clickable: true,
            },
            navigation: {
                nextEl: ".swiper-button-next",
                prevEl: ".swiper-button-prev",
            },
            breakpoints: {
                640: { slidesPerView: 2, spaceBetween: 20 },
                768: { slidesPerView: 3, spaceBetween: 20 },
                1024: { slidesPerView: 4, spaceBetween: 25 },
                1200: { slidesPerView: 5, spaceBetween: 25 },
            },
        });
    });
    <?php endif; ?>
</script>

</body>
</html>