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

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

// Get product details
$product = getProductById($pdo, $product_id);

if (!$product) {
    redirect(SITE_URL . '/products/index.php');
}

// Check if product is favorited
$is_favorited = false;
if (isLoggedIn()) {
    $is_favorited = isProductFavorited($pdo, $_SESSION['user_id'], $product_id);
}

// Handle add to cart
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isLoggedIn()) {
    $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
    
    if (addToCartDB($pdo, $_SESSION['user_id'], $product_id, $quantity)) {
        // Also update localStorage
        echo '<script>
            // Update cart in localStorage to sync with database
            let cart = JSON.parse(localStorage.getItem("cart")) || [];
            const existingItem = cart.find(item => item.id === ' . $product_id . ');
            if (existingItem) {
                existingItem.quantity += ' . $quantity . ';
            } else {
                cart.push({
                    id: ' . $product_id . ',
                    name: "' . htmlspecialchars($product['name']) . '",
                    price: ' . $product['price'] . ',
                    image: "' . (!empty($product['image']) ? (SITE_URL . '/' . htmlspecialchars($product['image'])) : '') . '",
                    quantity: ' . $quantity . '
                });
            }
            localStorage.setItem("cart", JSON.stringify(cart));
            updateCartCount();
        </script>';
        $message = '<div class="message success">Product added to cart successfully.</div>';
    } else {
        $message = '<div class="message error">Error adding product to cart.</div>';
    }
}
?>

<div class="container">
    <div class="product-detail">
        <div class="product-image-large">
            <?php if (!empty($product['image'])): ?>
                <img src="<?php echo SITE_URL . '/' . htmlspecialchars($product['image']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
            <?php else: ?>
                <i class="fas fa-image" style="font-size: 8rem; color: #ccc;"></i>
            <?php endif; ?>
            <?php if (isLoggedIn()): ?>
                <button class="favorite-btn <?php echo $is_favorited ? 'active' : ''; ?>" data-product-id="<?php echo $product['id']; ?>" style="position: absolute; top: 10px; right: 10px; z-index: 10;">
                    <i class="fas fa-heart"></i>
                </button>
            <?php endif; ?>
        </div>
        
        <div class="product-info-large">
            <h1><?php echo htmlspecialchars($product['name']); ?></h1>
            <div class="product-price-large">$<?php echo number_format($product['price'], 2); ?></div>
            <div class="product-category">Category: <?php echo htmlspecialchars($product['category']); ?></div>
            <div class="product-description">
                <?php echo htmlspecialchars($product['description']); ?>
            </div>
            
            <?php if (isLoggedIn()): ?>
                <?php echo $message ?? ''; ?>
                <form method="POST" action="">
                    <div class="form-group">
                        <label for="quantity">Quantity:</label>
                        <input type="number" id="quantity" name="quantity" min="1" value="1" style="width: 80px;">
                    </div>
                    <button type="submit" class="btn btn-primary btn-large">Add to Cart</button>
                </form>
            <?php else: ?>
                <p><a href="<?php echo SITE_URL; ?>/auth/login.php" class="btn btn-primary btn-large">Login to Purchase</a></p>
            <?php endif; ?>
        </div>
    </div>
</div>

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