<?php
/**
 * ============================================================================
 * marketplace/product-details.php - Enhanced Product Detail Page
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$userId = getUserId();
$productId = $_GET['id'] ?? null;

if (!$productId) {
    redirect('/marketplace/', 'Product not found', 'error');
}

// Get database connection
$database = new Database();
$db = $database->getConnection();

// Get product
$productClass = new \App\Product($db);
$product = $productClass->getById($productId);

if (!$product) {
    redirect('/marketplace/', 'Product not found', 'error');
}

$pageTitle = $product['product_name'] . ' - Marketplace';

// Get related products
$relatedProducts = $productClass->getRelated($productId, $product['category'], 4);

// Check if current user is the seller
$isSeller = ($userId == $product['seller_id']);

// Check if product is in favorites
$sql = "SELECT id FROM favorites WHERE user_id = ? AND product_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$userId, $productId]);
$isFavorite = $stmt->fetch(PDO::FETCH_ASSOC) !== false;

global $PRODUCT_CATEGORIES;

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <!-- Breadcrumb -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="<?php echo APP_URL; ?>/dashboard/">Home</a></li>
            <li class="breadcrumb-item"><a href="<?php echo APP_URL; ?>/marketplace/">Marketplace</a></li>
            <li class="breadcrumb-item active"><?php echo htmlspecialchars($product['product_name']); ?></li>
        </ol>
    </nav>

    <div class="row">
        <!-- Product Images -->
        <div class="col-lg-5 mb-4">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-0">
                    <?php if (!empty($product['images']) && is_array($product['images']) && count($product['images']) > 0): ?>
                        <!-- Main Image Display -->
                        <div class="position-relative" id="mainImageContainer">
                            <img src="<?php echo APP_URL . '/' . htmlspecialchars($product['images'][0]); ?>" 
                                 class="img-fluid w-100 rounded-top" 
                                 id="mainProductImage"
                                 alt="<?php echo htmlspecialchars($product['product_name']); ?>"
                                 style="max-height: 500px; object-fit: contain; background: #f8f9fa;"
                                 onerror="this.src='<?php echo APP_URL; ?>/assets/images/no-image.png'">
                            
                            <!-- Image Counter Badge -->
                            <?php if (count($product['images']) > 1): ?>
                            <span class="position-absolute bottom-0 end-0 m-3 badge bg-dark bg-opacity-75">
                                <i class="bi bi-images"></i> <span id="imageCounter">1</span> / <?php echo count($product['images']); ?>
                            </span>
                            <?php endif; ?>
                            
                            <!-- Favorite Button -->
                            <?php if (!$isSeller): ?>
                            <button class="btn btn-light position-absolute top-0 end-0 m-3 favorite-btn <?php echo $isFavorite ? 'active' : ''; ?>" 
                                    id="favoriteBtn"
                                    data-product-id="<?php echo $product['id']; ?>"
                                    title="Add to favorites">
                                <i class="bi bi-heart<?php echo $isFavorite ? '-fill' : ''; ?>"></i>
                            </button>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Thumbnail Gallery -->
                        <?php if (count($product['images']) > 1): ?>
                            <div class="d-flex gap-2 overflow-auto p-3" id="thumbnailGallery">
                                <?php foreach ($product['images'] as $index => $image): ?>
                                    <img src="<?php echo APP_URL . '/' . htmlspecialchars($image); ?>" 
                                         class="img-thumbnail cursor-pointer thumbnail-image <?php echo $index === 0 ? 'active' : ''; ?>" 
                                         style="width: 80px; height: 80px; object-fit: cover; flex-shrink: 0;"
                                         data-index="<?php echo $index; ?>"
                                         onclick="changeMainImage(<?php echo $index; ?>)"
                                         onerror="this.style.display='none'"
                                         alt="Thumbnail <?php echo $index + 1; ?>">
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <!-- No Image Placeholder -->
                        <div class="bg-light d-flex align-items-center justify-content-center rounded" style="height: 500px;">
                            <div class="text-center text-muted">
                                <i class="bi bi-image" style="font-size: 5rem;"></i>
                                <p class="mt-3">No images available</p>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Quick Actions for Seller -->
            <?php if ($isSeller): ?>
            <div class="card border-0 shadow-sm mt-3">
                <div class="card-body">
                    <h6 class="mb-3"><i class="bi bi-gear"></i> Product Management</h6>
                    <div class="d-grid gap-2">
                        <a href="<?php echo APP_URL; ?>/marketplace/edit-product.php?id=<?php echo $product['id']; ?>" 
                           class="btn btn-primary">
                            <i class="bi bi-pencil"></i> Edit Product
                        </a>
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-outline-success" 
                                    onclick="changeStatus(<?php echo $product['id']; ?>, 'available')">
                                <i class="bi bi-check-circle"></i> Available
                            </button>
                            <button type="button" class="btn btn-outline-warning" 
                                    onclick="changeStatus(<?php echo $product['id']; ?>, 'reserved')">
                                <i class="bi bi-bookmark"></i> Reserved
                            </button>
                            <button type="button" class="btn btn-outline-secondary" 
                                    onclick="changeStatus(<?php echo $product['id']; ?>, 'sold')">
                                <i class="bi bi-currency-dollar"></i> Sold
                            </button>
                        </div>
                        <button class="btn btn-outline-danger" onclick="deleteProduct(<?php echo $product['id']; ?>)">
                            <i class="bi bi-trash"></i> Delete Product
                        </button>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Product Information -->
        <div class="col-lg-7 mb-4">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <!-- Category & Status Badges -->
                    <div class="mb-3">
                        <span class="badge" style="background-color: <?php echo getCategoryColor($product['category']); ?>; font-size: 0.9rem;">
                            <?php echo $PRODUCT_CATEGORIES[$product['category']]['icon'] ?? ''; ?>
                            <?php echo $PRODUCT_CATEGORIES[$product['category']]['name'] ?? $product['category']; ?>
                        </span>
                        <span class="badge bg-<?php echo getStatusBadgeClass($product['status']); ?> ms-2" style="font-size: 0.9rem;">
                            <?php echo ucfirst($product['status']); ?>
                        </span>
                    </div>

                    <!-- Product Name -->
                    <h2 class="mb-3"><?php echo htmlspecialchars($product['product_name']); ?></h2>

                    <!-- Price -->
                    <div class="mb-4 p-3 bg-light rounded">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <h3 class="text-success mb-0">
                                    <?php echo formatCurrency($product['price_per_unit']); ?>
                                    <small class="text-muted fs-5">per <?php echo htmlspecialchars($product['unit']); ?></small>
                                </h3>
                            </div>
                            <div class="col-md-6 text-md-end mt-2 mt-md-0">
                                <div class="text-muted small">Total Value</div>
                                <div class="fw-bold text-dark">
                                    <?php echo formatCurrency($product['price_per_unit'] * $product['quantity']); ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Key Info -->
                    <div class="row mb-4">
                        <div class="col-6 col-md-3 mb-3">
                            <div class="text-center p-3 bg-light rounded">
                                <i class="bi bi-box text-primary fs-3 d-block mb-2"></i>
                                <div class="text-muted small">Quantity</div>
                                <div class="fw-semibold"><?php echo number_format($product['quantity'], 2); ?></div>
                                <div class="small text-muted"><?php echo htmlspecialchars($product['unit']); ?></div>
                            </div>
                        </div>
                        
                        <?php if (!empty($product['location'])): ?>
                        <div class="col-6 col-md-3 mb-3">
                            <div class="text-center p-3 bg-light rounded">
                                <i class="bi bi-geo-alt text-danger fs-3 d-block mb-2"></i>
                                <div class="text-muted small">Location</div>
                                <div class="fw-semibold small"><?php echo truncate($product['location'], 20); ?></div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <div class="col-6 col-md-3 mb-3">
                            <div class="text-center p-3 bg-light rounded">
                                <i class="bi bi-eye text-info fs-3 d-block mb-2"></i>
                                <div class="text-muted small">Views</div>
                                <div class="fw-semibold"><?php echo number_format($product['views']); ?></div>
                            </div>
                        </div>
                        
                        <div class="col-6 col-md-3 mb-3">
                            <div class="text-center p-3 bg-light rounded">
                                <i class="bi bi-calendar text-success fs-3 d-block mb-2"></i>
                                <div class="text-muted small">Listed</div>
                                <div class="fw-semibold small"><?php echo timeAgo($product['created_at']); ?></div>
                            </div>
                        </div>
                    </div>

                    <!-- Description -->
                    <?php if (!empty($product['description'])): ?>
                    <div class="mb-4">
                        <h5 class="mb-3"><i class="bi bi-file-text"></i> Description</h5>
                        <p class="text-muted"><?php echo nl2br(htmlspecialchars($product['description'])); ?></p>
                    </div>
                    <?php endif; ?>

                    <!-- Seller Information -->
                    <div class="card bg-light border-0 mb-4">
                        <div class="card-body">
                            <h5 class="mb-3"><i class="bi bi-person-circle"></i> Seller Information</h5>
                            <div class="d-flex align-items-center mb-3">
                                <img src="<?php echo getAvatarUrl($product['seller_avatar']); ?>" 
                                     class="rounded-circle me-3" 
                                     width="60" height="60"
                                     alt="Seller">
                                <div class="flex-grow-1">
                                    <h6 class="mb-1"><?php echo htmlspecialchars($product['seller_name']); ?></h6>
                                    <?php if ($product['seller_rating']): ?>
                                        <div class="text-warning mb-1">
                                            <?php 
                                            $rating = $product['seller_rating'];
                                            for ($i = 1; $i <= 5; $i++) {
                                                if ($i <= floor($rating)) {
                                                    echo '<i class="bi bi-star-fill"></i> ';
                                                } elseif ($i - 0.5 <= $rating) {
                                                    echo '<i class="bi bi-star-half"></i> ';
                                                } else {
                                                    echo '<i class="bi bi-star"></i> ';
                                                }
                                            }
                                            ?>
                                            <span class="text-muted small">(<?php echo $product['seller_reviews']; ?> reviews)</span>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (!$isSeller): ?>
                                    <a href="tel:<?php echo $product['seller_phone']; ?>" class="small text-primary">
                                        <i class="bi bi-telephone"></i> <?php echo formatPhone($product['seller_phone']); ?>
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons for Buyers -->
                    <?php if (!$isSeller): ?>
                    <div class="d-grid gap-2">
                        <?php if ($product['status'] === 'available'): ?>
                            <a href="<?php echo APP_URL; ?>/chat/?user=<?php echo $product['seller_id']; ?>" 
                               class="btn btn-success btn-lg">
                                <i class="bi bi-chat-dots"></i> Contact Seller
                            </a>
                            <a href="tel:<?php echo $product['seller_phone']; ?>" 
                               class="btn btn-primary btn-lg">
                                <i class="bi bi-telephone"></i> Call Now
                            </a>
                        <?php else: ?>
                            <div class="alert alert-warning mb-0">
                                <i class="bi bi-exclamation-triangle"></i> 
                                This product is currently <strong><?php echo $product['status']; ?></strong>
                            </div>
                        <?php endif; ?>
                        
                        <button class="btn btn-outline-primary" onclick="shareProduct()">
                            <i class="bi bi-share"></i> Share Product
                        </button>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Related Products -->
    <?php if (!empty($relatedProducts)): ?>
    <div class="row mt-5">
        <div class="col-12">
            <h4 class="mb-4">
                <i class="bi bi-grid"></i> Related Products
            </h4>
        </div>
        
        <?php foreach ($relatedProducts as $related): ?>
            <div class="col-sm-6 col-lg-3 mb-4">
                <div class="card h-100 border-0 shadow-sm hover-lift">
                    <div class="position-relative">
                        <?php 
                        $firstImage = !empty($related['images']) && is_array($related['images']) 
                            ? $related['images'][0] 
                            : null; 
                        ?>
                        <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $related['id']; ?>">
                            <?php if ($firstImage): ?>
                                <img src="<?php echo APP_URL . '/' . htmlspecialchars($firstImage); ?>" 
                                     class="card-img-top" 
                                     style="height: 180px; object-fit: cover;"
                                     alt="<?php echo htmlspecialchars($related['product_name']); ?>"
                                     onerror="this.src='<?php echo APP_URL; ?>/assets/images/no-image.png'">
                            <?php else: ?>
                                <div class="bg-light d-flex align-items-center justify-content-center" style="height: 180px;">
                                    <i class="bi bi-image text-muted" style="font-size: 2rem;"></i>
                                </div>
                            <?php endif; ?>
                        </a>
                    </div>
                    <div class="card-body">
                        <h6 class="card-title">
                            <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $related['id']; ?>" 
                               class="text-decoration-none text-dark">
                                <?php echo truncate($related['product_name'], 50); ?>
                            </a>
                        </h6>
                        <h5 class="text-success mb-0">
                            <?php echo formatCurrency($related['price_per_unit']); ?>
                            <small class="text-muted fs-6">/ <?php echo htmlspecialchars($related['unit']); ?></small>
                        </h5>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<style>
.cursor-pointer {
    cursor: pointer;
}

.thumbnail-image {
    transition: all 0.3s ease;
    border: 3px solid transparent;
}

.thumbnail-image.active {
    border-color: #0d6efd;
    transform: scale(1.05);
}

.thumbnail-image:hover {
    transform: scale(1.05);
    border-color: #6c757d;
}

.hover-lift {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.hover-lift:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.15) !important;
}

.favorite-btn {
    border-radius: 50%;
    width: 45px;
    height: 45px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}

.favorite-btn.active {
    background: #dc2626;
    color: white;
    border-color: #dc2626;
}

.favorite-btn.active:hover {
    background: #b91c1c;
    border-color: #b91c1c;
}

#mainProductImage {
    transition: opacity 0.3s ease;
}
</style>

<script>
// Store images array
const productImages = <?php echo json_encode($product['images'] ?? []); ?>;
let currentImageIndex = 0;

// Change main image when thumbnail clicked
function changeMainImage(index) {
    if (!productImages[index]) return;
    
    currentImageIndex = index;
    const mainImg = document.getElementById('mainProductImage');
    
    // Fade effect
    mainImg.style.opacity = '0';
    
    setTimeout(() => {
        mainImg.src = APP_URL + '/' + productImages[index];
        mainImg.style.opacity = '1';
    }, 150);
    
    // Update active thumbnail
    document.querySelectorAll('.thumbnail-image').forEach((thumb, i) => {
        thumb.classList.toggle('active', i === index);
    });
    
    // Update counter
    const counter = document.getElementById('imageCounter');
    if (counter) {
        counter.textContent = index + 1;
    }
}

// Favorite functionality
const favoriteBtn = document.getElementById('favoriteBtn');
if (favoriteBtn) {
    favoriteBtn.addEventListener('click', function() {
        const productId = this.dataset.productId;
        const icon = this.querySelector('i');
        
        fetch(`${APP_URL}/api/toggle-favorite.php`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ product_id: productId })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.classList.toggle('active');
                icon.classList.toggle('bi-heart');
                icon.classList.toggle('bi-heart-fill');
                showToast(data.message, 'success');
            } else {
                showToast(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('Connection error', 'error');
        });
    });
}

// Share product
function shareProduct() {
    const url = window.location.href;
    const title = '<?php echo addslashes($product['product_name']); ?>';
    
    if (navigator.share) {
        navigator.share({
            title: title,
            text: 'Check out this product on AIMS Marketplace',
            url: url
        }).then(() => {
            showToast('Shared successfully', 'success');
        }).catch((error) => {
            if (error.name !== 'AbortError') {
                copyToClipboard(url);
            }
        });
    } else {
        copyToClipboard(url);
    }
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        showToast('Link copied to clipboard', 'success');
    }).catch(() => {
        showToast('Failed to copy link', 'error');
    });
}

// Change product status
function changeStatus(productId, newStatus) {
    confirmAction(
        'Change Status',
        `Mark this product as ${newStatus}?`,
        function() {
            showLoading();
            fetch(APP_URL + '/ajax/update-product-status.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    product_id: productId,
                    status: newStatus
                })
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    showToast(data.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(data.message, 'error');
                }
            })
            .catch(error => {
                hideLoading();
                showToast('Connection error', 'error');
            });
        }
    );
}

// Delete product
function deleteProduct(productId) {
    confirmAction(
        'Delete Product',
        'Are you sure you want to delete this product? This action cannot be undone.',
        function() {
            showLoading();
            fetch(APP_URL + '/ajax/delete-product.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    product_id: productId
                })
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    showToast(data.message, 'success');
                    setTimeout(() => {
                        window.location.href = APP_URL + '/marketplace/my-products.php';
                    }, 1500);
                } else {
                    showToast(data.message, 'error');
                }
            })
            .catch(error => {
                hideLoading();
                showToast('Connection error', 'error');
            });
        }
    );
}

// Keyboard navigation for images
document.addEventListener('keydown', function(e) {
    if (productImages.length <= 1) return;
    
    if (e.key === 'ArrowLeft') {
        const prevIndex = currentImageIndex > 0 ? currentImageIndex - 1 : productImages.length - 1;
        changeMainImage(prevIndex);
    } else if (e.key === 'ArrowRight') {
        const nextIndex = currentImageIndex < productImages.length - 1 ? currentImageIndex + 1 : 0;
        changeMainImage(nextIndex);
    }
});
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>