<?php 
$title = $product['name'];
use App\Core\View;
?>

<style>
    .product__section { display: grid; grid-template-columns: 350px 1fr; gap: 30px; margin: 30px 0; }
    .product__main-image { width: 350px; height: 350px; background: #f8f9fa; border-radius: 8px; overflow: hidden; display: flex; align-items: center; justify-content: center; }
    .product__main-image img { width: 100%; height: 100%; object-fit: contain; }
    .product__info h1 { color: #453227; margin-bottom: 15px; }
    .product__price { margin: 20px 0; }
    .current-price { font-size: 28px; font-weight: bold; color: #453227; }
    .old-price { font-size: 18px; color: #999; text-decoration: line-through; margin-left: 15px; }
    .discount-badge { background: #dc3545; color: white; padding: 5px 10px; border-radius: 4px; font-size: 14px; margin-left: 10px; }
    .stock-status { display: inline-block; padding: 8px 15px; border-radius: 4px; font-weight: bold; margin: 15px 0; }
    .in-stock { background: #d4edda; color: #155724; }
    .low-stock { background: #fff3cd; color: #856404; }
    .out-of-stock { background: #f8d7da; color: #721c24; }
    .product-attributes { background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0; }
    .attribute-row { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #ddd; }
    .attribute-label { font-weight: bold; color: #453227; }
    .attribute-value { color: #617365; }
    .product__purchase { display: flex; gap: 15px; align-items: center; margin: 20px 0; }
    .product__quantity { display: flex; align-items: center; gap: 10px; }
    .product__qty-btn { width: 35px; height: 35px; border: 1px solid #ddd; background: white; cursor: pointer; font-size: 18px; border-radius: 4px; }
    .product__qty-value { width: 50px; text-align: center; border: 1px solid #ddd; padding: 8px; border-radius: 4px; }
    .product__actions { display: flex; gap: 10px; }
    .similar-products { margin: 40px 0; }
    .similar-products h2 { color: #453227; margin-bottom: 20px; }
    .products-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
    .product-card { background: #f5f5f5; border-radius: 8px; overflow: hidden; }
    .product-card img { width: 100%; height: 200px; object-fit: cover; }
    .product-card .product-info { padding: 15px; }
    
    /* Reviews Section */
    .product-reviews { margin: 40px 0; padding: 30px; background: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
    .product-reviews h2 { color: #453227; margin-bottom: 25px; font-size: 26px; }
    .reviews-summary { background: #f8f9fa; padding: 25px; border-radius: 8px; margin-bottom: 30px; }
    .reviews-summary-rating { text-align: center; }
    .rating-number { font-size: 48px; font-weight: bold; color: #453227; margin-bottom: 10px; }
    .rating-stars { font-size: 24px; margin: 10px 0; }
    .rating-stars .star { color: #ddd; margin: 0 2px; }
    .rating-stars .star.filled { color: #ffc107; }
    .rating-count { color: #666; margin-top: 10px; font-size: 14px; }
</style>

<main class="container">
    <div class="breadcrumbs">
        <a href="/">Главная</a> •
        <a href="/catalog">Каталог</a> •
        <?php if ($product['category_name']): ?>
        <a href="/catalog?category=<?= $product['category_id'] ?>">
            <?= htmlspecialchars($product['category_name']) ?>
        </a> •
        <?php endif; ?>
        <span><?= htmlspecialchars($product['name']) ?></span>
    </div>

    <div class="product__section">
        <div class="product__gallery">
            <div class="product__main-image">
                <?php 
                $imageUrl = $product['image_url'] ?? '';
                if (empty($imageUrl)) {
                    $imageUrl = '/assets/images/1.jpg';
                } elseif (strpos($imageUrl, '/img2/') === 0) {
                    $imageUrl = str_replace('/img2/', '/assets/images/', $imageUrl);
                } elseif (strpos($imageUrl, 'img2/') === 0) {
                    $imageUrl = str_replace('img2/', '/assets/images/', $imageUrl);
                }
                ?>
                <img src="<?= htmlspecialchars($imageUrl) ?>"
                     alt="<?= htmlspecialchars($product['name']) ?>">
            </div>
        </div>

        <div class="product__info">
            <h1><?= htmlspecialchars($product['name']) ?></h1>

            <div class="product__rating">
                <div class="stars">
                    <?php
                    $rating = $product['rating'] ?? 0;
                    for ($i = 1; $i <= 5; $i++) {
                        echo $i <= $rating ? '<span class="star filled">★</span>' : '<span class="star">☆</span>';
                    }
                    ?>
                </div>
                <span>(<?= $product['review_count'] ?? 0 ?> отзывов)</span>
            </div>

            <div class="product__price">
                <span class="current-price"><?= View::formatPrice($product['price']) ?></span>
                <?php if ($product['old_price'] && $product['old_price'] > $product['price']): ?>
                <span class="old-price"><?= View::formatPrice($product['old_price']) ?></span>
                <span class="discount-badge">
                    -<?= round(($product['old_price'] - $product['price']) / $product['old_price'] * 100) ?>%
                </span>
                <?php endif; ?>
            </div>

            <div class="stock-status <?php
                if ($product['stock_quantity'] > 10) echo 'in-stock';
                elseif ($product['stock_quantity'] > 0) echo 'low-stock';
                else echo 'out-of-stock';
            ?>">
                <?php
                if ($product['stock_quantity'] > 10) {
                    echo '<i class="fas fa-check-circle"></i> В наличии';
                } elseif ($product['stock_quantity'] > 0) {
                    echo '<i class="fas fa-exclamation-circle"></i> Осталось мало: ' . $product['stock_quantity'] . ' шт.';
                } else {
                    echo '<i class="fas fa-times-circle"></i> Нет в наличии';
                }
                ?>
            </div>

            <div class="product-attributes">
                <div class="attribute-row">
                    <span class="attribute-label">Артикул:</span>
                    <span class="attribute-value"><?= $product['sku'] ?? 'N/A' ?></span>
                </div>
                <div class="attribute-row">
                    <span class="attribute-label">Категория:</span>
                    <span class="attribute-value"><?= htmlspecialchars($product['category_name'] ?? 'Без категории') ?></span>
                </div>
                <div class="attribute-row">
                    <span class="attribute-label">На складе:</span>
                    <span class="attribute-value"><?= $product['stock_quantity'] ?> шт.</span>
                </div>
            </div>

            <p class="product__description">
                <?= nl2br(htmlspecialchars($product['description'] ?? 'Описание отсутствует')) ?>
            </p>

            <?php if (!$isAdmin && $product['stock_quantity'] > 0): ?>
            <div class="product__purchase">
                <div class="product__quantity">
                    <button class="product__qty-btn minus">-</button>
                    <input type="number" class="product__qty-value" value="1" min="1" max="<?= $product['stock_quantity'] ?>">
                    <button class="product__qty-btn plus">+</button>
                </div>

                <div class="product__actions">
                    <button class="btn primary-btn" onclick="addToCart(<?= $product['product_id'] ?>)">
                        <i class="fas fa-shopping-cart"></i> В корзину
                    </button>
                    <button class="btn secondary-btn" onclick="buyNow(<?= $product['product_id'] ?>)">
                        <i class="fas fa-bolt"></i> Купить сейчас
                    </button>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($isAdmin): ?>
            <div style="margin-top: 20px;">
                <a href="/admin/products/edit/<?= $product['product_id'] ?>" class="btn" style="background: #ffc107; color: #333;">
                    <i class="fas fa-edit"></i> Редактировать
                </a>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if (!empty($similarProducts)): ?>
    <section class="similar-products">
        <h2>Похожие товары</h2>
        <div class="products-grid">
            <?php foreach ($similarProducts as $similar): ?>
            <?php 
            $simImageUrl = $similar['image_url'] ?? '';
            if (empty($simImageUrl)) {
                $simImageUrl = '/assets/images/1.jpg';
            } elseif (strpos($simImageUrl, '/img2/') === 0) {
                $simImageUrl = str_replace('/img2/', '/assets/images/', $simImageUrl);
            } elseif (strpos($simImageUrl, 'img2/') === 0) {
                $simImageUrl = str_replace('img2/', '/assets/images/', $simImageUrl);
            }
            ?>
            <div class="product-card" onclick="window.location.href='/product/<?= $similar['product_id'] ?>'" style="cursor: pointer;">
                <img src="<?= htmlspecialchars($simImageUrl) ?>"
                     alt="<?= htmlspecialchars($similar['name']) ?>">
                <div class="product-info">
                    <h3 style="font-size: 16px; color: #453227;"><?= htmlspecialchars($similar['name']) ?></h3>
                    <p style="color: #617365; font-weight: bold;"><?= View::formatPrice($similar['price']) ?></p>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>

    <!-- Reviews Section -->
    <section class="product-reviews">
        <h2>Отзывы о товаре</h2>
        
        <div class="reviews-summary">
            <div class="reviews-summary-rating">
                <div class="rating-number"><?= number_format($product['rating'] ?? 0, 1) ?></div>
                <div class="rating-stars">
                    <?php
                    $avgRating = $product['rating'] ?? 0;
                    for ($i = 1; $i <= 5; $i++) {
                        $filled = $i <= round($avgRating);
                        echo '<span class="star ' . ($filled ? 'filled' : '') . '">★</span>';
                    }
                    ?>
                </div>
                <div class="rating-count">
                    Всего отзывов: <?= $product['review_count'] ?? 0 ?>
                </div>
            </div>
        </div>

        <?php if (!$isAdmin): ?>
            <?php if ($userReview): ?>
                <!-- User has already reviewed, show edit form -->
                <?php 
                $productId = $product['product_id'];
                include __DIR__ . '/_review_form.php'; 
                ?>
            <?php else: ?>
                <!-- User hasn't reviewed yet, show new review form -->
                <?php 
                $productId = $product['product_id'];
                $userReview = null;
                include __DIR__ . '/_review_form.php'; 
                ?>
            <?php endif; ?>
        <?php endif; ?>

        <!-- Reviews List -->
        <?php 
        $currentUserId = $user['id'] ?? null;
        include __DIR__ . '/_reviews_list.php'; 
        ?>
    </section>
</main>

<script>
$(document).ready(function() {
    $('.product__qty-btn.plus').click(function() {
        const $input = $('.product__qty-value');
        let value = parseInt($input.val());
        let max = parseInt($input.attr('max'));
        if (value < max) $input.val(value + 1);
    });

    $('.product__qty-btn.minus').click(function() {
        const $input = $('.product__qty-value');
        let value = parseInt($input.val());
        if (value > 1) $input.val(value - 1);
    });
});

function addToCart(productId) {
    const quantity = $('.product__qty-value').val();
    $.ajax({
        url: '/cart/add',
        method: 'POST',
        data: { product_id: productId, quantity: quantity },
        dataType: 'json',
        success: function(result) {
            if (result.success) {
                showNotification('Товар добавлен в корзину!');
                $('.cart-count').text(result.cart_count);
            } else {
                showNotification('Ошибка: ' + result.message, 'error');
            }
        }
    });
}

function buyNow(productId) {
    const quantity = $('.product__qty-value').val();
    $.ajax({
        url: '/cart/add',
        method: 'POST',
        data: { product_id: productId, quantity: quantity },
        success: function() {
            window.location.href = '/cart';
        }
    });
}

// Review functionality
$(document).ready(function() {
    // Submit review form
    $('#reviewForm').on('submit', function(e) {
        e.preventDefault();
        
        const rating = parseInt($('#ratingValue').val());
        if (rating < 1 || rating > 5) {
            $('#ratingError').text('Пожалуйста, выберите оценку от 1 до 5 звезд').addClass('show');
            return;
        }
        
        const formData = {
            product_id: $('input[name="product_id"]').val(),
            rating: rating,
            comment: $('#reviewComment').val().trim()
        };
        
        const reviewId = $('input[name="review_id"]').val();
        const url = reviewId ? `/reviews/${reviewId}` : '/reviews';
        const successMessage = reviewId ? 'Отзыв обновлен!' : 'Спасибо за ваш отзыв!';
        
        $('#submitReviewBtn').prop('disabled', true).text('Отправка...');
        
        $.ajax({
            url: url,
            method: 'POST',
            data: formData,
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    $('#formMessage')
                        .removeClass('error')
                        .addClass('success')
                        .text(successMessage)
                        .show();
                    
                    // Update product rating display
                    if (result.product_rating !== undefined) {
                        updateProductRating(result.product_rating, result.product_review_count);
                    }
                    
                    // Reload page after short delay to show updated reviews
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    $('#formMessage')
                        .removeClass('success')
                        .addClass('error')
                        .text(result.message || 'Произошла ошибка')
                        .show();
                    $('#submitReviewBtn').prop('disabled', false).html('<i class="fas fa-paper-plane"></i> Отправить отзыв');
                }
            },
            error: function() {
                $('#formMessage')
                    .removeClass('success')
                    .addClass('error')
                    .text('Ошибка соединения с сервером')
                    .show();
                $('#submitReviewBtn').prop('disabled', false).html('<i class="fas fa-paper-plane"></i> Отправить отзыв');
            }
        });
    });
    
    // Edit review button
    $(document).on('click', '.btn-edit-review', function() {
        const reviewId = $(this).data('review-id');
        const rating = $(this).data('rating');
        const comment = $(this).data('comment');
        
        // Scroll to form
        $('html, body').animate({
            scrollTop: $('#reviewFormContainer').offset().top - 100
        }, 500);
        
        // Set form values
        $('#ratingValue').val(rating);
        $('#reviewComment').val(comment);
        
        // Update star display
        $('.star-input').each(function(index) {
            if (index < rating) {
                $(this).addClass('selected');
            } else {
                $(this).removeClass('selected');
            }
        });
        
        // Update rating text
        const ratingTexts = {
            1: '1 из 5 - Плохо',
            2: '2 из 5 - Неудовлетворительно',
            3: '3 из 5 - Нормально',
            4: '4 из 5 - Хорошо',
            5: '5 из 5 - Отлично!'
        };
        $('#ratingText').text(ratingTexts[rating]);
        
        // Focus on comment field
        $('#reviewComment').focus();
    });
    
    // Delete review button
    $(document).on('click', '.btn-delete-review', function() {
        if (!confirm('Вы уверены, что хотите удалить этот отзыв?')) {
            return;
        }
        
        const reviewId = $(this).data('review-id');
        const $reviewItem = $(this).closest('.review-item');
        
        $.ajax({
            url: `/reviews/${reviewId}/delete`,
            method: 'POST',
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    showNotification('Отзыв удален');
                    
                    // Update product rating display
                    if (result.product_rating !== undefined) {
                        updateProductRating(result.product_rating, result.product_review_count);
                    }
                    
                    // Remove review item with animation
                    $reviewItem.fadeOut(400, function() {
                        $(this).remove();
                        
                        // Check if there are no more reviews
                        if ($('.review-item').length === 0) {
                            $('#reviewsList').html('<div class="no-reviews"><p>Пока нет отзывов об этом товаре. Будьте первым!</p></div>');
                        }
                    });
                } else {
                    showNotification(result.message || 'Ошибка при удалении отзыва', 'error');
                }
            },
            error: function() {
                showNotification('Ошибка соединения с сервером', 'error');
            }
        });
    });
    
    // Cancel edit button
    $(document).on('click', '#cancelEditBtn', function() {
        location.reload();
    });
    
    function updateProductRating(rating, count) {
        $('.rating-number').text(parseFloat(rating).toFixed(1));
        $('.rating-count').text('Всего отзывов: ' + count);
        
        // Update stars in main product info
        const $productRating = $('.product__rating .stars');
        $productRating.empty();
        for (let i = 1; i <= 5; i++) {
            const filled = i <= Math.round(rating);
            $productRating.append(`<span class="star ${filled ? 'filled' : ''}">★</span>`);
        }
        $('.product__rating span:last-child').text(`(${count} отзывов)`);
        
        // Update stars in reviews summary
        const $summaryStars = $('.reviews-summary-rating .rating-stars');
        $summaryStars.empty();
        for (let i = 1; i <= 5; i++) {
            const filled = i <= Math.round(rating);
            $summaryStars.append(`<span class="star ${filled ? 'filled' : ''}">★</span>`);
        }
    }
});
</script>
