<?php
// This line is now required at the top of pages that use the header.
require_once __DIR__ . '/includes/init.php';
require_login();

$product_id = $_GET['id'] ?? null;

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

try {
    $pdo = db();
    $stmt = $pdo->prepare("SELECT p.* FROM products p WHERE p.id = :product_id");
    $stmt->execute(['product_id' => $product_id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);

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

    // Get the correct price pair using the centralized function
    $prices = getEffectivePrice($pdo, $product['id'], $_SESSION['client_id'] ?? null);

    // Fetch product images
    $img_stmt = $pdo->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY is_primary DESC, id ASC");
    $img_stmt->execute([$product_id]);
    $product_images = $img_stmt->fetchAll(PDO::FETCH_ASSOC);
    $primary_image = $product_images[0] ?? null;

    // Fetch product materials
    $materials_stmt = $pdo->prepare("SELECT * FROM product_materials WHERE product_id = ? ORDER BY created_at ASC");
    $materials_stmt->execute([$product_id]);
    $product_materials = $materials_stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die(t('db_connection_error') . $e->getMessage());
}

$page_title = htmlspecialchars($product['name']);

require_once __DIR__ . '/includes/html_head.php';
require_once __DIR__ . '/includes/header.php';
?>

    <main class="container my-5">
        <a href="index.php" class="btn btn-outline-secondary mb-3">
        ← <?= t('back_to_product_list') ?>
        </a>
        <div class="row">
            <!-- Product Image Gallery -->
            <div class="col-lg-6 mb-4 mb-lg-0">
                <div class="text-center">
                    <?php
                    $primary_image_url = 'https://placehold.co/600x400/EEE/31343C?text='.t('no_image_placeholder');
                    if (!empty($product_images)) {
                        $primary_image_url = BASE_URL . 'uploads/products/' . htmlspecialchars($product_images[0]['file_path']);
                    }
                    ?>
                    <img src="<?= $primary_image_url ?>" alt="<?= htmlspecialchars($product['name']) ?>" class="img-fluid rounded shadow-sm mb-3" id="main-product-image">
                </div>

                <?php if (count($product_images) > 1): ?>
                    <div class="row gx-2 justify-content-center">
                        <?php foreach ($product_images as $image): ?>
                            <div class="col-2">
                                <a href="<?= BASE_URL . 'uploads/products/' . htmlspecialchars($image['file_path']) ?>" class="product-thumbnail d-block border rounded">
                                    <img src="<?= BASE_URL . 'uploads/products/' . htmlspecialchars($image['file_path']) ?>" alt="<?= t('product_thumbnail_alt') ?>" class="img-fluid">
                                </a>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Product Details -->
            <div class="col-lg-6">
                <h1 class="mb-3"><?= htmlspecialchars($product['name']) ?></h1>

                <div class="bg-light p-4 rounded mb-4">
                    <p class="h4 fw-bold mb-1"><?= format_money($prices['gross'], $_SESSION['lang'] ?? 'pl', $pdo) ?> <span class="fs-6 fw-normal"><?= t('gross') ?></span></p>
                    <p class="text-muted mb-0"><?= format_money($prices['net'], $_SESSION['lang'] ?? 'pl', $pdo) ?> <span class="fs-6 fw-normal"><?= t('net') ?></span></p>
                    <hr class="my-2">
                    <small class="text-muted"><?= t('price_per') ?>: <?= t(htmlspecialchars($product['unit'])) ?></small>
                </div>

                <form action="cart_actions.php" method="post" class="d-flex align-items-center">
                    <input type="hidden" name="action" value="add">
                    <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                    <div style="max-width: 200px;" class="me-3">
                        <label for="quantity" class="form-label"><?= t('quantity_label') ?> (<?= t(htmlspecialchars($product['unit'])) ?>):</label>
                        <input type="number" id="quantity" name="quantity" class="form-control" value="1" min="1">
                    </div>
                    <button type="submit" class="btn btn-primary mt-4">
                        <i class="bi bi-cart-plus"></i> <?= t('btn_add_to_cart') ?>
                    </button>
                </form>
            </div>
        </div>

        <!-- Additional Info Tabs -->
        <div class="mt-5">
            <ul class="nav nav-tabs" id="productTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="description-tab" data-bs-toggle="tab" data-bs-target="#description" type="button" role="tab" aria-controls="description" aria-selected="true"><?= t('description_tab') ?></button>
                </li>
                 <li class="nav-item" role="presentation">
                    <button class="nav-link" id="specs-tab" data-bs-toggle="tab" data-bs-target="#specs" type="button" role="tab" aria-controls="specs" aria-selected="false"><?= t('technical_data_tab') ?></button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="documents-tab" data-bs-toggle="tab" data-bs-target="#documents" type="button" role="tab" aria-controls="documents" aria-selected="false"><?= t('documents_tab') ?></button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="related-tab" data-bs-toggle="tab" data-bs-target="#related" type="button" role="tab" aria-controls="related" aria-selected="false"><?= t('related_products_tab') ?></button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="materials-tab" data-bs-toggle="tab" data-bs-target="#materials" type="button" role="tab" aria-controls="materials" aria-selected="false"><?= t('additional_materials_tab') ?></button>
                </li>
            </ul>
            <div class="tab-content p-3 border border-top-0" id="productTabsContent">
                <div class="tab-pane fade show active" id="description" role="tabpanel" aria-labelledby="description-tab">
                    <p class="lead mb-4"><?= nl2br(htmlspecialchars($product['description'])) ?></p>
                </div>
                <div class="tab-pane fade" id="specs" role="tabpanel" aria-labelledby="specs-tab">
                    <?php
                    $attrs_stmt = $pdo->prepare("SELECT ak.name, pa.value FROM product_attributes pa JOIN attribute_keys ak ON pa.attribute_key_id = ak.id WHERE pa.product_id = ? AND pa.value IS NOT NULL AND pa.value != '' ORDER BY ak.name");
                    $attrs_stmt->execute([$product_id]);
                    $product_attributes = $attrs_stmt->fetchAll(PDO::FETCH_ASSOC);

                    if ($product_attributes) {
                        echo '<table class="table table-striped">';
                        echo '<tbody>';
                        foreach ($product_attributes as $attr) {
                            echo '<tr>';
                            echo '<th>' . htmlspecialchars($attr['name']) . '</th>';
                            echo '<td>' . htmlspecialchars($attr['value']) . '</td>';
                            echo '</tr>';
                        }
                        echo '</tbody>';
                        echo '</table>';
                    } else {
                        echo '<p>' . t('no_technical_data') . '</p>';
                    }
                    ?>
                </div>
                <div class="tab-pane fade" id="documents" role="tabpanel" aria-labelledby="documents-tab">
                    <?php
                    $docs_stmt = $pdo->prepare("SELECT * FROM product_documents WHERE product_id = ?");
                    $docs_stmt->execute([$product_id]);
                    $product_documents = $docs_stmt->fetchAll(PDO::FETCH_ASSOC);

                    if ($product_documents) {
                        echo '<ul class="list-group list-group-flush">';
                        foreach ($product_documents as $doc) {
                            echo '<li class="list-group-item"><a href="' . BASE_URL . 'uploads/documents/' . htmlspecialchars($doc['file_path']) . '" download><i class="bi bi-file-earmark-arrow-down"></i> ' . htmlspecialchars($doc['file_name']) . '</a></li>';
                        }
                        echo '</ul>';
                    } else {
                        echo '<p class="mb-0">' . t('no_documents') . '</p>';
                    }
                    ?>
                </div>
                <div class="tab-pane fade" id="related" role="tabpanel" aria-labelledby="related-tab">
                    <div class="row">
                    <?php
                    $related_sql = "SELECT
                                        p.*,
                                        (SELECT file_path FROM product_images WHERE product_id = p.id ORDER BY is_primary DESC, id ASC LIMIT 1) AS image_path
                                    FROM products p
                                    JOIN product_relations pr ON p.id = pr.related_product_id
                                    WHERE pr.product_id = ?";
                    $related_products_stmt = $pdo->prepare($related_sql);
                    $related_products_stmt->execute([$product_id]);
                    $related_products = $related_products_stmt->fetchAll(PDO::FETCH_ASSOC);

                    if ($related_products) {
                        foreach ($related_products as $related_product) {
                            $related_image_url = !empty($related_product['image_path'])
                                ? BASE_URL . 'uploads/products/' . htmlspecialchars($related_product['image_path'])
                                : 'https://placehold.co/300x300/EEE/31343C?text='.t('no_image_placeholder');

                            echo '<div class="col-md-3 mb-3">';
                            echo '<div class="card h-100 product-card shadow-sm">';
                            echo '<a href="product.php?id=' . $related_product['id'] . '">';
                            echo '<img src="' . $related_image_url . '" class="card-img-top" alt="' . htmlspecialchars($related_product['name']) . '" style="height: 150px; object-fit: cover;">';
                            echo '</a>';
                            echo '<div class="card-body">';
                            echo '<h6 class="card-title"><a href="product.php?id=' . $related_product['id'] . '" class="text-decoration-none text-dark stretched-link">' . htmlspecialchars($related_product['name']) . '</a></h6>';
                            echo '</div>';
                            echo '</div>';
                            echo '</div>';
                        }
                    } else {
                        echo '<p class="mb-0">' . t('no_related_products') . '</p>';
                    }
                    ?>
                    </div>
                </div>
                <div class="tab-pane fade" id="materials" role="tabpanel" aria-labelledby="materials-tab">
                    <?php
                    if ($product_materials) {
                        echo '<div class="list-group list-group-flush">';
                        foreach ($product_materials as $material) {
                            echo '<div class="list-group-item">';
                            echo '<h5>' . htmlspecialchars($material['title']) . '</h5>';
                            switch ($material['material_type']) {
                                case 'pdf':
                                    echo '<a href="' . BASE_URL . 'uploads/products/' . htmlspecialchars($material['path']) . '" download><i class="bi bi-file-earmark-arrow-down"></i> Pobierz PDF</a>';
                                    break;
                                case 'image':
                                    echo '<img src="' . BASE_URL . 'uploads/products/' . htmlspecialchars($material['path']) . '" class="img-fluid rounded shadow-sm">';
                                    break;
                                case 'youtube':
                                    $video_id = '';
                                    if (preg_match('/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:embed\/|watch\?v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/', $material['url'], $matches)) {
                                        $video_id = $matches[1];
                                    }
                                    if ($video_id) {
                                        echo '<div class="ratio ratio-16x9"><iframe src="https://www.youtube.com/embed/' . $video_id . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>';
                                    } else {
                                        echo '<p>' . t('invalid_youtube_url') . '</p>';
                                    }
                                    break;
                            }
                            echo '</div>';
                        }
                        echo '</div>';
                    } else {
                        echo '<p class="mb-0">' . t('no_additional_materials') . '</p>';
                    }
                    ?>
                </div>
            </div>
        </div>
    </main>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    const mainImage = document.getElementById('main-product-image');
    const thumbnails = document.querySelectorAll('.product-thumbnail');

    thumbnails.forEach(thumbnail => {
        thumbnail.addEventListener('click', function(event) {
            event.preventDefault();
            mainImage.src = this.href;

            thumbnails.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
        });
    });
});
</script>