<?php
/**
 * Single Product Template
 * 
 * Available variables: $atts (shortcode attributes with id or sku)
 */

if (!defined('ABSPATH')) {
    exit;
}

global $wpdb;

$table = $wpdb->prefix . 'instinctor_products';
$product = null;

if (!empty($atts['id'])) {
    // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL -- $table is the plugin's own \$wpdb->prefix-prefixed table name; table identifiers cannot be bound via prepare; the id/sku VALUES are bound via %d/%s placeholders
    $product = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM $table WHERE id = %d AND status = 'published'",
        intval($atts['id'])
    ));
    // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL
} elseif (!empty($atts['sku'])) {
    // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL -- $table is the plugin's own \$wpdb->prefix-prefixed table name; table identifiers cannot be bound via prepare; the id/sku VALUES are bound via %d/%s placeholders
    $product = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM $table WHERE sku = %s AND status = 'published'",
        sanitize_text_field($atts['sku'])
    ));
    // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL
}

if (!$product) {
    echo '<p class="instinctor-no-products">' . esc_html__('Product not found.', 'instinctor') . '</p>';
    return;
}

$image_url = $product->featured_image ? wp_get_attachment_image_url($product->featured_image, 'large') : '';
$gallery_images = !empty($product->gallery_images) ? json_decode($product->gallery_images, true) : [];
$price = floatval($product->price);
$sale_price = $product->sale_price ? floatval($product->sale_price) : null;
// Only consider it a "sale" if BOTH prices exist and sale < regular
$has_sale = $sale_price && $price > 0 && $sale_price < $price;
// Effective price: sale if on sale, regular if exists, otherwise sale_price
$display_price = $has_sale ? $sale_price : ($price > 0 ? $price : ($sale_price ?: 0));
$currency_symbol = '$';
$api_url = rest_url('instinctor/v1/');
$nonce = wp_create_nonce('wp_rest');

// Currency service for price formatting
$currentCurrency = \Instinctor\Services\CurrencyService::getCurrentCurrency();

// Get categories
$categories = \Instinctor\Services\CategoryService::getProductCategories($product->id);

// Check if product is bookable
$productMeta = !empty($product->meta) ? json_decode($product->meta, true) : [];
$isBookable = !empty($productMeta['is_bookable']);
$bookingDuration = $productMeta['booking_duration'] ?? 60;

// Get booking settings for min date calculation
// phpcs:disable WordPress.DateTime.RestrictedFunctions -- date() for local-timezone booking date math, gmdate would force UTC
$bookingMinDate = date('Y-m-d');
// phpcs:enable WordPress.DateTime.RestrictedFunctions
if ($isBookable) {
    $bookingSettings = \Instinctor\Services\BookingService::instance()->getSettings();
    $minAdvanceHours = $bookingSettings['min_advance'] ?? 24;
    // phpcs:disable WordPress.DateTime.RestrictedFunctions -- date() for local-timezone booking date math, gmdate would force UTC
    $bookingMinDate = date('Y-m-d', strtotime('+' . $minAdvanceHours . ' hours'));
    // phpcs:enable WordPress.DateTime.RestrictedFunctions
    // phpcs:disable WordPress.DateTime.RestrictedFunctions -- date() for local-timezone booking date math, gmdate would force UTC
    $bookingMaxDate = date('Y-m-d', strtotime('+' . ($bookingSettings['max_advance'] ?? 60) . ' days'));
    // phpcs:enable WordPress.DateTime.RestrictedFunctions
}

// Get variations if product is variable
$variations = [];
$hasVariations = false;
$priceRange = null;
$attributes = [];

if ($product->product_type === 'variable') {
    $variations = \Instinctor\Services\VariationService::getProductVariations($product->id);
    $hasVariations = !empty($variations);
    
    if ($hasVariations) {
        // Get price range
        $priceRange = \Instinctor\Services\VariationService::getPriceRange($product->id);
        
        // Get all unique attributes
        foreach ($variations as $var) {
            $varAttrs = json_decode($var->attributes, true) ?: [];
            foreach ($varAttrs as $name => $value) {
                if (!isset($attributes[$name])) {
                    $attributes[$name] = [];
                }
                if (!in_array($value, $attributes[$name])) {
                    $attributes[$name][] = $value;
                }
            }
        }
    }
}

// Get related products
$relatedProducts = \Instinctor\Services\ProductRelationshipService::getRelated($product->id, 'related', 4);
if (empty($relatedProducts)) {
    $relatedProducts = \Instinctor\Services\ProductRelationshipService::getAutoRelated($product->id, 4);
}
?>

