<?php
require_once 'config.php';

$id = $_GET['id'] ?? '';
if (empty($id)) {
    header('Location: index.php');
    exit;
}

// Fetch product details
$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.id = ?");
$stmt->execute([$id]);
$product = $stmt->fetch();

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

$message = '';
$error = '';

// Handle add-to-cart action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_to_cart'])) {
    if (!isLoggedIn()) {
        header('Location: login.php');
        exit;
    }
    
    $qty = intval($_POST['quantity']);
    if ($qty < 1) $qty = 1;
    
    if ($qty > $product['stock']) {
        $error = "Sorry, only {$product['stock']} items available in stock.";
    } else {
        $user_id = $_SESSION['user_id'];
        // Check if item is already in the cart
        $stmt_check = $pdo->prepare("SELECT id, quantity FROM cart WHERE user_id = ? AND product_id = ?");
        $stmt_check->execute([$user_id, $product['id']]);
        $existing_cart = $stmt_check->fetch();
        
        if ($existing_cart) {
            $new_qty = $existing_cart['quantity'] + $qty;
            if ($new_qty > $product['stock']) {
                $error = "Cannot add more. Total quantity in cart exceeds available stock.";
            } else {
                $stmt_update = $pdo->prepare("UPDATE cart SET quantity = ? WHERE id = ?");
                $stmt_update->execute([$new_qty, $existing_cart['id']]);
                $message = "Cart updated successfully!";
            }
        } else {
            $stmt_insert = $pdo->prepare("INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?)");
            $stmt_insert->execute([$user_id, $product['id'], $qty]);
            $message = "Added to cart successfully!";
        }
        
        // Refresh cart count session info or simply rely on database query in header
    }
}
?>
<?php include 'header.php'; ?>

<div class="container">
    <a href="index.php" style="display: inline-block; margin-bottom: 20px; font-weight: 500; color: var(--text-muted);">&larr; Back to Shop</a>
    
    <?php if (!empty($message)): ?>
        <div class="alert alert-success"><?php echo $message; ?></div>
    <?php endif; ?>
    
    <?php if (!empty($error)): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>

    <div class="product-detail-container">
        <div class="detail-image">
            <img src="<?php echo htmlspecialchars($product['image_url']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
        </div>
        <div class="detail-info">
            <span class="badge badge-delivered" style="margin-bottom: 15px;"><?php echo htmlspecialchars($product['category_name'] ?? 'General'); ?></span>
            <h2><?php echo htmlspecialchars($product['name']); ?></h2>
            <div class="detail-price">฿<?php echo number_format($product['price'], 2); ?></div>
            
            <p class="detail-desc"><?php echo nl2br(htmlspecialchars($product['description'])); ?></p>
            
            <div style="margin-bottom: 20px; font-size: 14px;">
                <strong>Availability:</strong> 
                <?php if ($product['stock'] > 0): ?>
                    <span style="color: var(--success); font-weight: 600;"><?php echo $product['stock']; ?> items in stock</span>
                <?php else: ?>
                    <span style="color: var(--danger); font-weight: 600;">Out of Stock</span>
                <?php endif; ?>
            </div>

            <?php if ($product['stock'] > 0): ?>
                <form action="product_detail.php?id=<?php echo $product['id']; ?>" method="POST">
                    <input type="hidden" name="add_to_cart" value="1">
                    <div class="detail-action">
                        <div class="quantity-selector">
                            <button type="button" onclick="changeQty(-1)">&minus;</button>
                            <input type="number" id="qty-input" name="quantity" value="1" min="1" max="<?php echo $product['stock']; ?>" readonly>
                            <button type="button" onclick="changeQty(1)">&plus;</button>
                        </div>
                        <button type="submit" class="btn btn-primary">Add to Shopping Cart</button>
                    </div>
                </form>
            <?php endif; ?>

            <div style="border-top: 1px solid var(--gray-border); padding-top: 20px; font-size: 13px; color: var(--text-muted);">
                ✨ <strong>Earn Rewards:</strong> You will earn approximately <strong><?php echo floor($product['price'] * POINTS_EARN_RATE); ?> points</strong> from purchasing this item!
            </div>
        </div>
    </div>
</div>

<script>
function changeQty(amount) {
    const input = document.getElementById('qty-input');
    let val = parseInt(input.value) + amount;
    const max = parseInt(input.getAttribute('max'));
    if (val < 1) val = 1;
    if (val > max) val = max;
    input.value = val;
}
</script>

<?php include 'footer.php'; ?>
