<?php
require_once __DIR__ . '/config/config.php';
$slug = isset($_GET['slug']) ? trim($_GET['slug']) : '';
if (!$slug) {
    header('Location: products.php');
    exit;
}
$pdo = getDB();
$stmt = $pdo->prepare("SELECT p.*, c.name AS category_name FROM products p LEFT JOIN product_categories c ON p.category_id = c.id WHERE p.slug = ? AND p.is_active = 1 LIMIT 1");
$stmt->execute([$slug]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$product) {
    header('Location: products.php');
    exit;
}
$pageTitle = $product['name'];
$placeholder = (BASE_URL ? BASE_URL . '/' : '') . 'assets/images/placeholder-product.svg';
$imgSrc = !empty($product['image']) ? (BASE_URL ? BASE_URL . '/' : '') . UPLOAD_URL . 'products/' . $product['image'] : $placeholder;
require_once __DIR__ . '/includes/header.php';
?>
<div class="page-content product-detail-page">
    <div class="container">
        <nav class="breadcrumb">
            <a href="<?php echo BASE_URL ? BASE_URL . '/' : ''; ?>index.php">Home</a> &raquo; <a href="<?php echo BASE_URL ? BASE_URL . '/' : ''; ?>products.php">Products</a> &raquo; <?php echo htmlspecialchars($product['name']); ?>
        </nav>
        <div class="product-detail">
            <div class="product-detail-image">
                <img src="<?php echo htmlspecialchars($imgSrc); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" onerror="this.src='<?php echo $placeholder; ?>'">
            </div>
            <div class="product-detail-info">
                <h1><?php echo htmlspecialchars($product['name']); ?></h1>
                <?php if (!empty($product['category_name'])): ?>
                <p class="category">Category: <?php echo htmlspecialchars($product['category_name']); ?></p>
                <?php endif; ?>
                <?php if (!empty($product['description'])): ?>
                <div class="description"><?php echo nl2br(htmlspecialchars($product['description'])); ?></div>
                <?php endif; ?>
                <?php if (!empty($product['specifications'])): ?>
                <div class="specifications">
                    <h3>Specifications</h3>
                    <p><?php echo nl2br(htmlspecialchars($product['specifications'])); ?></p>
                </div>
                <?php endif; ?>
                <p><a href="<?php echo BASE_URL ? BASE_URL . '/' : ''; ?>enquiry.php?product=<?php echo urlencode($product['name']); ?>" class="btn">Enquire about this product</a></p>
            </div>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