<div class="instinctor-single-product">
    <div class="instinctor-product-gallery">
        <div class="instinctor-main-image" id="main-product-image">
            <?php 
            // Product badges
            include INSTINCTOR_PLUGIN_DIR . 'templates/partials/product-badges.php';
            ?>
            
            <?php if ($image_url): ?>
                <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($product->name); ?>" id="main-img">
            <?php else: ?>
                <div class="instinctor-no-image"><?php esc_html_e('No image available', 'instinctor'); ?></div>
            <?php endif; ?>
        </div>
        
        <?php if (!empty($gallery_images) || $product->featured_image): ?>
        <div class="instinctor-gallery-thumbs">
            <?php if ($product->featured_image): 
                $thumbUrl = wp_get_attachment_image_url($product->featured_image, 'thumbnail');
            ?>
            <div class="instinctor-gallery-thumb active" data-full="<?php echo esc_url($image_url); ?>">
                <img src="<?php echo esc_url($thumbUrl); ?>" alt="">
            </div>
            <?php endif; ?>
            <?php foreach ($gallery_images as $imgId): 
                $thumbUrl = wp_get_attachment_image_url($imgId, 'thumbnail');
                $fullUrl = wp_get_attachment_image_url($imgId, 'large');
                if (!$thumbUrl) continue;
            ?>
            <div class="instinctor-gallery-thumb" data-full="<?php echo esc_url($fullUrl); ?>">
                <img src="<?php echo esc_url($thumbUrl); ?>" alt="">
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <div class="instinctor-product-details">
        <?php if (!empty($categories)): ?>
        <div class="instinctor-product-cats">
            <?php foreach ($categories as $prodCat): ?>
            <a href="<?php echo esc_url(add_query_arg('category', $prodCat->slug, \Instinctor\Services\PageService::resolveUrl('shop'))); ?>"><?php echo esc_html($prodCat->name); ?></a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        
        <h1><?php echo esc_html($product->name); ?></h1>
        
        <div class="instinctor-product-price" id="instinctor-product-price">
            <?php if ($hasVariations && $priceRange): ?>
                <?php 
                $convertedMin = \Instinctor\Services\CurrencyService::convertPrice($priceRange['min']);
                $convertedMax = \Instinctor\Services\CurrencyService::convertPrice($priceRange['max']);
                if ($priceRange['min'] === $priceRange['max']): ?>
                    <?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($convertedMin)); ?>
                <?php else: ?>
                    <span class="instinctor-price-range"><?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($convertedMin)); ?> - <?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($convertedMax)); ?></span>
                <?php endif; ?>
            <?php elseif ($has_sale): ?>
                <?php 
                // Use per-product pricing when available
                $displaySalePrice = \Instinctor\Services\CurrencyService::convertProductPrice($product, 'sale_price');
                $displayRegularPrice = \Instinctor\Services\CurrencyService::convertProductPrice($product, 'price');
                ?>
                <span class="instinctor-sale-price"><?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($displaySalePrice)); ?></span>
                <span class="instinctor-original-price"><?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($displayRegularPrice)); ?></span>
                <span class="instinctor-save-badge"><?php
                    /* translators: %s is the discount percentage */
                    printf(esc_html__('Save %s%%', 'instinctor'), intval(round((($price - $sale_price) / $price) * 100)));
                ?></span>
            <?php else: ?>
                <?php 
                // Use per-product pricing when available - use effective display_price
                // This handles case where only sale_price is set (no regular price)
                $effectivePrice = $price > 0 ? $price : ($sale_price ?: 0);
                $displayPrice = \Instinctor\Services\CurrencyService::convertPrice($effectivePrice);
                echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($displayPrice)); 
                ?>
            <?php endif; ?>
        </div>

        <?php if ($product->short_description): ?>
            <div class="instinctor-product-description">
                <?php echo wp_kses_post($product->short_description); ?>
            </div>
        <?php endif; ?>

        <?php if ($hasVariations): ?>
        <div class="instinctor-variation-selector" id="variation-selector">
            <?php foreach ($attributes as $attrName => $values): ?>
            <div class="instinctor-variation-attribute">
                <label><?php echo esc_html(ucfirst($attrName)); ?></label>
                <select class="instinctor-variation-select" data-attribute="<?php echo esc_attr($attrName); ?>">
                    <option value=""><?php
                        /* translators: %s is the attribute name (e.g., size, color) */
                        printf(esc_html__('Choose %s', 'instinctor'), esc_html(ucfirst($attrName)));
                    ?></option>
                    <?php foreach ($values as $value): ?>
                    <option value="<?php echo esc_attr($value); ?>"><?php echo esc_html($value); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endforeach; ?>
            <div class="instinctor-variation-status" id="variation-status"></div>
        </div>
        <?php endif; ?>

        <?php if ($isBookable): ?>
        <!-- Booking Date/Time Picker -->
        <div class="instinctor-booking-picker" id="booking-picker">
            <h3 style="margin: 0 0 12px; font-size: 16px;">
                <?php esc_html_e('Select Appointment', 'instinctor'); ?>
                <span class="instinctor-tooltip" title="<?php esc_attr_e('Choose your preferred date and time for this service. Duration: ', 'instinctor'); ?><?php echo esc_attr($bookingDuration); ?> <?php esc_attr_e('minutes', 'instinctor'); ?>">?</span>
            </h3>
            
            <div class="instinctor-booking-date-wrap" style="margin-bottom: 12px;">
                <label for="booking-date" style="display: block; font-size: 13px; margin-bottom: 4px; color: #666;">
                    <?php esc_html_e('Date', 'instinctor'); ?>
                </label>
                <input type="date" id="booking-date" name="booking_date" required 
                       min="<?php echo esc_attr($bookingMinDate); ?>"
                       max="<?php echo esc_attr($bookingMaxDate); ?>"
                       style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
            </div>
            
            <div class="instinctor-booking-time-wrap" style="margin-bottom: 12px;">
                <label for="booking-time" style="display: block; font-size: 13px; margin-bottom: 4px; color: #666;">
                    <?php esc_html_e('Time', 'instinctor'); ?>
                </label>
                <select id="booking-time" name="booking_time" required disabled
                        style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background: #fff;">
                    <option value=""><?php esc_html_e('Select a date first', 'instinctor'); ?></option>
                </select>
            </div>
            
            <div class="instinctor-booking-note-wrap" style="margin-bottom: 12px;">
                <label for="booking-note" style="display: block; font-size: 13px; margin-bottom: 4px; color: #666;">
                    <?php esc_html_e('Notes (optional)', 'instinctor'); ?>
                    <span class="instinctor-tooltip" title="<?php esc_attr_e('Any special requests or information we should know', 'instinctor'); ?>">?</span>
                </label>
                <textarea id="booking-note" name="booking_note" rows="2" 
                          placeholder="<?php esc_attr_e('Any special requests...', 'instinctor'); ?>"
                          style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; resize: vertical;"></textarea>
            </div>
            
            <p class="instinctor-booking-duration" style="font-size: 13px; color: #666; margin: 0;">
                <strong><?php esc_html_e('Duration:', 'instinctor'); ?></strong> <?php echo esc_html($bookingDuration); ?> <?php esc_html_e('minutes', 'instinctor'); ?>
            </p>
        </div>
        
        <?php ob_start(); ?>
            .instinctor-tooltip {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                width: 16px;
                height: 16px;
                background: #e0e0e0;
                border-radius: 50%;
                font-size: 11px;
                color: #666;
                cursor: help;
                margin-left: 4px;
                vertical-align: middle;
            }
            .instinctor-booking-picker {
                background: #f9f9f9;
                padding: 16px;
                border-radius: 8px;
                margin-bottom: 16px;
                border: 1px solid #eee;
            }
            .instinctor-time-slot-unavailable {
                color: #999 !important;
            }
        <?php $_inst_lcss = ob_get_clean(); wp_add_inline_style("instinctor-page-inline", $_inst_lcss); ?>
        <?php endif; ?>

        <?php 
        // Volume discounts display
        $product_id = $product->id;
        include INSTINCTOR_PLUGIN_DIR . 'templates/partials/volume-discounts.php';
        ?>

        <?php 
        // Check stock status
        $is_in_stock = ($product->stock_quantity === null || $product->stock_quantity > 0);
        $is_preorder = !empty($product->is_preorder);
        
        if (!$is_in_stock && !$is_preorder):
            // Out of stock — no subscribe form; product is simply unavailable.
            echo '<p class="instinctor-out-of-stock">' . esc_html__('Out of stock', 'instinctor') . '</p>';
        else:
        ?>
        <div class="instinctor-add-to-cart-form">
            <?php 
            // Quantity selector with +/- buttons
            $product_id = $product->id;
            $quantity = 1;
            $min = 1;
            $max = $product->stock_quantity ?: 99;
            include INSTINCTOR_PLUGIN_DIR . 'templates/partials/quantity-selector.php';
            ?>
            
            <?php if ($is_preorder): ?>
            <button type="button" class="instinctor-preorder-btn" id="instinctor-add-btn" 
                    data-product-id="<?php echo esc_attr($product->id); ?>">
                <?php esc_html_e('Pre-Order Now', 'instinctor'); ?>
            </button>
            <?php if (!empty($product->preorder_date)): ?>
            <p class="instinctor-preorder-date">
                <?php 
                /* translators: %s is the expected availability date */
                printf(esc_html__('Expected: %s', 'instinctor'), esc_html(date_i18n(get_option('date_format'), strtotime($product->preorder_date)))); 
                ?>
            </p>
            <?php endif; ?>
            <?php else: ?>
            <button type="button" class="instinctor-add-to-cart-btn" id="instinctor-add-btn" 
                    data-product-id="<?php echo esc_attr($product->id); ?>"
                    <?php echo $hasVariations ? 'disabled' : ''; ?>>
                <?php echo $hasVariations ? esc_html__('Select Options', 'instinctor') : esc_html__('Add to Cart', 'instinctor'); ?>
            </button>
            <?php endif; ?>
            
            <?php 
            // Buy Now button (one-click checkout)
            $product_id = $product->id;
            include INSTINCTOR_PLUGIN_DIR . 'templates/partials/buy-now-button.php';
            ?>
        </div>
        
        <?php
        ?>
        <?php endif; ?>

        <?php if ($product->sku): ?>
            <p class="instinctor-product-sku">
                <strong><?php esc_html_e('SKU:', 'instinctor'); ?></strong> <?php echo esc_html($product->sku); ?>
            </p>
        <?php endif; ?>

        <?php if ($product->description): ?>
            <div class="instinctor-product-full-description">
                <h3><?php esc_html_e('Description', 'instinctor'); ?></h3>
                <?php echo wp_kses_post($product->description); ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php ob_start(); ?>
