<?php include __DIR__ . '/../layout/header.php'; ?>

<div class="container" style="padding-top:28px;padding-bottom:48px;">

    <!-- Breadcrumb -->
    <nav class="breadcrumb">
        <a href="<?php echo $baseUrl; ?>/"><i class="fa fa-home"></i></a>
        <span>/</span>
        <?php foreach ($product->getCategories() as $bcCat): ?>
        <a href="<?php echo $baseUrl; ?>/<?php echo $bcCat->slug; ?>"><?php echo htmlspecialchars($bcCat->name); ?></a>
        <span>/</span>
        <?php endforeach; ?>
        <span style="color:var(--text-1);"><?php echo htmlspecialchars($product->name); ?></span>
    </nav>

    <!-- Product Detail Grid -->
    <div class="product-detail-grid">

        <!-- Image -->
        <?php 
        $allImages = $product->getImages();
        $jsImages = [];
        foreach($allImages as $img) {
            $jsImages[] = strpos($img, 'http') === 0 ? $img : $baseUrl . $img;
        }
        ?>
        <div style="display:flex; flex-direction:column; gap:15px; position:relative;">
            <div class="product-detail-img" style="position:relative; cursor:zoom-in;">
                <img id="main-product-image" src="<?php echo $product->getMainImage($baseUrl); ?>" alt="<?php echo htmlspecialchars($product->name); ?>" loading="lazy" style="transition: transform 0.1s ease-out;">

                <?php if (count($jsImages) > 1): ?>
                <button onclick="event.stopPropagation(); changeImage(-1)" style="position:absolute; left:15px; top:50%; transform:translateY(-50%); background:rgba(0,0,0,0.7); backdrop-filter:blur(4px); color:#fff; border:2px solid rgba(255,255,255,0.2); box-shadow:0 4px 15px rgba(0,0,0,0.4); width:44px; height:44px; border-radius:50%; cursor:pointer; display:flex; align-items:center; justify-content:center; z-index:10; transition:0.2s;" onmouseover="this.style.background='var(--primary)'; this.style.borderColor='var(--primary)';" onmouseout="this.style.background='rgba(0,0,0,0.7)'; this.style.borderColor='rgba(255,255,255,0.2)';"><i class="fa fa-chevron-left" style="font-size:16px;"></i></button>
                <button onclick="event.stopPropagation(); changeImage(1)" style="position:absolute; right:15px; top:50%; transform:translateY(-50%); background:rgba(0,0,0,0.7); backdrop-filter:blur(4px); color:#fff; border:2px solid rgba(255,255,255,0.2); box-shadow:0 4px 15px rgba(0,0,0,0.4); width:44px; height:44px; border-radius:50%; cursor:pointer; display:flex; align-items:center; justify-content:center; z-index:10; transition:0.2s;" onmouseover="this.style.background='var(--primary)'; this.style.borderColor='var(--primary)';" onmouseout="this.style.background='rgba(0,0,0,0.7)'; this.style.borderColor='rgba(255,255,255,0.2)';"><i class="fa fa-chevron-right" style="font-size:16px;"></i></button>
                <?php endif; ?>
            </div>
            
            <?php if (count($jsImages) > 1): ?>
            <div style="display:flex; gap:10px; overflow-x:auto; padding-bottom:5px;" id="product-thumbnails">
                <?php foreach($jsImages as $idx => $fullPath): ?>
                <div onclick="setImage(<?php echo $idx; ?>);" 
                     class="thumb-img" id="thumb-<?php echo $idx; ?>"
                     style="width:80px; height:80px; border:2px solid <?php echo $idx === 0 ? 'var(--primary)' : 'var(--border)'; ?>; border-radius:var(--r-md); overflow:hidden; cursor:pointer; flex-shrink:0; background:var(--surface-2); padding:5px; transition:0.3s; opacity: <?php echo $idx === 0 ? '1' : '0.6'; ?>;">
                    <img src="<?php echo htmlspecialchars($fullPath); ?>" style="width:100%; height:100%; object-fit:contain; border-radius:4px;">
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- Info -->
        <div class="product-detail-info">
            <?php
