<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/cart.php';

$slug = trim($_GET['slug'] ?? '');

if ($slug === '') {
    redirect(BASE_URL . '/public/shop.php');
}

$stmt = $pdo->prepare("
    SELECT p.*, c.name AS category_name, c.slug AS category_slug
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    WHERE p.slug = ? AND p.status = 'active'
    LIMIT 1
");
$stmt->execute([$slug]);
$product = $stmt->fetch();

if (!$product) {
    http_response_code(404);
    $pageTitle = 'Product Not Found | LOVE-U Essentials';
    require_once __DIR__ . '/includes/header.php';
?>
    <section class="section">
        <div class="container empty-state">
            <h1>Product not found</h1>
            <p>The product you are looking for is unavailable or has been removed.</p>
            <a href="<?= e(BASE_URL); ?>/public/shop.php" class="btn">Back to Shop</a>
        </div>
    </section>
<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

$reviewSuccess = '';
$reviewError = '';

$currentCustomer = function_exists('customer') ? customer() : null;
$productNotice = '';

if (isset($_GET['variation']) && $_GET['variation'] === 'invalid') {
    $productNotice = 'Please select a valid product option.';
}

if (isset($_GET['variation']) && $_GET['variation'] === 'out_of_stock') {
    $productNotice = 'The selected option is currently out of stock.';
}

if (isset($_GET['stock']) && $_GET['stock'] === 'out') {
    $productNotice = 'This product is currently out of stock.';
}

if (is_post() && ($_POST['product_action'] ?? '') === 'submit_review') {
    if (!$currentCustomer) {
        $reviewError = 'Please login before submitting a review.';
    } elseif (!verify_csrf()) {
        $reviewError = 'Invalid request. Please refresh and try again.';
    } else {
        $rating = (int) ($_POST['rating'] ?? 0);
        $reviewTitle = trim($_POST['review_title'] ?? '');
        $reviewText = trim($_POST['review_text'] ?? '');

        if ($rating < 1 || $rating > 5) {
            $reviewError = 'Please select a rating from 1 to 5.';
        } elseif ($reviewText === '') {
            $reviewError = 'Please write your review.';
        } else {
            $stmt = $pdo->prepare("
                SELECT oi.order_id
                FROM order_items oi
                INNER JOIN orders o ON oi.order_id = o.id
                WHERE oi.product_id = ?
                  AND o.customer_id = ?
                  AND o.payment_status = 'paid'
                ORDER BY o.id DESC
                LIMIT 1
            ");
            $stmt->execute([$product['id'], $currentCustomer['id']]);
            $verifiedOrder = $stmt->fetch();

            $verifiedPurchase = $verifiedOrder ? 1 : 0;
            $orderId = $verifiedOrder['order_id'] ?? null;

            $stmt = $pdo->prepare("
                SELECT id
                FROM reviews
                WHERE product_id = ?
                  AND customer_id = ?
                LIMIT 1
            ");
            $stmt->execute([$product['id'], $currentCustomer['id']]);
            $existingReview = $stmt->fetch();

            if ($existingReview) {
                $reviewError = 'You have already submitted a review for this product.';
            } else {
                try {
                    $pdo->beginTransaction();

                    $stmt = $pdo->prepare("
                        INSERT INTO reviews (
                            product_id,
                            customer_id,
                            order_id,
                            rating,
                            review_title,
                            review_text,
                            verified_purchase,
                            status
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')
                    ");

                    $stmt->execute([
                        $product['id'],
                        $currentCustomer['id'],
                        $orderId,
                        $rating,
                        $reviewTitle !== '' ? $reviewTitle : null,
                        $reviewText,
                        $verifiedPurchase
                    ]);

                    $reviewId = (int) $pdo->lastInsertId();

                    if (!empty($_FILES['review_media']['name'][0])) {
                        $uploadDir = __DIR__ . '/../uploads/reviews/';

                        if (!is_dir($uploadDir)) {
                            mkdir($uploadDir, 0777, true);
                        }

                        $allowedTypes = [
                            'image/jpeg' => 'image',
                            'image/png' => 'image',
                            'image/webp' => 'image',
                            'video/mp4' => 'video',
                            'video/webm' => 'video',
                        ];

                        $fileCount = count($_FILES['review_media']['name']);

                        for ($i = 0; $i < $fileCount; $i++) {
                            if ($_FILES['review_media']['error'][$i] !== UPLOAD_ERR_OK) {
                                continue;
                            }

                            $tmpName = $_FILES['review_media']['tmp_name'][$i];
                            $mimeType = mime_content_type($tmpName);

                            if (!isset($allowedTypes[$mimeType])) {
                                continue;
                            }

                            $originalName = $_FILES['review_media']['name'][$i];
                            $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
                            $fileName = 'review-' . $reviewId . '-' . time() . '-' . bin2hex(random_bytes(4)) . '.' . $extension;
                            $targetPath = $uploadDir . $fileName;

                            if (move_uploaded_file($tmpName, $targetPath)) {
                                $mediaPath = 'uploads/reviews/' . $fileName;
                                $mediaType = $allowedTypes[$mimeType];

                                $stmtMedia = $pdo->prepare("
                                    INSERT INTO review_media (
                                        review_id,
                                        media_type,
                                        media_path
                                    ) VALUES (?, ?, ?)
                                ");

                                $stmtMedia->execute([
                                    $reviewId,
                                    $mediaType,
                                    $mediaPath
                                ]);
                            }
                        }
                    }

                    $pdo->commit();

                    redirect(BASE_URL . '/public/product.php?slug=' . urlencode($product['slug']) . '&review=submitted');
                } catch (Exception $e) {
                    if ($pdo->inTransaction()) {
                        $pdo->rollBack();
                    }

                    $reviewError = 'Review could not be submitted. Please try again.';
                }
            }
        }
    }
}

if (isset($_GET['review']) && $_GET['review'] === 'submitted') {
    $reviewSuccess = 'Thank you. Your review has been submitted and is waiting for approval.';
}

$stmt = $pdo->prepare("
    SELECT *
    FROM product_images
    WHERE product_id = ?
    ORDER BY is_primary DESC, sort_order ASC, id ASC
");
$stmt->execute([$product['id']]);
$images = $stmt->fetchAll();

$stmt = $pdo->prepare("
    SELECT *
    FROM product_variations
    WHERE product_id = ?
      AND status = 'active'
    ORDER BY id ASC
");
$stmt->execute([$product['id']]);
$variations = $stmt->fetchAll();

$hasVariations = !empty($variations);

$variationTotalStock = 0;
$availableVariationCount = 0;

if ($hasVariations) {
    foreach ($variations as $variation) {
        $variationStock = (int) $variation['stock_quantity'];
        $variationTotalStock += $variationStock;

        if ($variationStock > 0) {
            $availableVariationCount++;
        }
    }
}

$hasVariations = !empty($variations);


$stmt = $pdo->prepare("
    SELECT r.*,
           c.first_name,
           c.last_name
    FROM reviews r
    LEFT JOIN customers c ON r.customer_id = c.id
    WHERE r.product_id = ?
      AND r.status = 'approved'
    ORDER BY r.id DESC
");
$stmt->execute([$product['id']]);
$reviews = $stmt->fetchAll();

$reviewMedia = [];

if ($reviews) {
    $reviewIds = array_column($reviews, 'id');
    $placeholders = implode(',', array_fill(0, count($reviewIds), '?'));

    $stmt = $pdo->prepare("
        SELECT *
        FROM review_media
        WHERE review_id IN ($placeholders)
        ORDER BY id ASC
    ");
    $stmt->execute($reviewIds);
    $mediaRows = $stmt->fetchAll();

    foreach ($mediaRows as $media) {
        $reviewMedia[$media['review_id']][] = $media;
    }
}

$reviewCount = count($reviews);
$averageRating = 0;

if ($reviewCount > 0) {
    $ratingTotal = 0;

    foreach ($reviews as $review) {
        $ratingTotal += (int) $review['rating'];
    }

    $averageRating = round($ratingTotal / $reviewCount, 1);
}

$userHasReviewed = false;

if ($currentCustomer) {
    $stmt = $pdo->prepare("
        SELECT id
        FROM reviews
        WHERE product_id = ?
          AND customer_id = ?
        LIMIT 1
    ");
    $stmt->execute([$product['id'], $currentCustomer['id']]);
    $userHasReviewed = (bool) $stmt->fetch();
}

$stmt = $pdo->prepare("
    SELECT p.*,
        (
            SELECT image_path
            FROM product_images
            WHERE product_id = p.id
            ORDER BY is_primary DESC, sort_order ASC, id ASC
            LIMIT 1
        ) AS primary_image
    FROM products p
    WHERE p.status = 'active'
      AND p.id != ?
      AND (
            p.category_id = ?
            OR p.is_best_seller = 1
          )
    ORDER BY p.is_best_seller DESC, p.id DESC
    LIMIT 4
");
$stmt->execute([$product['id'], $product['category_id']]);
$relatedProducts = $stmt->fetchAll();

$pageTitle = !empty($product['seo_title'])
    ? $product['seo_title']
    : $product['product_name'] . ' | LOVE-U Essentials';

$pageDescription = !empty($product['seo_description'])
    ? $product['seo_description']
    : (!empty($product['short_description']) ? $product['short_description'] : 'Shop ' . $product['product_name'] . ' from LOVE-U Essentials.');

function stock_label($status)
{
    $labels = [
        'in_stock' => 'In Stock',
        'only_few_left' => 'Only Few Left',
        'out_of_stock' => 'Out of Stock',
        'back_in_stock' => 'Back In Stock',
    ];

    return $labels[$status] ?? 'In Stock';
}

function rating_stars($rating)
{
    $rating = (int) $rating;
    $output = '';

    for ($i = 1; $i <= 5; $i++) {
        $output .= $i <= $rating ? '★' : '☆';
    }

    return $output;
}

function render_related_product_card($product)
{
?>
    <a href="<?= e(BASE_URL); ?>/public/product.php?slug=<?= e($product['slug']); ?>" class="product-card lue-related-product-card">
        <?php if (!empty($product['badge'])): ?>
            <div class="badge"><?= e($product['badge']); ?></div>
        <?php endif; ?>

        <div class="product-image lue-related-product-image">
            <?php if (!empty($product['primary_image'])): ?>
                <img src="<?= e(BASE_URL . '/' . $product['primary_image']); ?>" alt="<?= e($product['product_name']); ?>">
            <?php else: ?>
                <div class="product-placeholder"><?= e($product['product_name']); ?></div>
            <?php endif; ?>
        </div>

        <div class="lue-related-product-body">
            <h3 class="product-title"><?= e($product['product_name']); ?></h3>

            <div class="product-price">
                <?php if (!empty($product['sale_price'])): ?>
                    <span class="old-price"><?= e(format_price($product['regular_price'], $product['currency_code'])); ?></span>
                    <span class="sale-price"><?= e(format_price($product['sale_price'], $product['currency_code'])); ?></span>
                <?php else: ?>
                    <?= e(format_price($product['regular_price'], $product['currency_code'])); ?>
                <?php endif; ?>
            </div>

            <span class="lue-related-view">View Product</span>
        </div>
    </a>
<?php
}

require_once __DIR__ . '/includes/header.php';

$mainImage = $images[0]['image_path'] ?? '';
?>

<section class="lue-product-page">
    <div class="lue-product-orb lue-product-orb-one"></div>
    <div class="lue-product-orb lue-product-orb-two"></div>

    <div class="container">
        <div class="lue-product-breadcrumb">
            <a href="<?= e(BASE_URL); ?>/public/index.php">Home</a>
            <span>/</span>
            <a href="<?= e(BASE_URL); ?>/public/shop.php">Shop</a>

            <?php if (!empty($product['category_slug'])): ?>
                <span>/</span>
                <a href="<?= e(BASE_URL); ?>/public/shop.php?category=<?= e($product['category_slug']); ?>">
                    <?= e($product['category_name']); ?>
                </a>
            <?php endif; ?>
        </div>

        <div class="lue-product-grid">
            <div class="lue-product-gallery">
                <div class="lue-product-main-image">
                    <?php if ($mainImage): ?>
                        <img id="mainProductImage" src="<?= e(BASE_URL . '/' . $mainImage); ?>" alt="<?= e($product['product_name']); ?>">
                    <?php else: ?>
                        <div class="product-placeholder"><?= e($product['product_name']); ?></div>
                    <?php endif; ?>
                </div>

                <?php if (count($images) > 1): ?>
                    <div class="lue-product-thumbs">
                        <?php foreach ($images as $index => $image): ?>
                            <button
                                class="lue-product-thumb <?= $index === 0 ? 'active' : ''; ?>"
                                type="button"
                                data-image="<?= e(BASE_URL . '/' . $image['image_path']); ?>"
                            >
                                <img src="<?= e(BASE_URL . '/' . $image['image_path']); ?>" alt="<?= e($image['alt_text'] ?: $product['product_name']); ?>">
                            </button>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <div class="lue-product-info">
                <div class="lue-product-info-card">
                    <div class="lue-product-topline">
                        <?php if (!empty($product['badge'])): ?>
                            <span class="lue-product-badge"><?= e($product['badge']); ?></span>
                        <?php endif; ?>

                        <?php if ($reviewCount > 0): ?>
                            <a href="#productReviews" class="lue-product-rating">
                                <span><?= e(rating_stars((int) round($averageRating))); ?></span>
                                <strong><?= e($averageRating); ?>/5 · <?= e($reviewCount); ?> review<?= $reviewCount === 1 ? '' : 's'; ?></strong>
                            </a>
                        <?php else: ?>
                            <a href="#productReviews" class="lue-product-rating">
                                <span>☆☆☆☆☆</span>
                                <strong>No reviews yet</strong>
                            </a>
                        <?php endif; ?>
                    </div>

                    <h1><?= e($product['product_name']); ?></h1>

                    <?php if ($productNotice): ?>
                        <div class="lue-product-alert lue-product-alert-error">
                            <?= e($productNotice); ?>
                        </div>
                    <?php endif; ?>

                    <?php
                    $basePrice = !empty($product['sale_price'])
                        ? (float) $product['sale_price']
                        : (float) $product['regular_price'];
                    ?>

                    <div class="lue-product-price" id="productPriceDisplay">
                        <?php if (!empty($product['sale_price'])): ?>
                            <span class="old-price"><?= e(format_price($product['regular_price'], $product['currency_code'])); ?></span>
                            <strong><?= e(format_price($basePrice, $product['currency_code'])); ?></strong>
                        <?php else: ?>
                            <strong><?= e(format_price($basePrice, $product['currency_code'])); ?></strong>
                        <?php endif; ?>
                    </div>

                    <?php if (!empty($product['short_description'])): ?>
                        <div class="lue-product-short">
                            <?= nl2br(e($product['short_description'])); ?>
                        </div>
                    <?php endif; ?>

                    <div class="lue-product-stock">
                        <?php if ($hasVariations): ?>
                            <?php if ($variationTotalStock > 0): ?>
                                <span class="lue-stock-dot"></span>
                                In Stock · <?= e($variationTotalStock); ?> available across <?= e($availableVariationCount); ?> option<?= $availableVariationCount === 1 ? '' : 's'; ?>
                            <?php else: ?>
                                <span class="lue-stock-dot lue-stock-dot-error"></span>
                                Out of Stock
                            <?php endif; ?>
                        <?php else: ?>
                            <?php if ($product['stock_status'] === 'out_of_stock'): ?>
                                <span class="lue-stock-dot lue-stock-dot-error"></span>
                            <?php else: ?>
                                <span class="lue-stock-dot"></span>
                            <?php endif; ?>

                            <?= e(stock_label($product['stock_status'])); ?>

                            <?php if ((int) $product['stock_quantity'] > 0): ?>
                                · <?= e($product['stock_quantity']); ?> available
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>

                    <form class="lue-product-actions" method="POST" action="<?= e(BASE_URL); ?>/public/cart.php">
                        <input type="hidden" name="action" value="add">
                        <input type="hidden" name="product_id" value="<?= e($product['id']); ?>">

                        <?php if ($hasVariations): ?>
                            <div class="lue-variation-panel">
                                <div class="lue-variation-head">
                                    <div>
                                        <span>Choose Option</span>
                                        <h3><?= e($variations[0]['variation_name']); ?></h3>
                                    </div>

                                    <small><?= e($availableVariationCount); ?> available</small>
                                </div>

                                <div class="lue-variation-options">
                                    <?php foreach ($variations as $variation): ?>
                                        <?php
                                        $variationPrice = $basePrice + (float) $variation['price_adjustment'];
                                        $variationImage = !empty($variation['image_path'])
                                            ? BASE_URL . '/' . $variation['image_path']
                                            : '';
                                        ?>

                                        <label class="lue-variation-option <?= (int) $variation['stock_quantity'] <= 0 ? 'is-disabled' : ''; ?>">
                                            <input
                                                type="radio"
                                                name="variation_id"
                                                value="<?= e($variation['id']); ?>"
                                                required
                                                data-price="<?= e(format_price($variationPrice, $product['currency_code'])); ?>"
                                                data-image="<?= e($variationImage); ?>"
                                                data-stock="<?= e((int) $variation['stock_quantity']); ?>"
                                                <?= (int) $variation['stock_quantity'] <= 0 ? 'disabled' : ''; ?>
                                            >

                                            <?php if (!empty($variation['color_code'])): ?>
                                                <span
                                                    class="lue-variation-swatch"
                                                    style="background: <?= e($variation['color_code']); ?>;"
                                                ></span>
                                            <?php endif; ?>

                                            <span class="lue-variation-copy">
                                                <strong><?= e($variation['variation_value']); ?></strong>

                                                <?php if ((float) $variation['price_adjustment'] > 0): ?>
                                                    <small>+<?= e(format_price($variation['price_adjustment'], $product['currency_code'])); ?></small>
                                                <?php endif; ?>

                                                <?php if ((int) $variation['stock_quantity'] <= 0): ?>
                                                    <small>Out of stock</small>
                                                <?php else: ?>
                                                    <small><?= e((int) $variation['stock_quantity']); ?> left</small>
                                                <?php endif; ?>
                                            </span>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <div class="lue-product-purchase-row">
                            <?php
                            $qtyMax = $hasVariations
                                ? max(1, $variationTotalStock)
                                : max(1, (int) $product['stock_quantity']);
                            ?>

                            <div class="lue-qty-control lue-product-qty" data-max="<?= e($qtyMax); ?>">
                                <button type="button" class="lue-qty-btn" data-qty-action="decrease">−</button>

                                <input
                                    type="number"
                                    name="quantity"
                                    value="1"
                                    min="1"
                                    max="<?= e($qtyMax); ?>"
                                    class="lue-qty-input"
                                    id="productQuantityInput"
                                >

                                <button type="button" class="lue-qty-btn" data-qty-action="increase">+</button>
                            </div>

                            <?php if ($hasVariations && $variationTotalStock <= 0): ?>
                                <button type="button" class="btn lue-product-cart-btn" disabled>Out of Stock</button>
                            <?php elseif (!$hasVariations && $product['stock_status'] === 'out_of_stock'): ?>
                                <button type="button" class="btn lue-product-cart-btn" disabled>Out of Stock</button>
                            <?php else: ?>
                                <button type="submit" class="btn lue-product-cart-btn">Add to Cart</button>
                            <?php endif; ?>
                        </div>

                        <a href="<?= e(BASE_URL); ?>/public/wishlist.php?add=<?= e($product['id']); ?>" class="lue-product-wishlist-btn">
                            Add to Wishlist
                        </a>
                    </form>

                    <div class="lue-product-trust">
                        <span>Secure checkout</span>
                        <span>Delivery calculated at checkout</span>
                        <span>Gift-ready ordering</span>
                    </div>
                </div>

                <div class="lue-product-accordion">
                    <?php if (!empty($product['description'])): ?>
                        <details class="lue-accordion-item" open>
                            <summary>Description</summary>
                            <p><?= nl2br(e($product['description'])); ?></p>
                        </details>
                    <?php endif; ?>

                    <?php if (!empty($product['ingredients'])): ?>
                        <details class="lue-accordion-item">
                            <summary>Ingredients / Materials</summary>
                            <p><?= nl2br(e($product['ingredients'])); ?></p>
                        </details>
                    <?php endif; ?>

                    <?php if (!empty($product['how_to_use'])): ?>
                        <details class="lue-accordion-item">
                            <summary>How To Use</summary>
                            <p><?= nl2br(e($product['how_to_use'])); ?></p>
                        </details>
                    <?php endif; ?>

                    <?php if (!empty($product['shipping_return_info'])): ?>
                        <details class="lue-accordion-item">
                            <summary>Shipping & Returns</summary>
                            <p><?= nl2br(e($product['shipping_return_info'])); ?></p>
                        </details>
                    <?php else: ?>
                        <details class="lue-accordion-item">
                            <summary>Shipping & Returns</summary>
                            <p>Shipping options and delivery messages will be shown during checkout based on your region.</p>
                        </details>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</section>

<section class="lue-review-section" id="productReviews">
    <div class="container">
        <div class="lue-review-head">
            <div>
                <div class="eyebrow">Customer Reviews</div>
                <h2>Real thoughts from LOVE-U customers</h2>
                <p>
                    <?= $reviewCount > 0
                        ? e($averageRating . '/5 average rating from ' . $reviewCount . ' approved review' . ($reviewCount === 1 ? '' : 's') . '.')
                        : 'No approved reviews yet. Be the first to review this product.'; ?>
                </p>
            </div>

            <div class="lue-review-score">
                <span><?= $reviewCount > 0 ? e($averageRating) : '0.0'; ?></span>
                <strong><?= $reviewCount > 0 ? e(rating_stars((int) round($averageRating))) : '☆☆☆☆☆'; ?></strong>
                <small><?= e($reviewCount); ?> review<?= $reviewCount === 1 ? '' : 's'; ?></small>
            </div>
        </div>

        <?php if ($reviewSuccess): ?>
            <div class="lue-product-alert lue-product-alert-success"><?= e($reviewSuccess); ?></div>
        <?php endif; ?>

        <?php if ($reviewError): ?>
            <div class="lue-product-alert lue-product-alert-error"><?= e($reviewError); ?></div>
        <?php endif; ?>

        <div class="lue-review-layout">
            <div class="lue-review-list-panel">
                <div class="lue-review-panel-head">
                    <span>Approved Reviews</span>
                    <h3>What customers say</h3>
                </div>

                <?php if (!$reviews): ?>
                    <div class="lue-review-empty">
                        <span>No reviews yet</span>
                        <h3>Be the first to share your thoughts.</h3>
                        <p>Once reviews are approved by admin, they will appear here.</p>
                    </div>
                <?php else: ?>
                    <div class="lue-review-list">
                        <?php foreach ($reviews as $review): ?>
                            <article class="lue-review-card">
                                <div class="lue-review-stars"><?= e(rating_stars($review['rating'])); ?></div>

                                <?php if (!empty($review['review_title'])): ?>
                                    <h3><?= e($review['review_title']); ?></h3>
                                <?php endif; ?>

                                <p><?= nl2br(e($review['review_text'])); ?></p>

                                <div class="lue-review-meta">
                                    <strong><?= e(trim(($review['first_name'] ?? 'Customer') . ' ' . ($review['last_name'] ?? ''))); ?></strong>

                                    <?php if (!empty($review['verified_purchase'])): ?>
                                        <span>Verified Purchase</span>
                                    <?php endif; ?>

                                    <small><?= e(date('d M Y', strtotime($review['created_at']))); ?></small>
                                </div>

                                <?php if (!empty($reviewMedia[$review['id']])): ?>
                                    <div class="lue-review-media">
                                        <?php foreach ($reviewMedia[$review['id']] as $media): ?>
                                            <?php if ($media['media_type'] === 'image'): ?>
                                                <a href="<?= e(BASE_URL . '/' . $media['media_path']); ?>" target="_blank">
                                                    <img src="<?= e(BASE_URL . '/' . $media['media_path']); ?>" alt="Review media">
                                                </a>
                                            <?php else: ?>
                                                <a href="<?= e(BASE_URL . '/' . $media['media_path']); ?>" target="_blank" class="lue-review-video-link">
                                                    View Video
                                                </a>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </article>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <aside class="lue-review-form-panel">
                <div class="lue-review-panel-head">
                    <span>Share Feedback</span>
                    <h3>Write a Review</h3>
                </div>

                <?php if (!$currentCustomer): ?>
                    <p class="lue-review-login-text">
                        Please login to submit a product review.
                    </p>

                    <a href="<?= e(BASE_URL); ?>/public/login.php" class="btn lue-review-login-btn">Login to Review</a>
                <?php elseif ($userHasReviewed): ?>
                    <p class="lue-review-login-text">
                        You have already submitted a review for this product.
                    </p>
                <?php else: ?>
                    <form method="POST" enctype="multipart/form-data" class="lue-review-form">
                        <?= csrf_field(); ?>
                        <input type="hidden" name="product_action" value="submit_review">

                        <div class="lue-review-field">
                            <label>Rating *</label>
                            <select name="rating" required>
                                <option value="">Select Rating</option>
                                <option value="5">5 Stars</option>
                                <option value="4">4 Stars</option>
                                <option value="3">3 Stars</option>
                                <option value="2">2 Stars</option>
                                <option value="1">1 Star</option>
                            </select>
                        </div>

                        <div class="lue-review-field">
                            <label>Review Title</label>
                            <input type="text" name="review_title" maxlength="180" placeholder="Short title">
                        </div>

                        <div class="lue-review-field">
                            <label>Review *</label>
                            <textarea name="review_text" required placeholder="Write your experience..."></textarea>
                        </div>

                        <div class="lue-review-field">
                            <label>Photos / Videos</label>
                            <input type="file" name="review_media[]" accept="image/jpeg,image/png,image/webp,video/mp4,video/webm" multiple>
                            <small>Accepted: JPG, PNG, WEBP, MP4, WEBM</small>
                        </div>

                        <button type="submit" class="btn lue-review-submit-btn">Submit Review</button>

                        <p class="lue-review-note">
                            Reviews are shown after admin approval.
                        </p>
                    </form>
                <?php endif; ?>
            </aside>
        </div>
    </div>
</section>

<?php if ($relatedProducts): ?>
    <section class="lue-related-section">
        <div class="container">
            <div class="section-head">
                <div>
                    <div class="eyebrow">You may also like</div>
                    <h2>Related essentials</h2>
                    <p>Continue exploring products that pair beautifully with your selection.</p>
                </div>
            </div>

            <div class="product-grid lue-related-grid">
                <?php foreach ($relatedProducts as $related): ?>
                    <?php render_related_product_card($related); ?>
                <?php endforeach; ?>
            </div>
        </div>
    </section>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const thumbs = document.querySelectorAll('.lue-product-thumb');
    const mainImage = document.getElementById('mainProductImage');

    thumbs.forEach(function (thumb) {
        thumb.addEventListener('click', function () {
            const image = thumb.getAttribute('data-image');

            if (mainImage && image) {
                mainImage.src = image;
            }

            thumbs.forEach(function (item) {
                item.classList.remove('active');
            });

            thumb.classList.add('active');
        });
    });

    const variationInputs = document.querySelectorAll('input[name="variation_id"]');
    const priceDisplay = document.getElementById('productPriceDisplay');
    const quantityInput = document.getElementById('productQuantityInput');
    const qtyControl = document.querySelector('.lue-product-qty');
    const mainProductImage = document.getElementById('mainProductImage');

    variationInputs.forEach(function (input) {
        input.addEventListener('change', function () {
            const price = input.dataset.price;
            const image = input.dataset.image;
            const stock = parseInt(input.dataset.stock || '1', 10);

            if (price && priceDisplay) {
                priceDisplay.innerHTML = '<strong>' + price + '</strong>';
            }

            if (image && mainProductImage) {
                mainProductImage.src = image;
            }

            if (quantityInput) {
                quantityInput.max = Math.max(1, stock);
                quantityInput.value = 1;
            }

            if (qtyControl) {
                qtyControl.dataset.max = Math.max(1, stock);
            }
        });
    });
});
</script>

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