<?php
require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/html_head.php';
require_once __DIR__ . '/includes/header.php';
require_login();

$page_title = t('related_suggestions_title');

// Use product_id and qty from the URL
$product_id = isset($_GET['product_id']) ? (int)$_GET['product_id'] : 0;
$added_qty = isset($_GET['qty']) ? (int)$_GET['qty'] : 0;

// If product_id is invalid, redirect to cart
if ($product_id === 0) {
    header('Location: cart.php');
    exit;
}

$db = db();
$user_id = $_SESSION['user_id'];

// Fetch details for the added product, including the primary image
$stmt = $db->prepare(
    "SELECT
        p.id,
        p.name,
        p.unit,
        p.price_net,
        p.price_gross,
        COALESCE(
            (SELECT CONCAT('uploads/products/', pi.file_path) FROM product_images pi WHERE pi.product_id = p.id AND pi.is_primary = 1),
            (SELECT CONCAT('uploads/products/', pi.file_path) FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.id ASC LIMIT 1)
        ) AS primary_image
    FROM products p
    WHERE p.id = :product_id"
);
$stmt->execute(['product_id' => $product_id]);
$added_product = $stmt->fetch(PDO::FETCH_ASSOC);

// If product somehow doesn't exist, redirect away
if (!$added_product) {
    header('Location: cart.php');
    exit;
}
$added_product_price = getEffectivePrice($db, $added_product['id'], $_SESSION['client_id'] ?? null);


// If image is not found, use a placeholder
if (empty($added_product['primary_image'])) {
    $added_product['primary_image'] = 'assets/pasted-20251212-131440-62c0087c.jpg'; // A default placeholder
}


// Fetch related products (accessories)
$related_products_stmt = $db->prepare(
    "SELECT
        p.id,
        p.name,
        p.unit,
        p.price_net,
        p.price_gross,
        COALESCE(
            (SELECT CONCAT('uploads/products/', pi.file_path) FROM product_images pi WHERE pi.product_id = p.id AND pi.is_primary = 1),
            (SELECT CONCAT('uploads/products/', pi.file_path) FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.id ASC LIMIT 1)
        ) AS primary_image
    FROM products p
    JOIN product_relations pr ON p.id = pr.related_product_id
    WHERE pr.product_id = :product_id AND p.product_role = 'akcesoria'
    GROUP BY p.id
");
$related_products_stmt->execute(['product_id' => $product_id]);
$related_products = $related_products_stmt->fetchAll(PDO::FETCH_ASSOC);

$user_role = get_user_role();
?>

<main class="container my-5">
    <div class="alert alert-success text-center">
        <strong><?= t('product_added_successfully'); ?></strong>
    </div>

    <?php if ($added_product): ?>
    <div class="card shadow-sm mb-4">
        <div class="card-header">
            <h4 class="mb-0"><?= t('you_added_to_cart'); ?></h4>
        </div>
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-2 text-center">
                    <img src="<?= htmlspecialchars($added_product['primary_image']); ?>" class="img-fluid rounded" style="max-height: 120px;" alt="<?= htmlspecialchars($added_product['name']); ?>">
                </div>
                <div class="col-md-5">
                    <h5 class="mb-1"><?= htmlspecialchars($added_product['name']); ?></h5>
                    <?php if ($added_qty > 0): ?>
                    <small class="text-muted"><?= t('quantity'); ?>: <?= $added_qty; ?></small>
                    <?php endif; ?>
                </div>
                <div class="col-md-5">
                    <div class="d-flex justify-content-end align-items-center">
                        <div class="text-end">
                            <p class="mb-0 h5"><strong><?= format_money($added_product_price['gross'], $_SESSION['lang'] ?? 'pl', $db) ?></strong> <small><?= t('gross'); ?></small></p>
                            <p class="mb-0 text-muted"><?= format_money($added_product_price['net'], $_SESSION['lang'] ?? 'pl', $db) ?> <small><?= t('net'); ?></small></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($related_products)): ?>
        <h3 class="mt-5 mb-4"><?= t('related_products_recommendation'); ?></h3>
        <div class="list-group">
            <?php foreach ($related_products as $product):
                $effective_price = getEffectivePrice($db, $product['id'], $_SESSION['client_id'] ?? null);
            ?>
                <div class="list-group-item list-group-item-action">
                    <div class="row align-items-center">
                        <div class="col-md-2 text-center">
                            <a href="product.php?id=<?= $product['id']; ?>">
                                <img src="<?= htmlspecialchars(!empty($product['primary_image']) ? $product['primary_image'] : 'assets/pasted-20251212-131440-62c0087c.jpg'); ?>" class="img-fluid rounded" style="max-height: 100px;" alt="<?= htmlspecialchars($product['name']); ?>">
                            </a>
                        </div>
                        <div class="col-md-4">
                            <a href="product.php?id=<?= $product['id']; ?>" class="text-decoration-none text-dark">
                                <h5 class="mb-1"><?= htmlspecialchars($product['name']); ?></h5>
                            </a>
                            <p class="mb-1">
                                <?php if (!empty($product['unit'])): ?>
                                    <small class="text-muted"><?= t('unit'); ?>: <?= t(htmlspecialchars($product['unit'])); ?></small>
                                <?php endif; ?>
                            </p>
                        </div>
                        <div class="col-md-3">
                            <div class="text-end">
                                <p class="mb-0 h5"><strong><?= format_money($effective_price['gross'], $_SESSION['lang'] ?? 'pl', $db) ?></strong> <small><?= t('gross'); ?></small></p>
                                <p class="mb-0 text-muted"><?= format_money($effective_price['net'], $_SESSION['lang'] ?? 'pl', $db) ?> <small><?= t('net'); ?></small></p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <form action="cart_actions.php" method="post" class="d-flex justify-content-end">
                                <input type="hidden" name="action" value="add">
                                <input type="hidden" name="product_id" value="<?= $product['id']; ?>">
                                <!-- Correctly redirect back to this suggestion page -->
                                <input type="hidden" name="redirect_to" value="related_suggestions.php?product_id=<?= $product_id; ?>">
                                <div class="input-group" style="max-width: 180px;">
                                    <input type="number" name="quantity" class="form-control" value="1" min="1">
                                    <button type="submit" class="btn btn-primary"><i class="bi bi-cart-plus"></i></button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <div class="mt-5 d-flex justify-content-between">
        <a href="index.php" class="btn btn-outline-secondary btn-lg"> <i class="bi bi-arrow-left"></i> <?= t('continue_shopping'); ?></a>
        <a href="cart.php" class="btn btn-success btn-lg"><?= t('go_to_cart'); ?> <i class="bi bi-arrow-right"></i></a>
    </div>

</main>

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