<?php
/**
 * ============================================================
 * SINGLE PRODUCT PAGE
 * ============================================================
 */

require_once APP_PATH . '/services/product_service.php';
require_once APP_PATH . '/services/review_service.php';

// Get product by slug or ID
$slug = sanitize($_GET['slug'] ?? '');
$productId = (int)($_GET['id'] ?? 0);

if ($slug) {
    $product = ProductService::getBySlug($slug);
} elseif ($productId) {
    $product = ProductService::getById($productId);
} else {
    redirect(url('public/?page=products'));
}

if (!$product || !$product['is_active']) {
    redirect(url('public/?page=products'));
}

// Track recently viewed
$sessionId = getCartSessionId();
Database::execute(
    "INSERT INTO recently_viewed (session_id, user_id, product_id, viewed_at) 
     VALUES (?, ?, ?, NOW()) 
     ON DUPLICATE KEY UPDATE viewed_at = NOW()",
    [$sessionId, getUserId(), $product['id']]
);

// Get reviews
$reviews = ReviewService::getByProduct($product['id'], 10, 0);

// Get related products
$relatedProducts = ProductService::getRelated($product['id'], $product['category_id'], 4);

// Check if in wishlist
$inWishlist = false;
if (isLoggedIn()) {
    $inWishlist = Database::fetchColumn(
        "SELECT id FROM wishlists WHERE user_id = ? AND product_id = ?",
        [getUserId(), $product['id']]
    );
}

// Page meta
$pageTitle = $product['meta_title'] ?: $product['name'];
$pageDescription = $product['meta_description'] ?: truncate($product['short_description'] ?? '', 160);

$currentPrice = $product['sale_price'] ?? $product['price'];
$hasDiscount = $product['sale_price'] && $product['sale_price'] < $product['price'];

include PUBLIC_PATH . '/includes/head.php';
include PUBLIC_PATH . '/includes/navbar.php';
?>

