<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
include "config/db.php";

if (isset($_GET['id']) && !empty($_GET['id'])) {
    $where_clause = "p.id = '" . mysqli_real_escape_string($conn, $_GET['id']) . "'";
} elseif (isset($_GET['slug']) && !empty($_GET['slug'])) {
    $where_clause = "p.slug = '" . mysqli_real_escape_string($conn, $_GET['slug']) . "'";
} else {
    header("Location: products.php");
    exit();
}

$product_query = mysqli_query($conn, 
    "SELECT p.*, c.category_name 
     FROM products p 
     LEFT JOIN categories c ON p.category_id = c.id 
     WHERE $where_clause AND p.stock > 0 AND (p.is_deleted = 0 OR p.is_deleted IS NULL)"
);

if (mysqli_num_rows($product_query) == 0) {
    header("Location: products.php");
    exit();
}

$product = mysqli_fetch_assoc($product_query);

// Handle add to cart
if (isset($_POST['add_to_cart'])) {
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = [];
    }
    
    $item = [
        'id' => $product['id'],
        'name' => $product['name'],
        'price' => $product['price'],
        'image' => $product['images'],
        'size' => isset($_POST['size']) ? $_POST['size'] : $product['size'],
        'qty' => 1
    ];
    
    $_SESSION['cart'][] = $item;
    header("Location: cart.php");
    exit();
}

