<?php
// /product_detail.php

// FILE SETUP: Initialize connection and functions first.
// This line assumes you have a file that sets up your database connection ($conn)
// and functions like redirect_to(). Your header.php was likely doing this.
require_once 'includes/init.php'; // Or config.php, functions.php, etc.

// --- LOGIC FIRST ---
// All database queries and potential redirects must happen BEFORE the header is included.

// Handle the new SEO-friendly URL structure
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    redirect_to('/listing.php');
}
$product_id = (int)$_GET['id'];
$url_slug = $_GET['slug'] ?? '';

// Fetch product details to check for existence and get the correct slug
$stmt = $conn->prepare("
    SELECT p.id, p.slug
    FROM products p
    JOIN partners pa ON p.partner_user_id = pa.user_id
    WHERE p.id = ? AND pa.status = 'active'
");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$product_check = $stmt->get_result()->fetch_assoc();
$stmt->close();

// If the product doesn't exist, redirect before output starts
if (!$product_check) {
    redirect_to('/listing.php');
}

// SEO REDIRECT LOGIC: This is the critical part that needed to be moved.
// If the slug from the URL doesn't match, 301 redirect to the correct URL.
$correct_slug = $product_check['slug'];
if ($url_slug !== $correct_slug) {
    $correct_url = "/product/{$product_id}/{$correct_slug}";
    // This header() call now works because no HTML has been sent yet.
    header("Location: {$correct_url}", true, 301);
    exit;
}

// --- ALL CHECKS PASSED, NOW WE CAN FETCH FULL DATA & RENDER THE PAGE ---

// Fetch full product details along with partner/seller info
$stmt = $conn->prepare("
    SELECT p.*, u.username as seller_name, u.is_verified
    FROM products p
    JOIN users u ON p.partner_user_id = u.id
    WHERE p.id = ?
");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$product = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Fetch product images
$images_stmt = $conn->prepare("SELECT image_url FROM product_images WHERE product_id = ? ORDER BY is_thumbnail DESC, id ASC");
$images_stmt->bind_param("i", $product_id);
$images_stmt->execute();
$images = $images_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$images_stmt->close();

// Fetch product features
$features_stmt = $conn->prepare("SELECT feature_name, feature_value FROM product_features WHERE product_id = ?");
$features_stmt->bind_param("i", $product_id);
$features_stmt->execute();
$features = $features_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$features_stmt->close();

// Set the page title for the header
$page_title = escape($product['name']);

// --- START HTML OUTPUT ---
// Now that all logic is done, we can safely include the header and start the page.
require_once 'includes/header.php';
?>

<div class="container mx-auto px-4 lg:px-6 py-8">
    <div class="bg-white p-4 md:p-8 rounded-lg shadow-md">
        <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
            
            <div class="lg:col-span-3">
                <div class="mb-4">
                    <img id="main-image" src="/<?php echo escape($images[0]['image_url'] ?? 'assets/images/placeholder.png'); ?>" 
                         alt="<?php echo escape($product['name']); ?>" 
                         class="w-full h-auto max-h-[500px] object-contain rounded-lg shadow-sm bg-gray-100"
                         onerror="this.onerror=null;this.src='https://placehold.co/600x600/e2e8f0/4a5568?text=No+Image';">
                </div>
                <?php if (count($images) > 1): ?>
                <div class="grid grid-cols-5 gap-2">
                    <?php foreach($images as $image): ?>
                    <img src="/<?php echo escape($image['image_url']); ?>" 
                         alt="Thumbnail" 
                         class="w-full h-20 object-cover rounded-md cursor-pointer border-2 border-transparent hover:border-blue-500 transition"
                         onclick="changeImage('<?php echo escape($image['image_url']); ?>')">
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <div class="lg:col-span-2">
                <h1 class="text-3xl font-bold text-gray-800"><?php echo escape($product['name']); ?></h1>
                
                <div class="flex items-center my-4">
                    <span class="text-3xl font-bold text-blue-600">₦<?php echo number_format($product['price'], 2); ?></span>
                    <span class="ml-4 px-3 py-1 text-sm font-semibold rounded-full <?php echo $product['stock'] > 0 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                        <?php echo $product['stock'] > 0 ? 'In Stock' : 'Out of Stock'; ?>
                    </span>
                </div>
                
                <div class="mt-6 p-4 bg-gray-50 rounded-lg border">
                    <h4 class="font-semibold text-gray-700 mb-1">Sold by:</h4>
                    <p class="text-lg text-blue-700 flex items-center">
                        <?php echo escape($product['seller_name']); ?>
                        <?php if ($product['is_verified']): ?>
                            <i data-lucide="shield-check" class="w-5 h-5 ml-2 text-blue-500" title="Verified Seller"></i>
                        <?php endif; ?>
                    </p>
                </div>

                <?php if ($product['stock'] > 0): ?>
                <form action="/cart_actions.php" method="POST" class="mt-8">
                    <input type="hidden" name="action" value="add">
                    <input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
                    
                    <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-4">
                        <div>
                            <label for="quantity" class="sr-only">Quantity</label>
                            <input type="number" name="quantity" id="quantity" value="1" min="1" max="<?php echo $product['stock']; ?>" class="w-full sm:w-24 p-3 border-gray-300 rounded-lg shadow-sm text-center">
                        </div>
                        <button type="submit" class="w-full flex-1 bg-blue-600 text-white font-bold py-3 px-6 rounded-lg hover:bg-blue-700 transition duration-300 flex items-center justify-center">
                            <i data-lucide="shopping-cart" class="w-5 h-5 mr-2"></i>
                            Add to Cart
                        </button>
                    </div>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="mt-12 border-t pt-8">
            <div>
                <h2 class="text-2xl font-bold text-gray-800 mb-4">Product Description</h2>
                <div class="prose max-w-none text-gray-700">
                    <?php echo nl2br(escape($product['description'])); ?>
                </div>
            </div>

            <?php if (!empty($features)): ?>
            <div class="mt-8">
                <h2 class="text-2xl font-bold text-gray-800 mb-4">Features & Specifications</h2>
                <div class="overflow-x-auto">
                    <table class="min-w-full bg-white border">
                        <tbody>
                            <?php foreach ($features as $feature): ?>
                            <tr class="border-t">
                                <td class="px-4 py-3 font-semibold text-gray-600 bg-gray-50 w-1/3"><?php echo escape($feature['feature_name']); ?></td>
                                <td class="px-4 py-3 text-gray-800"><?php echo escape($feature['feature_value']); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
    function changeImage(imageUrl) {
        document.getElementById('main-image').src = '/' + imageUrl;
    }
</script>

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