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

// Get product ID
$product_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($product_id <= 0) {
    header("Location: shop.php");
    exit;
}

// Fetch product details
try {
    $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.id = ?");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch();
} catch (Exception $e) {
    $product = null;
}

if (!$product) {
    header("Location: shop.php");
    exit;
}

// Fetch recommended products (from same category, excluding current product)
try {
    $stmt = $pdo->prepare("SELECT p.*, c.name as category_name 
                            FROM products p 
                            LEFT JOIN categories c ON p.category_id = c.id 
                            WHERE p.category_id = ? AND p.id != ? 
                            ORDER BY RAND() LIMIT 3");
    $stmt->execute([$product['category_id'], $product_id]);
    $recommended = $stmt->fetchAll();
} catch (Exception $e) {
    $recommended = [];
}

// Fetch dynamic colors of this product
$colors = [];
try {
    $stmt_colors = $pdo->prepare("SELECT c.* FROM colors c JOIN product_colors pc ON c.id = pc.color_id WHERE pc.product_id = ? ORDER BY c.name ASC");
    $stmt_colors->execute([$product_id]);
    $colors = $stmt_colors->fetchAll();
} catch (Exception $e) {
    $colors = [];
}

// Fetch dynamic sizes of this product
$sizes = [];
try {
    $stmt_sizes = $pdo->prepare("SELECT s.* FROM sizes s JOIN product_sizes ps ON s.id = ps.size_id WHERE ps.product_id = ? ORDER BY s.id ASC");
    $stmt_sizes->execute([$product_id]);
    $sizes = $stmt_sizes->fetchAll();
} catch (Exception $e) {
    $sizes = [];
}

// Fallback collections to protect page display in extreme cases
if (empty($colors)) {
    $colors = [
        ['name' => 'Midnight Black', 'hex' => '#050505', 'border' => '#2A2A2A'],
        ['name' => 'Royal Gold', 'hex' => '#DCC7A3', 'border' => '#FFFFFF'],
        ['name' => 'Ivory White', 'hex' => '#F4F4F4', 'border' => '#E0E0E0'],
        ['name' => 'Espresso Brown', 'hex' => '#4E3629', 'border' => '#6A4E3D']
    ];
}
if (empty($sizes)) {
    $sizes = [
        ['name' => 'XS'],
        ['name' => 'S'],
        ['name' => 'M'],
        ['name' => 'L'],
        ['name' => 'XL']
    ];
}
?>

<!-- Breadcrumbs -->
<div class="py-4 border-bottom border-dark" style="background-color: #050505;">
    <div class="container">
        <nav class="luxury-breadcrumb-wrapper" aria-label="breadcrumb">
            <div class="d-flex flex-wrap align-items-center gap-2 small">
                <a href="index.php" class="breadcrumb-btn">
                    <i class="fa-solid fa-house me-1" style="font-size: 0.7rem;"></i> Home
                </a> 
                <span class="breadcrumb-separator"><i class="fa-solid fa-chevron-right"></i></span> 
                
                <a href="shop.php" class="breadcrumb-btn">Shop</a> 
                <span class="breadcrumb-separator"><i class="fa-solid fa-chevron-right"></i></span> 
                
                <a href="shop.php?category=<?php echo urlencode($product['category_slug'] ?? ''); ?>" class="breadcrumb-btn">
                    <?php echo htmlspecialchars($product['category_name'] ?? 'Couture'); ?>
                </a>
                <span class="breadcrumb-separator"><i class="fa-solid fa-chevron-right"></i></span> 
                
                <span class="breadcrumb-btn-active">
                    <?php echo htmlspecialchars($product['name']); ?>
                </span>
            </div>
        </nav>
    </div>
</div>

<!-- Product Details Section -->
<section class="py-5" style="background-color: var(--bg-dark);">
    <div class="container py-3">
        <div class="row g-5">
            <!-- Left Column: Image -->
            <div class="col-lg-6">
                <div class="product-detail-img-container border border-secondary p-2 rounded bg-black" style="overflow: hidden;">
                    <img src="assets/images/<?php echo htmlspecialchars($product['image']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" class="img-fluid w-100 rounded" style="transition: transform 0.5s ease; object-fit: cover; max-height: 600px;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">
                </div>
            </div>

            <!-- Right Column: Info & Options -->
            <div class="col-lg-6">
                <div class="product-info-wrap text-white">
                    <p class="text-warning text-uppercase small fw-bold mb-1" style="letter-spacing: 2px;"><?php echo htmlspecialchars($product['category_name'] ?? 'Luxury'); ?></p>
                    <h1 class="fw-bold display-5 mb-2"><?php echo htmlspecialchars($product['name']); ?></h1>
                    
                    <!-- Rating and Reviews -->
                    <div class="d-flex align-items-center gap-2 mb-3">
                        <div class="text-warning small">
                            <i class="fa-solid fa-star"></i>
                            <i class="fa-solid fa-star"></i>
                            <i class="fa-solid fa-star"></i>
                            <i class="fa-solid fa-star"></i>
                            <i class="fa-solid fa-star-half-stroke"></i>
                        </div>
                        <span class="text-muted small">(4.8 Stars | 42 Verified Reviews)</span>
                    </div>

                    <!-- Price -->
                    <h2 class="text-warning fw-semibold mb-4" style="font-family: var(--font-body);">LKR <?php echo number_format($product['price'], 2); ?></h2>
                    
                    <!-- Description -->
                    <div class="description-content text-muted small lh-lg mb-4" style="color: var(--text-gray);">
                        <p><?php echo nl2br(htmlspecialchars($product['description'] ?? 'This is a premium tailored accessory designed for the modern fashionista. Featuring ultimate quality materials, luxury handcrafting, and beautiful custom hardware. Exquisite detail matching the gold theme is applied, promising high-class comfort and ultimate durability. Perfect for all seasons.')); ?></p>
                    </div>

                    <hr class="border-secondary opacity-25 my-4">

                    <!-- Product Options Form -->
                    <form id="product-options-form">
                        <!-- Size Selector -->
                        <div class="mb-4">
                            <label class="text-white text-uppercase small fw-bold mb-2 d-block" style="letter-spacing: 1px;">Select Couture Size</label>
                            <div class="d-flex gap-2">
                                <?php 
                                $size_first = true;
                                foreach ($sizes as $s_item): 
                                    $size_val = htmlspecialchars($s_item['name']);
                                ?>
                                    <input type="radio" class="btn-check" name="size" id="size-<?php echo $size_val; ?>" value="<?php echo $size_val; ?>" <?php echo $size_first ? 'checked' : ''; ?>>
                                    <label class="btn btn-outline-light rounded-circle d-flex align-items-center justify-content-center" for="size-<?php echo $size_val; ?>" style="width: 45px; height: 45px; font-size: 0.8rem; font-weight: bold; border-width: 1px; transition: all 0.2s;">
                                        <?php echo $size_val; ?>
                                    </label>
                                <?php 
                                    $size_first = false;
                                endforeach; 
                                ?>
                            </div>
                        </div>

                        <!-- Color Swatches -->
                        <div class="mb-4">
                            <label class="text-white text-uppercase small fw-bold mb-2 d-block" style="letter-spacing: 1px;">Select Couture Color</label>
                            <div class="d-flex gap-3 align-items-center">
                                <?php 
                                $first = true;
                                foreach ($colors as $idx => $info): 
                                    $color_id_tag = 'color-' . $idx;
                                ?>
                                    <input type="radio" class="btn-check btn-check-color" name="color" id="<?php echo $color_id_tag; ?>" value="<?php echo htmlspecialchars($info['name']); ?>" <?php echo $first ? 'checked' : ''; ?>>
                                    <label class="rounded-circle color-swatch" for="<?php echo $color_id_tag; ?>" style="width: 32px; height: 32px; background-color: <?php echo htmlspecialchars($info['hex']); ?>; border: 2px solid <?php echo htmlspecialchars($info['border']); ?>; cursor: pointer; transition: all 0.2s;" title="<?php echo htmlspecialchars($info['name']); ?>"></label>
                                <?php 
                                    $first = false;
                                    endforeach; 
                                ?>
                            </div>
                        </div>

                        <!-- Quantity Selector and CTA -->
                        <div class="d-flex flex-wrap align-items-end gap-3 mb-4 mt-2">
                            <div>
                                <label class="text-white text-uppercase small fw-bold mb-2 d-block" style="letter-spacing: 1px;">Quantity</label>
                                <div class="input-group" style="width: 120px;">
                                    <button class="btn btn-outline-light px-3 py-2" type="button" onclick="const q = document.getElementById('quantity'); if(q.value > 1) q.value--">-</button>
                                    <input type="text" id="quantity" class="form-control text-center bg-black border-light text-white" value="1" readonly>
                                    <button class="btn btn-outline-light px-3 py-2" type="button" onclick="const q = document.getElementById('quantity'); q.value++">+</button>
                                </div>
                            </div>
                            
                            <!-- Add to Cart Button -->
                            <div class="flex-grow-1">
                                <button type="button" class="btn btn-warning w-100 text-black py-3 rounded-pill fw-bold text-uppercase fs-7 add-to-cart-detail-btn" style="letter-spacing: 1px;">
                                    <i class="fa-solid fa-bag-shopping me-2"></i> Add to Atelier Bag
                                </button>
                            </div>
                        </div>
                    </form>

                    <!-- Atelier Badges -->
                    <div class="border border-secondary p-3 rounded bg-black d-flex flex-column gap-2 small">
                        <div class="d-flex align-items-center gap-2"><i class="fa-solid fa-shield text-warning"></i> <span>100% Genuine Luxury Certified</span></div>
                        <div class="d-flex align-items-center gap-2"><i class="fa-solid fa-box-open text-warning"></i> <span>Complimentary Premium Gift Box & Silk wrapping included</span></div>
                        <div class="d-flex align-items-center gap-2"><i class="fa-solid fa-arrow-rotate-left text-warning"></i> <span>Enjoy 14-day hassle-free returns</span></div>
                    </div>

                </div>
            </div>
        </div>

        <!-- Recommended Products / Atelier Selection -->
        <?php if (!empty($recommended)): ?>
            <div class="mt-5 pt-5">
                <div class="text-center mb-5">
                    <p class="text-warning small text-uppercase fw-bold mb-1" style="letter-spacing: 2px;">Atelier Recommendations</p>
                    <h3 class="text-white fw-bold display-6">You May Also Exquisitely Like</h3>
                    <div class="mx-auto" style="width: 50px; height: 2px; background-color: var(--accent-gold); margin-top: 10px;"></div>
                </div>

                <div class="row g-4 justify-content-center">
                    <?php foreach ($recommended as $rec): ?>
                        <div class="col-lg-4 col-md-6">
                            <div class="product-card">
                                <div class="product-img-wrapper">
                                    <a href="product.php?id=<?php echo $rec['id']; ?>">
                                        <img src="assets/images/<?php echo htmlspecialchars($rec['image']); ?>" alt="<?php echo htmlspecialchars($rec['name']); ?>" loading="lazy">
                                    </a>
                                    <button type="button" class="wishlist-btn" onclick="addToWishlist(<?php echo $rec['id']; ?>)">
                                        <i class="fa-regular fa-heart"></i>
                                    </button>
                                </div>
                                <div class="product-details position-relative">
                                    <div class="mb-1 text-muted text-uppercase small" style="font-size: 0.7rem; letter-spacing: 1px;">
                                        <?php echo htmlspecialchars($rec['category_name'] ?? 'Couture'); ?>
                                    </div>
                                    <h4 class="product-name fs-6">
                                        <a href="product.php?id=<?php echo $rec['id']; ?>" class="text-white text-decoration-none hover-gold">
                                            <?php echo htmlspecialchars($rec['name']); ?>
                                        </a>
                                    </h4>
                                    <div class="product-price">LKR <?php echo number_format($rec['price'], 2); ?></div>
                                    <button type="button" class="cart-icon-btn add-to-cart-btn" data-product-id="<?php echo $rec['id']; ?>" title="Add to Cart">
                                        <i class="fa-solid fa-plus text-dark"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

    </div>
</section>

<!-- Size selector styling and dynamic single page AJAX add-to-cart logic -->
<style>
    .btn-check:checked + label {
        background-color: var(--accent-gold) !important;
        border-color: var(--accent-gold) !important;
        color: black !important;
        box-shadow: 0 0 10px rgba(220, 199, 163, 0.4);
    }
    .btn-check-color:checked + label.color-swatch {
        box-shadow: 0 0 0 2px var(--accent-gold) !important;
        transform: scale(1.15);
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const detailAddBtn = document.querySelector('.add-to-cart-detail-btn');
    if (detailAddBtn) {
        detailAddBtn.addEventListener('click', function(e) {
            e.preventDefault();
            const productId = <?php echo $product_id; ?>;
            const quantity = document.getElementById('quantity').value;
            const selectedSize = document.querySelector('input[name="size"]:checked').value;
            const selectedColor = document.querySelector('input[name="color"]:checked').value;
            
            const originalHTML = this.innerHTML;
            this.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Adding to Bag...';
            this.disabled = true;

            fetch('cart_action.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=add&product_id=${productId}&quantity=${quantity}&size=${encodeURIComponent(selectedSize)}&color=${encodeURIComponent(selectedColor)}`
            })
            .then(response => response.json())
            .then(data => {
                this.innerHTML = originalHTML;
                this.disabled = false;
                
                if (data.status === 'success') {
                    // Update header cart count badge dynamically
                    let cartBadge = document.querySelector('.cart-badge');
                    if (cartBadge) {
                        cartBadge.textContent = data.cart_count;
                    } else {
                        const cartLink = document.querySelector('.fa-bag-shopping').parentElement;
                        const badgeSpan = document.createElement('span');
                        badgeSpan.className = 'position-absolute top-0 start-100 translate-middle badge rounded-circle cart-badge';
                        badgeSpan.textContent = data.cart_count;
                        cartLink.appendChild(badgeSpan);
                    }
                    
                    window.showToast(`${data.product_name} (${selectedColor} / ${selectedSize}) added to cart!`);
                } else {
                    window.showToast(data.message || 'Error adding to cart.', 'error');
                }
            })
            .catch(error => {
                console.error('Error adding to cart:', error);
                this.innerHTML = originalHTML;
                this.disabled = false;
                window.showToast('Something went wrong. Please try again.', 'error');
            });
        });
    }
});
</script>

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