<?php
require_once 'config.php';
require_once 'includes/product.php';
require_once 'includes/cart.php';

$pageTitle = 'Product Details';
$productModel = new Product();
$cart = new Cart();

// Get product ID
$productId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$product = $productModel->getById($productId);

if (!$product) {
    header('Location: products.php');
    exit;
}

$pageTitle = $product['name'];

// Handle add to cart
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_to_cart') {
    $quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;
    $size = isset($_POST['size']) ? $_POST['size'] : null;
    $color = isset($_POST['color']) ? $_POST['color'] : null;
    
    $cart->add($product, $quantity, $size, $color);
    $message = 'Product added to cart!';
    $messageType = 'success';
}

require_once 'includes/header.php';
?>

<!-- Product Detail Page -->
<section class="product-detail">
    <div class="container">
        <!-- Breadcrumb -->
        <nav class="breadcrumb">
            <a href="<?php echo SITE_URL; ?>/index.php">Home</a>
            <span>/</span>
            <a href="<?php echo SITE_URL; ?>/products.php">Products</a>
            <span>/</span>
            <a href="<?php echo SITE_URL; ?>/products.php?category=<?php echo urlencode($product['category']); ?>"><?php echo htmlspecialchars($product['category']); ?></a>
            <span>/</span>
            <span><?php echo htmlspecialchars($product['name']); ?></span>
        </nav>
        
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?>">
                <?php echo htmlspecialchars($message); ?>
                <a href="<?php echo SITE_URL; ?>/cart.php" style="text-decoration: underline;">View Cart</a>
            </div>
        <?php endif; ?>
        
        <div class="product-detail-grid">
            <!-- Product Image -->
            <div class="product-detail-image">
                <img src="<?php echo htmlspecialchars($product['image_url']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
            </div>
            
            <!-- Product Info -->
            <div class="product-detail-info">
                <h1><?php echo htmlspecialchars($product['name']); ?></h1>
                <div class="product-detail-price"><?php echo formatPrice($product['price']); ?></div>
                
                <p class="product-detail-description"><?php echo htmlspecialchars($product['description']); ?></p>
                
                <form method="POST">
                    <input type="hidden" name="action" value="add_to_cart">
                    
                    <!-- Size Selection -->
                    <?php if (!empty($product['sizes'])): ?>
                        <div class="option-group">
                            <span class="option-label">Size</span>
                            <div class="option-buttons">
                                <?php foreach ($product['sizes'] as $size): ?>
                                    <label class="option-btn">
                                        <input type="radio" name="size" value="<?php echo htmlspecialchars($size); ?>" <?php echo $loop_first = true && isset($product['sizes'][0]) ? 'checked' : ''; ?> style="display: none;">
                                        <?php echo htmlspecialchars($size); ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Color Selection -->
                    <?php if (!empty($product['colors'])): ?>
                        <div class="option-group">
                            <span class="option-label">Color</span>
                            <div class="option-buttons">
                                <?php foreach ($product['colors'] as $index => $color): ?>
                                    <label class="option-btn <?php echo $index === 0 ? 'active' : ''; ?>">
                                        <input type="radio" name="color" value="<?php echo htmlspecialchars($color); ?>" <?php echo $index === 0 ? 'checked' : ''; ?> style="display: none;">
                                        <?php echo htmlspecialchars($color); ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Quantity -->
                    <div class="quantity-selector">
                        <span class="option-label">Quantity</span>
                        <button type="button" class="quantity-btn" onclick="updateQuantity(-1)">-</button>
                        <input type="number" name="quantity" id="quantity" class="quantity-input" value="1" min="1" max="<?php echo $product['stock_quantity']; ?>">
                        <button type="button" class="quantity-btn" onclick="updateQuantity(1)">+</button>
                        <span style="color: var(--medium-gray); margin-left: var(--spacing-md);"><?php echo $product['stock_quantity']; ?> in stock</span>
                    </div>
                    
                    <!-- Add to Cart -->
                    <div class="product-actions">
                        <button type="submit" class="btn btn-primary btn-large btn-block">Add to Cart</button>
                    </div>
                </form>
                
                <!-- Product Details -->
                <div style="margin-top: var(--spacing-xl); border-top: 1px solid var(--lighter-gray); padding-top: var(--spacing-lg);">
                    <h4 style="font-size: 0.875rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: var(--spacing-md);">Product Details</h4>
                    <ul style="color: var(--medium-gray); font-size: 0.875rem; line-height: 2;">
                        <li>Category: <?php echo htmlspecialchars($product['category']); ?></li>
                        <li>SKU: RSC-<?php echo str_pad($product['id'], 4, '0', STR_PAD_LEFT); ?></li>
                        <li>Stock: <?php echo $product['stock_quantity']; ?> units</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
function updateQuantity(delta) {
    const input = document.getElementById('quantity');
    const newValue = parseInt(input.value) + delta;
    if (newValue >= 1 && newValue <= parseInt(input.max)) {
        input.value = newValue;
    }
}

// Option button selection
document.querySelectorAll('.option-btn input').forEach(input => {
    input.addEventListener('change', function() {
        this.parentElement.classList.add('active');
        const siblings = this.parentElement.parentElement.querySelectorAll('.option-btn');
        siblings.forEach(sibling => {
            if (sibling !== this.parentElement) {
                sibling.classList.remove('active');
            }
        });
    });
});
</script>

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