$brandName = '';
$brandSlug = $product->brand_slug ?? '';
if ($brandSlug) {
    $allSettings = \App\Models\Settings::all();
    foreach (($allSettings['brands'] ?? []) as $b) {
        if ($b['slug'] === $brandSlug) { $brandName = $b['name']; break; }
    }
}
?>
<div class="product-brand" style="font-size:12px;margin-bottom:-4px;"><?php echo htmlspecialchars($brandName ?: ''); ?></div>
            <h1><?php echo htmlspecialchars($product->name); ?></h1>

            <!-- Specs -->
            <div class="card" style="padding:16px;display:flex;flex-direction:column;gap:10px;">
                <div style="display:flex;gap:8px;font-size:13px;">
                    <span style="color:var(--text-3);min-width:110px;">Model:</span>
                    <span style="color:var(--text-2);font-weight:600;"><?php echo htmlspecialchars(isset($product->model) ? $product->model : '-'); ?></span>
                </div>
                <div style="display:flex;gap:8px;font-size:13px;">
                    <span style="color:var(--text-3);min-width:110px;">Stok Durumu:</span>
                    <?php if ($product->stock > 0): ?>
                    <span class="badge badge-green"><i class="fa fa-check-circle" style="margin-right:4px;"></i>Stokta Var (<?php echo $product->stock; ?> Adet)</span>
                    <?php else: ?>
                    <span class="badge badge-red"><i class="fa fa-times-circle" style="margin-right:4px;"></i>Stokta Yok</span>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Price -->
            <div style="background:var(--surface-2);border:1px solid var(--border);border-radius:var(--r-lg);padding:20px;">
                <div style="font-size:12px;color:var(--text-3);margin-bottom:6px;letter-spacing:0.5px;text-transform:uppercase;">Fiyat</div>
                <div class="product-detail-price"><?php echo $product->getFormattedPrice(); ?></div>
                <div style="font-size:11px;color:var(--text-3);margin-top:6px;">* KDV hariç fiyat: <?php echo $product->getOriginalPriceFormatted(); ?></div>
            </div>

            <!-- Add to cart -->
            <?php if ($product->stock > 0): ?>
            <div style="display:flex;gap:12px;align-items:center;">
                <div class="quantity-input">
                    <button type="button" class="qty-minus" onclick="const q=document.getElementById('p-qty');if(q.value>1)q.value--;"><i class="fa fa-minus"></i></button>
                    <input type="number" id="p-qty" value="1" min="1" max="<?php echo $product->stock; ?>">
                    <button type="button" class="qty-plus" onclick="const q=document.getElementById('p-qty');if(parseInt(q.value)<<?php echo $product->stock;?>)q.value=parseInt(q.value)+1;"><i class="fa fa-plus"></i></button>
                </div>
                <button class="btn btn-primary btn-lg" style="flex:1;" onclick="addToCart('<?php echo $product->id; ?>', parseInt(document.getElementById('p-qty').value))">
                    <i class="fa fa-shopping-basket"></i> Sepete Ekle
                </button>
            </div>
            <?php else: ?>
            <div class="alert alert-danger"><i class="fa fa-times-circle"></i> Bu ürün şu an stokta bulunmamaktadır.</div>
            <?php endif; ?>

            <!-- Trust badges -->
            <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:4px;">
                <div style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--text-3);">
                    <i class="fa fa-truck" style="color:var(--orange);"></i> Hızlı Kargo
                </div>
                <div style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--text-3);">
                    <i class="fa fa-shield" style="color:var(--orange);"></i> Güvenli Ödeme
                </div>
                <div style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--text-3);">
                    <i class="fa fa-undo" style="color:var(--orange);"></i> İade Garantisi
                </div>
            </div>
        </div>
    </div>

    <!-- Description -->
    <?php if (!empty($product->description)): ?>
    <div class="card" style="margin-top:32px;">
        <h3 style="font-size:16px;font-weight:700;color:var(--text-1);margin-bottom:20px;padding-bottom:12px;border-bottom:1px solid var(--border);">
            Ürün Açıklaması
        </h3>
        <div class="product-description">
            <?php echo str_replace('http://', 'https://', $product->description); ?>
        </div>
    </div>
    <?php endif; ?>

</div>

<style>
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
.product-description { color:var(--text-2); font-size:14px; line-height:1.9; }
.product-description table { width:100%; border-collapse:collapse; margin:12px 0; }
.product-description table td { padding:10px 14px; vertical-align:top; }
.product-description table tr { border-bottom:1px solid var(--border); }
.product-description table td:first-child { font-weight:600; width:40%; color:var(--text-1); background:var(--surface-2); }
.product-description table td:last-child { color:var(--text-2); }
.product-description h3 { font-size:16px; font-weight:700; margin:24px 0 12px; padding-bottom:8px; border-bottom:2px solid var(--border); color:var(--text-1); }
.product-description p { margin:6px 0; }
</style>