<main class="py-4">
    <div class="container">
        <!-- Breadcrumb -->
        <nav aria-label="breadcrumb" class="mb-4">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?= url('public/') ?>">হোম</a></li>
                <li class="breadcrumb-item"><a href="<?= url('public/?page=products') ?>">পণ্য</a></li>
                <li class="breadcrumb-item">
                    <a href="<?= url('public/?page=products&category=' . $product['category_slug']) ?>">
                        <?= sanitize($product['category_name']) ?>
                    </a>
                </li>
                <li class="breadcrumb-item active"><?= sanitize(truncate($product['name'], 30)) ?></li>
            </ol>
        </nav>
        
        <div class="row g-4">
            <!-- Product Images -->
            <div class="col-lg-6">
                <div class="bg-white rounded p-3 shadow-sm">
                    <!-- Main Image -->
                    <div class="mb-3 text-center" style="height: 400px;">
                        <?php 
                        $mainImage = $product['images'][0]['file_path'] ?? null;
                        $mainImageUrl = $mainImage ? UPLOADS_URL . '/products/' . $mainImage : asset('img/no-image.png');
                        ?>
                        <img src="<?= $mainImageUrl ?>" alt="<?= sanitize($product['name']) ?>" 
                             id="mainProductImage" class="img-fluid h-100" style="object-fit: contain;">
                    </div>
                    
                    <!-- Thumbnails -->
                    <?php if (count($product['images']) > 1): ?>
                    <div class="d-flex gap-2 overflow-auto">
                        <?php foreach ($product['images'] as $index => $img): ?>
                        <img src="<?= UPLOADS_URL . '/products/' . $img['file_path'] ?>" 
                             alt="<?= sanitize($product['name']) ?>"
                             class="product-thumb rounded <?= $index === 0 ? 'active border-primary' : '' ?>"
                             data-src="<?= UPLOADS_URL . '/products/' . $img['file_path'] ?>"
                             style="width: 70px; height: 70px; object-fit: cover; cursor: pointer; border: 2px solid transparent;">
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Product Info -->
            <div class="col-lg-6">
                <div class="bg-white rounded p-4 shadow-sm">
                    <h1 class="h3 mb-2"><?= sanitize($product['name']) ?></h1>
                    
                    <!-- Rating -->
                    <?php if ($product['review_count'] > 0): ?>
                    <div class="mb-3">
                        <span class="text-warning">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                            <i class="bi bi-star<?= $i <= round($product['avg_rating']) ? '-fill' : '' ?>"></i>
                            <?php endfor; ?>
                        </span>
                        <span class="text-muted ms-2">(<?= $product['review_count'] ?> রিভিউ)</span>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Price -->
                    <div class="mb-4">
                        <span class="display-6 text-primary fw-bold"><?= formatPrice($currentPrice) ?></span>
                        <?php if ($hasDiscount): ?>
                        <span class="text-muted text-decoration-line-through ms-2 fs-5">
                            <?= formatPrice($product['price']) ?>
                        </span>
                        <span class="badge bg-danger ms-2">
                            <?= round((($product['price'] - $product['sale_price']) / $product['price']) * 100) ?>% ছাড়
                        </span>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Short Description -->
                    <?php if ($product['short_description']): ?>
                    <p class="text-muted mb-4"><?= sanitize($product['short_description']) ?></p>
                    <?php endif; ?>
                    
                    <!-- Stock Status -->
                    <div class="mb-4">
                        <?php if ($product['stock_qty'] > 10): ?>
                        <span class="text-success"><i class="bi bi-check-circle me-1"></i> স্টকে আছে</span>
                        <?php elseif ($product['stock_qty'] > 0): ?>
                        <span class="text-warning"><i class="bi bi-exclamation-circle me-1"></i> মাত্র <?= $product['stock_qty'] ?>টি বাকি!</span>
                        <?php else: ?>
                        <span class="text-danger"><i class="bi bi-x-circle me-1"></i> স্টক শেষ</span>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Add to Cart Form -->
                    <?php if ($product['stock_qty'] > 0): ?>
                    <div class="product-actions-form">
                        <div class="row g-3 mb-3">
                            <div class="col-auto">
                                <label class="form-label">পরিমাণ</label>
                                <div class="input-group qty-input-group">
                                    <button type="button" class="btn btn-outline-secondary qty-btn" data-action="decrease">
                                        <i class="bi bi-dash"></i>
                                    </button>
                                    <input type="number" class="form-control qty-input text-center" value="1" min="1" max="<?= $product['stock_qty'] ?>">
                                    <button type="button" class="btn btn-outline-secondary qty-btn" data-action="increase">
                                        <i class="bi bi-plus"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex gap-2 flex-wrap">
                            <button type="button" class="btn btn-primary btn-lg btn-add-cart" data-product-id="<?= $product['id'] ?>">
                                <i class="bi bi-cart-plus me-2"></i>কার্টে যোগ করুন
                            </button>
                            <button type="button" class="btn btn-outline-secondary btn-lg btn-wishlist" data-product-id="<?= $product['id'] ?>">
                                <i class="bi bi-heart<?= $inWishlist ? '-fill text-danger' : '' ?>"></i>
                            </button>
                        </div>
                    </div>
                    <?php else: ?>
                    <button type="button" class="btn btn-secondary btn-lg" disabled>
                        <i class="bi bi-x-circle me-2"></i>স্টক শেষ
                    </button>
                    <?php endif; ?>
                    
                    <!-- Meta Info -->
                    <div class="mt-4 pt-4 border-top">
                        <?php if ($product['sku']): ?>
                        <p class="mb-1"><strong>SKU:</strong> <?= sanitize($product['sku']) ?></p>
                        <?php endif; ?>
                        <p class="mb-1"><strong>ক্যাটাগরি:</strong> 
                            <a href="<?= url('public/?page=products&category=' . $product['category_slug']) ?>">
                                <?= sanitize($product['category_name']) ?>
                            </a>
                        </p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Description & Reviews Tabs -->
        <div class="mt-5">
            <ul class="nav nav-tabs" id="productTabs">
                <li class="nav-item">
                    <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#description">বিবরণ</button>
                </li>
                <li class="nav-item">
                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#reviews">
                        রিভিউ (<?= $product['review_count'] ?>)
                    </button>
                </li>
            </ul>
            
            <div class="tab-content bg-white rounded-bottom p-4 shadow-sm">
                <!-- Description -->
                <div class="tab-pane fade show active" id="description">
                    <?php if ($product['description']): ?>
                    <div class="product-description">
                        <?= $product['description'] ?>
                    </div>
                    <?php else: ?>
                    <p class="text-muted">কোনো বিবরণ নেই।</p>
                    <?php endif; ?>
                </div>
                
                <!-- Reviews -->
                <div class="tab-pane fade" id="reviews">
                    <?php if (empty($reviews)): ?>
                    <p class="text-muted">এখনও কোনো রিভিউ নেই।</p>
                    <?php else: ?>
                    <?php foreach ($reviews as $review): ?>
                    <div class="border-bottom pb-3 mb-3">
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong><?= sanitize($review['user_name']) ?></strong>
                                <div class="text-warning">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <i class="bi bi-star<?= $i <= $review['rating'] ? '-fill' : '' ?>"></i>
                                    <?php endfor; ?>
                                </div>
                            </div>
                            <small class="text-muted"><?= formatDate($review['created_at']) ?></small>
                        </div>
                        <?php if ($review['review_title']): ?>
                        <h6 class="mt-2 mb-1"><?= sanitize($review['review_title']) ?></h6>
                        <?php endif; ?>
                        <?php if ($review['review_text']): ?>
                        <p class="mb-0"><?= nl2br(sanitize($review['review_text'])) ?></p>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                    
                    <!-- Write Review Form -->
                    <?php if (isLoggedIn()): ?>
                    <div class="mt-4 pt-4 border-top">
                        <h5>রিভিউ লিখুন</h5>
                        <form id="reviewForm">
                            <?= csrf_field() ?>
                            <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                            
                            <div class="mb-3">
                                <label class="form-label">রেটিং</label>
                                <div class="star-rating">
                                    <?php for ($i = 5; $i >= 1; $i--): ?>
                                    <input type="radio" name="rating" value="<?= $i ?>" id="star<?= $i ?>">
                                    <label for="star<?= $i ?>"><i class="bi bi-star-fill"></i></label>
                                    <?php endfor; ?>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="review_title" class="form-label">শিরোনাম (ঐচ্ছিক)</label>
                                <input type="text" class="form-control" id="review_title" name="review_title">
                            </div>
                            
                            <div class="mb-3">
                                <label for="review_text" class="form-label">আপনার রিভিউ</label>
                                <textarea class="form-control" id="review_text" name="review_text" rows="3"></textarea>
                            </div>
                            
                            <button type="submit" class="btn btn-primary">রিভিউ জমা দিন</button>
                        </form>
                        
                        <div id="reviewThankYou" class="alert alert-success mt-3" style="display: none;">
                            <i class="bi bi-check-circle me-2"></i>
                            রিভিউ জমা হয়েছে! অ্যাডমিন অনুমোদনের পর প্রকাশ হবে।
                        </div>
                    </div>
                    <?php else: ?>
                    <p class="mt-4 text-muted">
                        রিভিউ দিতে <a href="<?= url('public/?page=login') ?>">লগইন করুন</a>।
                    </p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Related Products -->
        <?php if (!empty($relatedProducts)): ?>
        <section class="mt-5">
            <h3 class="mb-4">সম্পর্কিত পণ্য</h3>
            <div class="row g-4">
                <?php foreach ($relatedProducts as $product): ?>
                <div class="col-6 col-md-3">
                    <?php include PUBLIC_PATH . '/includes/product-card.php'; ?>
                </div>
                <?php endforeach; ?>
            </div>
        </section>
        <?php endif; ?>
    </div>
</main>

<style>
.product-thumb.active {
    border-color: var(--bs-primary) !important;
}
</style>

<?php include PUBLIC_PATH . '/includes/footer.php'; ?>
