<?php
// Require authentication
require_once 'includes/auth.php';
requireAuth();

// Get product slug from URL
$slug = isset($_GET['slug']) ? trim($_GET['slug']) : '';

if (empty($slug)) {
    header('Location: products.php');
    exit;
}

// Fetch product data
require_once '../database/config.php';
$db = Database::getInstance()->getConnection();

try {
    // Get product with collections
    $stmt = $db->prepare("
        SELECT 
            p.*,
            GROUP_CONCAT(DISTINCT c.name SEPARATOR ', ') as collections
        FROM products p
        LEFT JOIN product_collections pc ON p.id = pc.product_id
        LEFT JOIN collections c ON pc.collection_id = c.id
        WHERE p.slug = ?
        GROUP BY p.id
    ");
    $stmt->execute([$slug]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$product) {
        header('Location: products.php');
        exit;
    }
    
    // Get variants
    $stmt = $db->prepare("
        SELECT * FROM product_variants 
        WHERE product_id = ? AND is_active = 1
        ORDER BY variant_name
    ");
    $stmt->execute([$product['id']]);
    $variants = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get product images
    $stmt = $db->prepare("
        SELECT * FROM product_images 
        WHERE product_id = ?
        ORDER BY is_featured DESC, sort_order ASC
    ");
    $stmt->execute([$product['id']]);
    $images = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Calculate inventory totals
    $totalInventory = 0;
    $committedInventory = 0;
    foreach ($variants as $variant) {
        $totalInventory += $variant['inventory_quantity'];
        // Committed would come from orders - simplified for now
    }
    $availableInventory = $totalInventory - $committedInventory;
    
} catch (Exception $e) {
    error_log('Product detail error: ' . $e->getMessage());
    header('Location: products.php');
    exit;
}
?>
<?php include 'header.php'; ?>

<div class="page-wrapper">
    <div class="page-content">
        <div class="container-fluid">
            <!-- Page Title -->
            <div class="row">
                <div class="col-sm-12">
                    <div class="page-title-box d-md-flex justify-content-md-between align-items-center">
                        <h4 class="page-title">Product Details</h4>
                        <div class="">
                            <ol class="breadcrumb mb-0">
                                <li class="breadcrumb-item"><a href="products.php">Products</a></li>
                                <li class="breadcrumb-item active"><?php echo htmlspecialchars($product['title']); ?></li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <div class="row">
                <!-- Left Column: Product Info & Media -->
                <div class="col-lg-8">
                    <!-- Product Header Card -->
                    <div class="card">
                        <div class="card-body">
                            <div class="d-flex align-items-start">
                                <div class="flex-grow-1">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span class="badge <?php 
                                            echo $product['status'] === 'active' ? 'bg-success-subtle text-success' : 
                                                ($product['status'] === 'draft' ? 'bg-warning-subtle text-warning' : 'bg-secondary-subtle text-secondary'); 
                                        ?>">
                                            <?php echo ucfirst($product['status']); ?>
                                        </span>
                                        <div class="dropdown">
                                            <a href="#" class="btn btn-sm btn-outline-secondary" type="button">
                                                <i class="fas fa-external-link-alt me-1"></i> Preview
                                            </a>
                                            <a href="edit-product.php?slug=<?php echo urlencode($product['slug']); ?>" class="btn btn-sm btn-primary ms-2">
                                                <i class="fas fa-pen me-1"></i> Edit Product
                                            </a>
                                        </div>
                                    </div>
                                    <h3 class="mb-1"><?php echo htmlspecialchars($product['title']); ?></h3>
                                    <p class="text-muted mb-3"><?php echo htmlspecialchars($product['collections'] ?: 'Uncategorized'); ?></p>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <h5 class="font-14 text-muted">Price</h5>
                                            <h4 class="mb-0">
                                                $<?php echo number_format($product['price'], 2); ?>
                                                <?php if ($product['compare_at_price']): ?>
                                                    <small class="text-muted text-decoration-line-through ms-2">
                                                        $<?php echo number_format($product['compare_at_price'], 2); ?>
                                                    </small>
                                                <?php endif; ?>
                                            </h4>
                                        </div>
                                        <div class="col-md-6">
                                            <h5 class="font-14 text-muted">SKU</h5>
                                            <p class="mb-0"><?php echo htmlspecialchars($product['sku'] ?: 'N/A'); ?></p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Media Gallery -->
                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title mb-0">Media</h4>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($images)): ?>
                                <div class="row g-2">
                                    <div class="col-md-8">
                                        <div class="border rounded p-2 text-center bg-light">
                                            <img src="<?php echo htmlspecialchars($images[0]['image_path'] ?? 'assets/images/products/01.png'); ?>" 
                                                 alt="Main Image" class="img-fluid" style="max-height: 400px;">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="row g-2">
                                            <?php for ($i = 1; $i < min(4, count($images)); $i++): ?>
                                                <div class="col-4">
                                                    <div class="border rounded p-1 text-center bg-light">
                                                        <img src="<?php echo htmlspecialchars($images[$i]['image_path']); ?>" 
                                                             alt="Gallery <?php echo $i; ?>" class="img-fluid" style="max-height: 100px;">
                                                    </div>
                                                </div>
                                            <?php endfor; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div class="border rounded p-5 text-center bg-light">
                                    <i class="las la-image fs-1 text-muted"></i>
                                    <p class="text-muted mt-2">No images available</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Description -->
                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title mb-0">Description</h4>
                        </div>
                        <div class="card-body">
                            <?php if ($product['description']): ?>
                                <div class="text-dark">
                                    <?php echo nl2br(htmlspecialchars($product['description'])); ?>
                                </div>
                            <?php else: ?>
                                <p class="text-muted">No description available</p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Variants Table -->
                    <?php if (!empty($variants)): ?>
                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title mb-0">Variants (<?php echo count($variants); ?>)</h4>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Variant</th>
                                            <th>Price</th>
                                            <th>SKU</th>
                                            <th>Inventory</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($variants as $variant): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($variant['variant_name']); ?></td>
                                            <td>$<?php echo number_format($variant['price'], 2); ?></td>
                                            <td><?php echo htmlspecialchars($variant['sku'] ?: 'N/A'); ?></td>
                                            <td>
                                                <?php echo $variant['inventory_quantity']; ?> available
                                                <?php if ($variant['inventory_quantity'] == 0): ?>
                                                    <span class="badge bg-danger-subtle text-danger ms-1">Out of Stock</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Right Column: Stats & Organization -->
                <div class="col-lg-4">
                    <!-- Organization -->
                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title mb-0">Organization</h4>
                        </div>
                        <div class="card-body">
                            <div class="mb-1">
                                <label class="text-muted small">Collections</label>
                                <p class="fw-medium"><?php echo htmlspecialchars($product['collections'] ?: 'Uncategorized'); ?></p>
                            </div>
                            <div class="mb-1">
                                <label class="text-muted small">Status</label>
                                <p class="fw-medium"><?php echo ucfirst($product['status']); ?></p>
                            </div>
                            <div class="mb-0">
                                <label class="text-muted small">Created</label>
                                <p class="fw-medium"><?php echo date('M d, Y', strtotime($product['created_at'])); ?></p>
                            </div>
                        </div>
                    </div>

                    <!-- Inventory Summary -->
                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title mb-0">Inventory Summary</h4>
                        </div>
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-dark">Total Variants</span>
                                <span class="fw-bold"><?php echo count($variants); ?></span>
                            </div>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-dark">Total Stock</span>
                                <span class="fw-bold"><?php echo $totalInventory; ?></span>
                            </div>
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="text-dark">Available</span>
                                <span class="fw-bold text-primary"><?php echo $availableInventory; ?></span>
                            </div>
                        </div>
                    </div>

                    <!-- Product Info -->
                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title mb-0">Product Information</h4>
                        </div>
                        <div class="card-body">
                            <div class="mb-2">
                                <label class="text-muted small">Product ID</label>
                                <p class="fw-medium">#<?php echo $product['id']; ?></p>
                            </div>
                            <div class="mb-2">
                                <label class="text-muted small">Slug</label>
                                <p class="fw-medium"><code><?php echo htmlspecialchars($product['slug']); ?></code></p>
                            </div>
                            <div class="mb-0">
                                <label class="text-muted small">Last Updated</label>
                                <p class="fw-medium"><?php echo date('M d, Y h:i A', strtotime($product['updated_at'])); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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