<script>
    const productImages = <?php echo json_encode($jsImages); ?>;
    let currentImageIndex = 0;
    let zoomLevel = 1;

    function resetZoom() {
        zoomLevel = 1;
        const mainImg = document.getElementById('main-product-image');
        if (mainImg) {
            mainImg.style.transform = 'scale(1)';
            mainImg.style.transformOrigin = 'center center';
            mainImg.style.cursor = 'zoom-in';
        }
    }

    function setImage(index) {
        if (!productImages || productImages.length === 0) return;
        currentImageIndex = index;
        document.getElementById('main-product-image').src = productImages[currentImageIndex];
        resetZoom();

        // Highlight thumbnail
        const thumbs = document.querySelectorAll('.thumb-img');
        thumbs.forEach((el, idx) => {
            el.style.borderColor = idx === currentImageIndex ? 'var(--primary)' : 'var(--border)';
            el.style.opacity = idx === currentImageIndex ? '1' : '0.6';
        });
    }

    function changeImage(direction, preventBubble = false) {
        if (preventBubble && window.event) window.event.stopPropagation();
        if (!productImages || productImages.length <= 1) return;
        currentImageIndex += direction;
        if (currentImageIndex >= productImages.length) currentImageIndex = 0;
        if (currentImageIndex < 0) currentImageIndex = productImages.length - 1;
        setImage(currentImageIndex);
    }

    // Inline Focal Zoom on Main Image
    const mainImg = document.getElementById('main-product-image');
    const imgContainer = document.querySelector('.product-detail-img');
    
    if (mainImg && imgContainer) {
        // Toggle zoom on click
        imgContainer.addEventListener('click', function(e) {
            // Prevent zoom if clicking on navigation buttons
            if(e.target.tagName.toLowerCase() === 'button' || e.target.closest('button')) return;
            
            if (zoomLevel > 1) {
                resetZoom();
            } else {
                const rect = imgContainer.getBoundingClientRect();
                const xPercent = ((e.clientX - rect.left) / rect.width) * 100;
                const yPercent = ((e.clientY - rect.top) / rect.height) * 100;
                mainImg.style.transformOrigin = `${xPercent}% ${yPercent}%`;
                
                zoomLevel = 2.5;
                mainImg.style.transform = 'scale(2.5)';
                mainImg.style.cursor = 'zoom-out';
            }
        });
        
        // Pan on mousemove when zoomed
        imgContainer.addEventListener('mousemove', function(e) {
            if (zoomLevel > 1) {
                const rect = imgContainer.getBoundingClientRect();
                const xPercent = ((e.clientX - rect.left) / rect.width) * 100;
                const yPercent = ((e.clientY - rect.top) / rect.height) * 100;
                mainImg.style.transformOrigin = `${xPercent}% ${yPercent}%`;
            }
        });
        
        // Reset zoom when mouse leaves the image container
        imgContainer.addEventListener('mouseleave', function() {
            if (zoomLevel > 1) {
                resetZoom();
            }
        });
        
        // Mouse wheel to zoom inline
        imgContainer.addEventListener('wheel', function(e) {
            e.preventDefault();
            
            if (zoomLevel === 1) {
                const rect = imgContainer.getBoundingClientRect();
                const xPercent = ((e.clientX - rect.left) / rect.width) * 100;
                const yPercent = ((e.clientY - rect.top) / rect.height) * 100;
                mainImg.style.transformOrigin = `${xPercent}% ${yPercent}%`;
            }

            if (e.deltaY < 0) {
                zoomLevel += 0.25;
            } else {
                zoomLevel -= 0.25;
            }
            
            if (zoomLevel <= 1) {
                zoomLevel = 1;
                mainImg.style.transformOrigin = 'center center';
            }
            if (zoomLevel > 5) zoomLevel = 5;
            
            mainImg.style.transform = 'scale(' + zoomLevel + ')';
            mainImg.style.cursor = zoomLevel > 1 ? 'zoom-out' : 'zoom-in';
        });
    }
</script>

<?php include __DIR__ . '/../layout/footer.php'; ?>