// Handle add to wishlist
if (isset($_POST['add_to_wishlist'])) {
    if (!isset($_SESSION['wishlist'])) {
        $_SESSION['wishlist'] = [];
    }
    
    // Check if already in wishlist
    $already_in_wishlist = false;
    foreach ($_SESSION['wishlist'] as $item) {
        if ($item['id'] == $product['id']) {
            $already_in_wishlist = true;
            break;
        }
    }
    
    if (!$already_in_wishlist) {
        $_SESSION['wishlist'][] = [
            'id' => $product['id'],
            'name' => $product['name'],
            'price' => $product['price'],
            'image' => $product['images']
        ];
        $wishlist_success = "Added to wishlist!";
    } else {
        $wishlist_error = "Already in wishlist!";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($product['name']); ?> - ShopNest</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .btn-orange {
            background: linear-gradient(45deg, #ff6b35, #ff8e53);
            border: none;
            color: white;
            padding: 10px 25px;
            border-radius: 25px;
            font-weight: 600;
        }
        .btn-orange:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 107, 53, 0.3);
            color: white;
        }
        .product-image {
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }
        .product-info {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
        }
        .price-tag {
            font-size: 2.5rem;
            font-weight: bold;
            color: #ff6b35;
        }
        .size-marker {
            display: inline-block;
            width: 45px;
            height: 45px;
            line-height: 45px;
            text-align: center;
            border: 2px solid #ddd;
            border-radius: 5px;
            margin-right: 10px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
        }
        .size-marker:hover {
            border-color: #ff6b35;
            color: #ff6b35;
        }
        .size-marker.active {
            background: #ff6b35;
            border-color: #ff6b35;
            color: white;
        }
        .carousel-control-prev, .carousel-control-next {
            background: rgba(255, 255, 255, 0.8) !important;
            backdrop-filter: blur(8px);
            -webkit-backdrop-filter: blur(8px);
            width: 38px;
            height: 38px;
            border-radius: 50%;
            top: 50% !important;
            transform: translateY(-50%) !important;
            box-shadow: 0 4px 12px rgba(0,0,0,0.12);
            opacity: 1 !important;
            transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
            z-index: 5;
            display: flex !important;
            align-items: center;
            justify-content: center;
            border: 1px solid rgba(255,255,255,0.4);
            color: #333 !important;
        }
        .carousel-control-prev { left: 15px; }
        .carousel-control-next { right: 15px; }
        
        .carousel-control-prev:hover, .carousel-control-next:hover {
            background: #ff6b35 !important;
            color: white !important;
            box-shadow: 0 6px 20px rgba(255, 107, 53, 0.4);
            transform: translateY(-50%) scale(1.1) !important;
            border-color: #ff6b35;
        }
        .carousel-control-prev i, .carousel-control-next i {
            font-size: 14px;
            font-weight: bold;
        }
        .carousel-item img {
            border-radius: 15px;
        }
    </style>
</head>
<body>
    <?php include "includes/header.php"; ?>

    <div class="container mt-4">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                <li class="breadcrumb-item"><a href="products.php">Rent Clothes</a></li>
                <li class="breadcrumb-item"><a href="products.php?cat=<?php echo $product['category_id']; ?>">
                    <?php echo htmlspecialchars($product['category_name']); ?>
                </a></li>
                <li class="breadcrumb-item active"><?php echo htmlspecialchars($product['name']); ?></li>
            </ol>
        </nav>

<?php
// Helper to get images array (handle JSON or old string)
function getImages($imgStr) {
    if (empty($imgStr)) return [];
    $decoded = json_decode($imgStr, true);
    return is_array($decoded) ? $decoded : [$imgStr];
}

$product_images = getImages($product['images']);
$main_image = !empty($product_images) ? $product_images[0] : '';
?>
        <div class="row">
            <!-- Product Image Gallery -->
            <div class="col-lg-6 mb-4">
                <div class="product-gallery">
                    <div id="productCarousel" class="carousel slide mb-3" data-bs-ride="carousel">
                        <div class="carousel-inner product-image" style="height: 500px; background: #f8f9fa;">
                            <?php foreach ($product_images as $key => $img): ?>
                                <div class="carousel-item <?php echo $key === 0 ? 'active' : ''; ?> h-100">
                                    <div class="d-flex align-items-center justify-content-center h-100">
                                        <img src="assets/images/products/<?php echo htmlspecialchars($img); ?>" 
                                             class="d-block mw-100 mh-100" 
                                             alt="<?php echo htmlspecialchars($product['name']); ?>"
                                             style="object-fit: contain;"
                                             onerror="this.src='assets/images/products/placeholder.jpg'">
                                    </div>
                                </div>
                            <?php endforeach; ?>

                            <!-- Video Item in Carousel -->
                            <?php if (!empty($product['video_path'])): ?>
                                <div class="carousel-item <?php echo empty($product_images) ? 'active' : ''; ?> h-100">
                                    <div class="d-flex align-items-center justify-content-center h-100 bg-black rounded">
                                        <div class="ratio ratio-16x9 w-100 h-100">
                                            <video id="pDVideo" controls class="rounded w-100 h-100" style="object-fit: contain;">
                                                <source src="assets/videos/products/<?php echo htmlspecialchars($product['video_path']); ?>">
                                                Your browser does not support the video tag.
                                            </video>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                        <?php 
                        $total_items = count($product_images) + (!empty($product['video_path']) ? 1 : 0);
                        if ($total_items > 1): 
                        ?>
                            <button class="carousel-control-prev" type="button" data-bs-target="#productCarousel" data-bs-slide="prev">
                                <i class="fas fa-chevron-left" aria-hidden="true"></i>
                                <span class="visually-hidden">Previous</span>
                            </button>
                            <button class="carousel-control-next" type="button" data-bs-target="#productCarousel" data-bs-slide="next">
                                <i class="fas fa-chevron-right" aria-hidden="true"></i>
                                <span class="visually-hidden">Next</span>
                            </button>
                        <?php endif; ?>
                    </div>
                    
                    <?php if ($total_items > 1): ?>
                        <div class="thumbnails d-flex flex-wrap gap-2">
                            <?php foreach ($product_images as $key => $img): ?>
                                <div class="thumbnail-item <?php echo $key === 0 ? 'active' : ''; ?>" 
                                     style="width: 80px; height: 80px; cursor: pointer; border: 2px solid <?php echo $key === 0 ? '#ff6b35' : 'transparent'; ?>; transition: 0.3s; border-radius: 10px; overflow: hidden;"
                                     data-bs-target="#productCarousel" data-bs-slide-to="<?php echo $key; ?>">
                                    <img src="assets/images/products/<?php echo htmlspecialchars($img); ?>" 
                                         class="img-fluid h-100 w-100" 
                                         style="object-fit: cover;"
                                         onerror="this.src='assets/images/products/placeholder.jpg'">
                                </div>
                            <?php endforeach; ?>

                            <?php if (!empty($product['video_path'])): ?>
                                <div class="thumbnail-item <?php echo empty($product_images) ? 'active' : ''; ?> position-relative" 
                                     style="width: 80px; height: 80px; cursor: pointer; border: 2px solid transparent; transition: 0.3s; border-radius: 10px; overflow: hidden; background: #000;"
                                     data-bs-target="#productCarousel" data-bs-slide-to="<?php echo count($product_images); ?>">
                                    <i class="fas fa-play position-absolute top-50 start-50 translate-middle text-white shadow-sm" style="font-size: 1.5rem; z-index: 1;"></i>
                                    <div class="h-100 w-100 bg-dark opacity-50"></div>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>



                </div>

                <!-- Product Specifications -->
                <div class="card mt-4">
                    <div class="card-body">
                        <h4 class="mb-4">Product Details</h4>
                        
                        <div class="row">
                            <div class="col-12">
                                <table class="table table-bordered table-striped mb-0">
                                    <tbody>
                                        <tr>
                                            <td width="40%" class="bg-light"><strong>Category</strong></td>
                                            <td><?php echo htmlspecialchars($product['category_name']); ?></td>
                                        </tr>
                                        <?php if(!empty($product['size'])): ?>
                                        <tr>
                                            <td class="bg-light"><strong>Size</strong></td>
                                            <td><?php echo htmlspecialchars($product['size']); ?></td>
                                        </tr>
                                        <?php endif; ?>
                                        <?php if(!empty($product['color'])): ?>
                                        <tr>
                                            <td class="bg-light"><strong>Color</strong></td>
                                            <td><?php echo htmlspecialchars($product['color']); ?></td>
                                        </tr>
                                        <?php endif; ?>
                                        <?php if(!empty($product['brand'])): ?>
                                        <tr>
                                            <td class="bg-light"><strong>Brand</strong></td>
                                            <td><?php echo htmlspecialchars($product['brand']); ?></td>
                                        </tr>
                                        <?php endif; ?>
                                        <?php if(!empty($product['material'])): ?>
                                        <tr>
                                            <td class="bg-light"><strong>Material</strong></td>
                                            <td><?php echo htmlspecialchars($product['material']); ?></td>
                                        </tr>
                                        <?php endif; ?>
                                        <tr>
                                            <td class="bg-light"><strong>Product Price</strong></td>
                                            <td>₹<?php echo number_format($product['original_price'], 2); ?></td>
                                        </tr>
                                        <tr>
                                            <td class="bg-light"><strong>Rental Price</strong></td>
                                            <td>₹<?php echo number_format($product['rental_price'] > 0 ? $product['rental_price'] : $product['price'], 2); ?> per day</td>
                                        </tr>
                                        <?php if($product['discount_percent'] > 0): ?>
                                        <tr>
                                            <td class="bg-light"><strong>Discount</strong></td>
                                            <td class="text-warning"><?php echo $product['discount_percent']; ?>% OFF</td>
                                        </tr>
                                        <tr>
                                            <td class="bg-light"><strong>Final Price</strong></td>
                                            <td class="text-success"><strong>₹<?php echo number_format($product['price'], 2); ?>/day</strong></td>
                                        </tr>
                                        <?php endif; ?>
                                        <tr>
                                            <td class="bg-light"><strong>Security Deposit</strong></td>
                                            <td class="text-danger">₹<?php echo number_format($product['security_deposit'], 2); ?></td>
                                        </tr>
                                        <tr>
                                            <td class="bg-light"><strong>Availability</strong></td>
                                            <td>
                                                <?php if($product['stock'] > 0): ?>
                                                    <span class="text-success">In Stock (<?php echo $product['stock']; ?> available)</span>
                                                <?php else: ?>
                                                    <span class="text-danger">Out of Stock</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Product Details -->
            <div class="col-lg-6">
                <div class="product-info pe-lg-3">
                    <h3 class="mb-2 fw-bold"><?php echo htmlspecialchars($product['name']); ?></h3>
                    
                    <div class="mb-3">
                        <span class="badge bg-primary mb-2 p-1 px-2" style="font-size: 0.8rem;"><?php echo htmlspecialchars($product['category_name']); ?></span>
                        <?php if(!empty($product['color'])): ?>
                            <span class="ms-2 text-muted fw-bold" style="font-size: 0.85rem;">Color: <span class="text-dark"><?php echo htmlspecialchars($product['color']); ?></span></span>
                        <?php endif; ?>
                    </div>

                    <?php if(!empty($product['size'])): ?>
                    <div class="mb-3">
                        <h6 class="fw-bold mb-2" style="font-size: 0.9rem;">Select Size</h6>
                        <div class="d-flex flex-wrap" id="sizeSelector">
                            <?php 
                            $sizes = explode(',', $product['size']);
                            foreach ($sizes as $s): 
                                $s = trim($s);
                                if (empty($s)) continue;
                            ?>
                                <div class="size-marker py-1 px-3" data-size="<?php echo htmlspecialchars($s); ?>" style="font-size: 0.85rem;"><?php echo htmlspecialchars($s); ?></div>
                            <?php endforeach; ?>
                        </div>
                        <input type="hidden" name="selected_size" id="selectedSizeInput" value="<?php echo trim($sizes[0]); ?>">
                    </div>
                    <?php endif; ?>
                    
                    <div class="price-tag mb-3">
                        <?php
                        $p_original = floatval($product['original_price']);
                        $p_rental = floatval($product['rental_price'] > 0 ? $product['rental_price'] : $product['price']);
                        $p_discount = intval($product['discount_percent']);
                        
                        // The 'price' column in DB is already the final discounted price saved by the admin panel
                        $p_final = floatval($product['price']);
                        
                        $p_security = floatval($product['security_deposit']);
                        ?>
                            <div class="price-container p-3 mb-3 mt-2 rounded" style="background-color: #f8f9fa; border: 1px solid #e9ecef; border-left: 4px solid #ff6b35;">
                                <div class="d-flex align-items-baseline mb-2">
                                    <h2 class="mb-0 text-dark fw-bold me-3" style="font-size: 2rem;">₹<?php echo number_format($p_final, 2); ?></h2>
                                    <span class="text-muted" style="font-size: 0.95rem;">/ day</span>
                                    
                                    <?php if ($p_discount > 0): ?>
                                        <span class="badge bg-success ms-3" style="font-size: 0.85rem; padding: 5px 10px;"><?php echo $p_discount; ?>% OFF</span>
                                    <?php endif; ?>
                                </div>
                                
                                 <div class="d-flex flex-wrap" style="font-size: 0.85rem;">
                                    <?php 
                                    $display_market = floatval($product['market_price'] ?? 0);
                                    if ($display_market > 0): ?>
                                        <div class="text-muted me-4 mb-1">
                                            <span>Market Price (MRP):</span> <del>₹<?php echo number_format($display_market, 2); ?></del>
                                        </div>
                                    <?php else: 
                                        $display_original = ($p_original > 0) ? $p_original : $p_rental; ?>
                                        <div class="text-muted me-4 mb-1">
                                            <span>Retail Price:</span> <del>₹<?php echo number_format($display_original, 2); ?></del>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($p_discount > 0): ?>
                                        <div class="text-muted mb-1">
                                            <span>Base Rental:</span> <del>₹<?php echo number_format($p_rental, 2); ?></del>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Security Deposit Note -->
                            <?php if ($p_security > 0): ?>
                                <div class="alert alert-info py-2 px-3 mb-0" style="font-size: 0.85rem;">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>Security Deposit:</strong> ₹<?php echo number_format($p_security, 2); ?> (refundable)
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <p class="text-muted mb-3" style="font-size: 0.9rem; line-height: 1.5;"><?php echo nl2br(htmlspecialchars($product['description'])); ?></p>
                    
                    <!-- Stock Status -->
                    <div class="mb-3">
                        <?php if($product['stock'] > 0): ?>
                            <span class="badge bg-success py-1 px-2">
                                <i class="fas fa-check-circle me-1"></i>Available for Rent
                            </span>
                            <small class="text-muted d-block mt-1" style="font-size: 0.8rem;">Only <?php echo $product['stock']; ?> left in stock</small>
                        <?php else: ?>
                            <span class="badge bg-danger py-1 px-2">
                                <i class="fas fa-times-circle me-1"></i>Out of Stock
                            </span>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Action Buttons -->
                    <div class="row g-2 mb-3">
                        <div class="col-md-6">
                            <form method="POST">
                                <input type="hidden" name="qty" value="1">
                                <!-- Re-inject selected size for form submission -->
                                <input type="hidden" name="size" id="formSize">
                                <button type="submit" name="add_to_cart" class="btn btn-orange w-100 py-2 fw-bold" 
                                        onclick="document.getElementById('formSize').value = document.getElementById('selectedSizeInput').value;"
                                        <?php echo $product['stock'] == 0 ? 'disabled' : ''; ?>
                                        style="font-size: 0.95rem;">
                                    <i class="fas fa-cart-plus me-2"></i>Add to Cart
                                </button>
                            </form>
                        </div>
                        <div class="col-md-6">
                            <form method="POST">
                                <button type="submit" name="add_to_wishlist" class="btn btn-outline-danger w-100 py-2 fw-bold" style="font-size: 0.95rem;">
                                    <i class="fas fa-heart me-2"></i>Add to Wishlist
                                </button>
                            </form>
                        </div>
                    </div>
                    
                    <?php if(isset($wishlist_success)): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle me-2"></i>
                            <?php echo $wishlist_success; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if(isset($wishlist_error)): ?>
                        <div class="alert alert-warning alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            <?php echo $wishlist_error; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Rental Information -->
                    <div class="card shadow-sm border-0 bg-light mt-1">
                        <div class="card-body p-3">
                            <h6 class="fw-bold mb-2 mx-1" style="font-size: 0.9rem;"><i class="fas fa-info-circle me-2 text-info"></i>Rental Information</h6>
                            <ul class="mb-0 text-muted" style="font-size: 0.8rem; padding-left: 1.5rem;">
                                <li class="mb-1">Free delivery & pickup included</li>
                                <li class="mb-1">Professional dry cleaning after every use</li>
                                <li class="mb-1">Flexible rental periods (3-14 days)</li>
                                <li class="mb-1">Quality check & ironing before delivery</li>
                                <li>Easy cancellation policy</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </div>
        
        <!-- Related Products -->
        <div class="row mt-5">
            <div class="col-12">
                <h3 class="mb-4">You Might Also Like (Trending)</h3>
                <?php
                // Fetch trending (featured) products instead of category-restricted, excluding the current product
                $related_products = mysqli_query($conn, 
                    "SELECT * FROM products 
                     WHERE featured = 1 
                     AND id != '{$product['id']}' 
                     AND stock > 0 
                     AND (is_deleted = 0 OR is_deleted IS NULL)
                     ORDER BY created_at DESC
                     LIMIT 4"
                );
                
                if(mysqli_num_rows($related_products) > 0):
                ?>
                <div class="row">
                    <?php while($related = mysqli_fetch_assoc($related_products)): ?>
                    <div class="col-lg-3 col-md-6 mb-4">
                        <div class="card h-100">
                            <?php
                            $rel_imgs = getImages($related['images']);
                            $rel_src = !empty($rel_imgs) ? $rel_imgs[0] : 'placeholder.jpg';
                            ?>
                            <img src="assets/images/products/<?php echo htmlspecialchars($rel_src); ?>" 
                                 class="card-img-top" 
                                 alt="<?php echo htmlspecialchars($related['name']); ?>"
                                 style="height: 200px; object-fit: cover;"
                                 onerror="this.src='assets/images/products/placeholder.jpg'">
                            <div class="card-body">
                                <h6 class="card-title"><?php echo htmlspecialchars($related['name']); ?></h6>
                                <p class="card-text text-success fw-bold">
                                    ₹<?php echo number_format($related['price'], 2); ?>/day
                                </p>
                                <a href="product-details.php?slug=<?php echo htmlspecialchars($related['slug']); ?>" class="btn btn-sm btn-outline-primary w-100">
                                    <i class="fas fa-eye me-1"></i>View Details
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php endwhile; ?>
                </div>
                <?php else: ?>
                    <div class="alert alert-light text-center py-4">
                        <i class="fas fa-star text-warning mb-2 fa-2x"></i>
                        <p class="mb-0 text-muted">More trending collections arriving soon!</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?php include "includes/footer.php"; ?>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Size Selector Logic
        document.querySelectorAll('.size-marker').forEach(marker => {
            // Set first size as active by default
            if(marker.dataset.size === document.getElementById('selectedSizeInput').value) {
                marker.classList.add('active');
            }

            marker.addEventListener('click', function() {
                document.querySelectorAll('.size-marker').forEach(m => m.classList.remove('active'));
                this.classList.add('active');
                document.getElementById('selectedSizeInput').value = this.dataset.size;
            });
        });

        // Sync Thumbnail Border with Carousel
        const carousel = document.getElementById('productCarousel');
        carousel.addEventListener('slide.bs.carousel', function (e) {
            document.querySelectorAll('.thumbnail-item').forEach((thumb, index) => {
                if(index === e.to) {
                    thumb.style.borderColor = '#ff6b35';
                } else {
                    thumb.style.borderColor = 'transparent';
                }
            });
        });
    </script>
</body>
</html>