<?php
// ========================================
// صفحه جزئیات محصول
// پروژه فروشگاه کیف‌لند
// ========================================

require_once 'config/database.php';
require_once 'config/settings.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if(!$id) {
    header('Location: products.php');
    exit;
}

$db = Database::getInstance()->getConnection();
$settings = SiteSettings::getInstance();

// افزایش بازدید
$db->prepare("UPDATE products SET view_count = view_count + 1 WHERE id = ?")->execute([$id]);

// دریافت اطلاعات محصول
$stmt = $db->prepare("SELECT p.*, c.name as category_name, c.slug as category_slug 
                      FROM products p 
                      LEFT JOIN categories c ON p.category_id = c.id 
                      WHERE p.id = ?");
$stmt->execute([$id]);
$product = $stmt->fetch();

if(!$product || !$product['is_active']) {
    header('Location: products.php');
    exit;
}

$pageTitle = $product['name'] . ' | ' . $settings->get('site_name');

// نظرات محصول
$stmt = $db->prepare("SELECT r.*, u.username, u.avatar 
                      FROM reviews r 
                      LEFT JOIN users u ON r.user_id = u.id 
                      WHERE r.product_id = ? AND r.is_approved = 1 
                      ORDER BY r.created_at DESC");
$stmt->execute([$id]);
$reviews = $stmt->fetchAll();

// محصولات مرتبط
$stmt = $db->prepare("SELECT * FROM products WHERE category_id = ? AND id != ? AND is_active = 1 ORDER BY RAND() LIMIT 4");
$stmt->execute([$product['category_id'], $id]);
$relatedProducts = $stmt->fetchAll();

// ثبت نظر
$review_success = '';
$review_error = '';

if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_review'])) {
    if(Auth::isLoggedIn()) {
        $rating = intval($_POST['rating']);
        $title = sanitize($_POST['title']);
        $comment = sanitize($_POST['comment']);
        
        // بررسی خرید قبلی
        $stmt = $db->prepare("SELECT COUNT(*) FROM order_items oi 
                              JOIN orders o ON oi.order_id = o.id 
                              WHERE o.user_id = ? AND oi.product_id = ? AND o.status = 'delivered'");
        $stmt->execute([$_SESSION['user_id'], $id]);
        $has_purchased = $stmt->fetchColumn();
        
        try {
            $stmt = $db->prepare("INSERT INTO reviews (product_id, user_id, rating, title, comment, is_verified) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$id, $_SESSION['user_id'], $rating, $title, $comment, $has_purchased ? 1 : 0]);
            
            // آپدیت میانگین امتیاز
            $stmt = $db->prepare("UPDATE products SET rating_avg = (SELECT AVG(rating) FROM reviews WHERE product_id = ? AND is_approved = 1), 
                                  rating_count = (SELECT COUNT(*) FROM reviews WHERE product_id = ? AND is_approved = 1) WHERE id = ?");
            $stmt->execute([$id, $id, $id]);
            
            $review_success = 'نظر شما ثبت شد و پس از تایید نمایش داده می‌شود';
        } catch(Exception $e) {
            $review_error = 'خطا در ثبت نظر';
        }
    } else {
        $review_error = 'برای ثبت نظر باید وارد حساب کاربری شوید';
    }
}

include 'includes/header.php';
?>

<section class="product-detail-page">
    <?php if($review_success): ?>
    <div class="alert alert-success" style="margin: 20px 5%;"><?= $review_success ?></div>
    <?php endif; ?>
    
    <?php if($review_error): ?>
    <div class="alert alert-danger" style="margin: 20px 5%;"><?= $review_error ?></div>
    <?php endif; ?>
    
    <div class="breadcrumb" style="padding: 20px 5%;">
        <a href="index.php">خانه</a>
        <i class="fas fa-chevron-left"></i>
        <a href="products.php">محصولات</a>
        <i class="fas fa-chevron-left"></i>
        <a href="products.php?category=<?= $product['category_slug'] ?>"><?= htmlspecialchars($product['category_name']) ?></a>
        <i class="fas fa-chevron-left"></i>
        <span><?= htmlspecialchars($product['name']) ?></span>
    </div>
    
    <div class="product-detail-layout">
        <!-- تصاویر محصول -->
        <div class="product-gallery">
            <div class="main-image">
                <img src="uploads/products/<?= $product['image'] ?>" 
                     alt="<?= htmlspecialchars($product['name']) ?>" 
                     id="mainImage"
                     onerror="this.src='assets/images/no-image.svg'">
            </div>
        </div>
        
        <!-- اطلاعات محصول -->
        <div class="product-info-detail">
            <span class="product-category">
                <a href="products.php?category=<?= $product['category_slug'] ?>">
                    <?= htmlspecialchars($product['category_name']) ?>
                </a>
            </span>
            
            <h1><?= htmlspecialchars($product['name']) ?></h1>
            
            <?php if($product['rating_avg'] > 0): ?>
            <div class="product-rating-large">
                <?php for($i = 1; $i <= 5; $i++): ?>
                <i class="fas fa-star" style="color: <?= $i <= round($product['rating_avg']) ? '#ffc107' : '#e0e0e0' ?>"></i>
                <?php endfor; ?>
                <span><?= $product['rating_avg'] ?> از 5 (<?= $product['rating_count'] ?> نظر)</span>
            </div>
            <?php endif; ?>
            
            <div class="product-price-large">
                <?php if($product['discount_price']): ?>
                <span class="old-price"><?= formatPrice($product['price']) ?></span>
                <span class="price"><?= formatPrice($product['discount_price']) ?></span>
                <span class="discount-badge"><?= round((($product['price'] - $product['discount_price']) / $product['price']) * 100) ?>٪ تخفیف</span>
                <?php else: ?>
                <span class="price"><?= formatPrice($product['price']) ?></span>
                <?php endif; ?>
            </div>
            
            <div class="product-meta">
                <?php if($product['sku']): ?>
                <p><strong>کد محصول:</strong> <?= htmlspecialchars($product['sku']) ?></p>
                <?php endif; ?>
                <p><strong>موجودی:</strong> 
                    <span class="badge badge-<?= $product['stock'] > 0 ? 'success' : 'danger' ?>">
                        <?= $product['stock'] > 0 ? 'موجود در انبار' : 'ناموجود' ?>
                    </span>
                </p>
                <p><strong>بازدید:</strong> <?= formatNumber($product['view_count']) ?></p>
            </div>
            
            <div class="product-description">
                <h3>توضیحات محصول</h3>
                <p><?= nl2br(htmlspecialchars($product['description'])) ?></p>
            </div>
            
            <div class="product-actions">
                <form method="POST" action="cart-action.php" style="display: flex; gap: 10px; flex-wrap: wrap;">
                    <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                    <input type="hidden" name="action" value="add">
                    
                    <div class="quantity-selector">
                        <button type="button" onclick="document.getElementById('qty').value--">-</button>
                        <input type="number" id="qty" name="quantity" value="1" min="1" max="<?= $product['stock'] ?>">
                        <button type="button" onclick="document.getElementById('qty').value++">+</button>
                    </div>
                    
                    <button type="submit" class="btn btn-primary btn-lg" <?= $product['stock'] == 0 ? 'disabled' : '' ?>>
                        <i class="fas fa-shopping-cart"></i>
                        افزودن به سبد
                    </button>
                    
                    <button type="button" class="btn btn-outline btn-lg" onclick="addToWishlist(<?= $product['id'] ?>)">
                        <i class="fas fa-heart"></i>
                    </button>
                </form>
            </div>
            
            <div class="product-features">
                <h3>ویژگی‌ها</h3>
                <ul>
                    <li><i class="fas fa-check"></i> گارانتی مادام‌العمر</li>
                    <li><i class="fas fa-check"></i> ارسال رایگان برای خریدهای بالای <?= formatPrice($settings->get('free_shipping_threshold')) ?></li>
                    <li><i class="fas fa-check"></i> بازگشت ۷ روزه</li>
                    <li><i class="fas fa-check"></i> پرداخت در محل</li>
                </ul>
            </div>
        </div>
    </div>
    
    <!-- نظرات کاربران -->
    <section class="reviews-section">
        <h2>نظرات کاربران</h2>
        
        <?php if(count($reviews) > 0): ?>
        <div class="reviews-list">
            <?php foreach($reviews as $review): ?>
            <div class="review-card">
                <div class="review-header">
                    <div class="reviewer-info">
                        <div class="reviewer-avatar">
                            <i class="fas fa-user"></i>
                        </div>
                        <div>
                            <h4><?= htmlspecialchars($review['username'] ?? 'کاربر مهمان') ?></h4>
                            <div class="review-rating">
                                <?php for($i = 1; $i <= 5; $i++): ?>
                                <i class="fas fa-star" style="color: <?= $i <= $review['rating'] ? '#ffc107' : '#e0e0e0' ?>"></i>
                                <?php endfor; ?>
                            </div>
                        </div>
                    </div>
                    <span class="review-date"><?= jdate($review['created_at']) ?></span>
                </div>
                <?php if($review['title']): ?>
                <h5><?= htmlspecialchars($review['title']) ?></h5>
                <?php endif; ?>
                <p><?= nl2br(htmlspecialchars($review['comment'])) ?></p>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <p class="no-reviews">هنوز نظری برای این محصول ثبت نشده است</p>
        <?php endif; ?>
        
        <!-- فرم ثبت نظر -->
        <?php if(Auth::isLoggedIn()): ?>
        <div class="review-form">
            <h3>ثبت نظر جدید</h3>
            <form method="POST">
                <div class="form-group">
                    <label>امتیاز</label>
                    <div class="star-rating">
                        <input type="radio" name="rating" value="5" id="star5" required>
                        <label for="star5">★</label>
                        <input type="radio" name="rating" value="4" id="star4">
                        <label for="star4">★</label>
                        <input type="radio" name="rating" value="3" id="star3">
                        <label for="star3">★</label>
                        <input type="radio" name="rating" value="2" id="star2">
                        <label for="star2">★</label>
                        <input type="radio" name="rating" value="1" id="star1">
                        <label for="star1">★</label>
                    </div>
                </div>
                <div class="form-group">
                    <label>عنوان نظر</label>
                    <input type="text" name="title" placeholder="عنوان نظر خود را وارد کنید">
                </div>
                <div class="form-group">
                    <label>متن نظر</label>
                    <textarea name="comment" rows="5" placeholder="نظر خود را بنویسید..." required></textarea>
                </div>
                <button type="submit" name="submit_review" class="btn btn-primary">ثبت نظر</button>
            </form>
        </div>
        <?php else: ?>
        <div class="login-prompt">
            <p>برای ثبت نظر باید <a href="login.php">وارد حساب کاربری</a> شوید</p>
        </div>
        <?php endif; ?>
    </section>
    
    <!-- محصولات مرتبط -->
    <?php if(count($relatedProducts) > 0): ?>
    <section class="related-products">
        <h2>محصولات مرتبط</h2>
        <div class="product-grid">
            <?php foreach($relatedProducts as $related): ?>
            <div class="product-card">
                <a href="product-detail.php?id=<?= $related['id'] ?>">
                    <img src="uploads/products/<?= $related['image'] ?>" 
                         alt="<?= htmlspecialchars($related['name']) ?>" 
                         onerror="this.src='assets/images/no-image.svg'">
                </a>
                <div class="product-info">
                    <h3 class="product-title">
                        <a href="product-detail.php?id=<?= $related['id'] ?>">
                            <?= htmlspecialchars($related['name']) ?>
                        </a>
                    </h3>
                    <div class="product-price">
                        <span class="price"><?= formatPrice($related['discount_price'] ?? $related['price']) ?></span>
                        <button class="btn-add-cart" onclick="addToCart(<?= $related['id'] ?>)">
                            <i class="fas fa-plus"></i>
                        </button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>
</section>

<style>
.product-detail-page { padding: 20px 5%; }
.breadcrumb { display: flex; gap: 10px; align-items: center; color: var(--text-secondary); font-size: 0.9rem; }
.breadcrumb a { color: var(--text-secondary); transition: 0.3s; }
.breadcrumb a:hover { color: var(--primary); }
.product-detail-layout { display: grid; grid-template-columns: 1fr 1fr; gap: 50px; padding: 40px 0; }
.product-gallery .main-image { background: var(--bg-card); border-radius: var(--radius-lg); padding: 20px; border: 1px solid var(--border-color); }
.product-gallery .main-image img { width: 100%; border-radius: var(--radius-md); }
.product-info-detail { padding: 20px; }
.product-info-detail h1 { font-size: 2rem; margin: 20px 0; }
.product-category a { color: var(--primary); font-size: 0.9rem; }
.product-rating-large { display: flex; align-items: center; gap: 10px; margin-bottom: 20px; }
.product-price-large { display: flex; align-items: center; gap: 15px; margin-bottom: 20px; font-size: 1.5rem; color: var(--primary); font-weight: bold; }
.product-price-large .old-price { text-decoration: line-through; color: var(--text-secondary); font-size: 1rem; }
.discount-badge { background: var(--danger); color: #fff; padding: 5px 15px; border-radius: 20px; font-size: 0.9rem; }
.product-meta { margin-bottom: 20px; padding: 20px; background: var(--bg-card); border-radius: var(--radius-lg); }
.product-meta p { margin-bottom: 10px; }
.product-description { margin-bottom: 30px; }
.product-description h3 { margin-bottom: 15px; }
.product-actions { margin-bottom: 30px; }
.quantity-selector { display: flex; align-items: center; border: 1px solid var(--border-color); border-radius: var(--radius-md); overflow: hidden; }
.quantity-selector button { width: 40px; height: 40px; background: var(--bg-card); border: none; cursor: pointer; font-size: 1.2rem; }
.quantity-selector input { width: 60px; height: 40px; text-align: center; border: none; background: var(--bg-card); color: var(--text-primary); }
.product-features { margin-bottom: 30px; padding: 20px; background: var(--bg-card); border-radius: var(--radius-lg); }
.product-features ul { list-style: none; }
.product-features li { padding: 10px 0; display: flex; align-items: center; gap: 10px; }
.product-features li i { color: var(--success); }
.reviews-section { padding: 40px 0; border-top: 1px solid var(--border-color); }
.reviews-section h2 { margin-bottom: 30px; }
.reviews-list { display: flex; flex-direction: column; gap: 20px; margin-bottom: 40px; }
.review-card { background: var(--bg-card); padding: 20px; border-radius: var(--radius-lg); border: 1px solid var(--border-color); }
.review-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
.reviewer-info { display: flex; align-items: center; gap: 15px; }
.reviewer-avatar { width: 50px; height: 50px; background: var(--bg-secondary); border-radius: 50%; display: flex; align-items: center; justify-content: center; }
.review-rating { display: flex; gap: 5px; margin-top: 5px; }
.review-date { color: var(--text-secondary); font-size: 0.9rem; }
.review-form { background: var(--bg-card); padding: 30px; border-radius: var(--radius-lg); border: 1px solid var(--border-color); }
.star-rating { display: flex; flex-direction: row-reverse; justify-content: flex-end; gap: 5px; }
.star-rating input { display: none; }
.star-rating label { font-size: 2rem; color: var(--text-secondary); cursor: pointer; transition: 0.3s; }
.star-rating input:checked ~ label, .star-rating label:hover { color: #ffc107; }
.login-prompt { text-align: center; padding: 40px; background: var(--bg-card); border-radius: var(--radius-lg); }
.login-prompt a { color: var(--primary); }
.related-products { padding: 40px 0; border-top: 1px solid var(--border-color); }
.related-products h2 { margin-bottom: 30px; }
@media (max-width: 1024px) {
    .product-detail-layout { grid-template-columns: 1fr; }
}
</style>

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