.instinctor-gallery-thumbs { display: flex; gap: 8px; margin-top: 12px; }
.instinctor-gallery-thumb { width: 60px; height: 60px; border: 2px solid transparent; border-radius: 6px; overflow: hidden; cursor: pointer; opacity: 0.7; transition: all 0.2s; }
.instinctor-gallery-thumb:hover, .instinctor-gallery-thumb.active { border-color: #1d1d1f; opacity: 1; }
.instinctor-gallery-thumb img { width: 100%; height: 100%; object-fit: cover; }

.instinctor-product-cats { margin-bottom: 8px; }
.instinctor-product-cats a { color: #86868b; font-size: 12px; text-decoration: none; text-transform: uppercase; letter-spacing: 0.5px; }
.instinctor-product-cats a:hover { color: #1d1d1f; }


.instinctor-save-badge { background: #e8f5e9; color: #2e7d32; font-size: 12px; padding: 4px 8px; border-radius: 4px; margin-left: 8px; }

<?php $_inst_lcss = ob_get_clean(); wp_add_inline_style("instinctor-page-inline", $_inst_lcss); ?>

<?php ob_start(); ?>
(function() {
    const apiUrl = '<?php echo esc_js($api_url); ?>';
    const nonce = '<?php echo esc_js($nonce); ?>';
    const isBookable = <?php echo $isBookable ? 'true' : 'false'; ?>;
    const productId = <?php echo (int) $product->id; ?>;

    // Gallery thumbnails
    document.querySelectorAll('.instinctor-gallery-thumb').forEach(thumb => {
        thumb.addEventListener('click', function() {
            document.querySelectorAll('.instinctor-gallery-thumb').forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            document.getElementById('main-img').src = this.dataset.full;
        });
    });

    // Booking date change handler
    if (isBookable) {
        const dateInput = document.getElementById('booking-date');
        const timeSelect = document.getElementById('booking-time');
        const addBtn = document.getElementById('instinctor-add-btn');
        
        // Initially disable add to cart for bookable products
        addBtn.disabled = true;
        addBtn.textContent = '<?php echo esc_js(__('Select date & time', 'instinctor')); ?>';
        
        dateInput.addEventListener('change', async function() {
            const selectedDate = this.value;
            if (!selectedDate) return;
            
            timeSelect.disabled = true;
            timeSelect.innerHTML = '<option value=""><?php echo esc_js(__('Loading times...', 'instinctor')); ?></option>';
            
            try {
                const response = await fetch(apiUrl + 'bookings/slots?product_id=' + productId + '&date=' + selectedDate, {
                    headers: { 'X-WP-Nonce': nonce }
                });
                const data = await response.json();
                
                timeSelect.innerHTML = '<option value=""><?php echo esc_js(__('Select a time', 'instinctor')); ?></option>';
                
                if (data.slots && data.slots.length > 0) {
                    data.slots.forEach(slot => {
                        const option = document.createElement('option');
                        option.value = slot.time;
                        option.textContent = slot.display;
                        if (!slot.available) {
                            option.disabled = true;
                            option.textContent += ' (<?php echo esc_js(__('Unavailable', 'instinctor')); ?>)';
                            option.className = 'instinctor-time-slot-unavailable';
                        }
                        timeSelect.appendChild(option);
                    });
                    timeSelect.disabled = false;
                } else {
                    timeSelect.innerHTML = '<option value=""><?php echo esc_js(__('No times available', 'instinctor')); ?></option>';
                }
            } catch (error) {
                console.error('Error loading time slots:', error);
                timeSelect.innerHTML = '<option value=""><?php echo esc_js(__('Error loading times', 'instinctor')); ?></option>';
            }
        });
        
        timeSelect.addEventListener('change', function() {
            if (this.value) {
                addBtn.disabled = false;
                addBtn.textContent = '<?php echo esc_js(__('Add to Cart', 'instinctor')); ?>';
            } else {
                addBtn.disabled = true;
                addBtn.textContent = '<?php echo esc_js(__('Select date & time', 'instinctor')); ?>';
            }
        });
    }

    // Add to cart
    document.getElementById('instinctor-add-btn').addEventListener('click', async function() {
        const quantity = parseInt(document.getElementById('instinctor-qty').value) || 1;
        const originalText = this.textContent;
        
        // Build request body
        const requestBody = { 
            product_id: productId, 
            quantity: quantity 
        };
        
        // Add booking meta if bookable
        if (isBookable) {
            const bookingDate = document.getElementById('booking-date').value;
            const bookingTime = document.getElementById('booking-time').value;
            const bookingNote = document.getElementById('booking-note').value;
            
            if (!bookingDate || !bookingTime) {
                alert('<?php echo esc_js(__('Please select a date and time for your appointment.', 'instinctor')); ?>');
                return;
            }
            
            requestBody.meta = {
                booking_date: bookingDate,
                booking_time: bookingTime,
                booking_note: bookingNote
            };
        }
        
        // Collect add-ons from product page
        const addonsWrap = document.getElementById('instinctor-addons-wrap');
        if (addonsWrap) {
            const addons = {};
            let valid = true;
            addonsWrap.querySelectorAll('.instinctor-addon-row').forEach(function(row) {
                const required = row.dataset.required === '1';
                const input = row.querySelector('input,select,textarea');
                if (!input) return;
                const match = input.name.match(/addons\[(\d+)\]/);
                if (!match) return;
                const id = match[1];
                const val = input.type === 'checkbox' ? (input.checked ? '1' : '') : input.value;
                if (required && !val) {
                    input.style.outline = '2px solid #c00';
                    valid = false;
                } else {
                    input.style.outline = '';
                    if (val) addons[id] = val;
                }
            });
            if (!valid) return;
            if (Object.keys(addons).length) {
                if (!requestBody.meta) requestBody.meta = {};
                requestBody.meta.addons = addons;
            }
        }

        this.disabled = true;
        this.textContent = '<?php echo esc_js(__('Adding...', 'instinctor')); ?>';

        try {
            const response = await fetch(apiUrl + 'cart/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify(requestBody)
            });

            const data = await response.json();
            
            if (data.success) {
                this.textContent = '<?php echo esc_js(__('Added!', 'instinctor')); ?>';
                document.dispatchEvent(new CustomEvent('instinctor:cart:updated', { detail: data.cart || {} }));
                setTimeout(() => {
                    this.textContent = originalText;
                    this.disabled = false;
                }, 1500);
            } else {
                this.textContent = data.error || '<?php echo esc_js(__('Error', 'instinctor')); ?>';
                setTimeout(() => {
                    this.textContent = originalText;
                    this.disabled = false;
                }, 2000);
            }
        } catch (error) {
            this.textContent = '<?php echo esc_js(__('Error', 'instinctor')); ?>';
            setTimeout(() => {
                this.textContent = originalText;
                this.disabled = false;
            }, 2000);
        }
    });
})();
<?php $_inst_ljs = ob_get_clean(); wp_add_inline_script('instinctor-frontend-js', $_inst_ljs, 'after'); ?>
