<?php
require_once __DIR__ . '/../config/config.php';

/*
|--------------------------------------------------------------------------
| SEO URL SUPPORT
| /profile/slug/id
|--------------------------------------------------------------------------
*/

$target_user_id = (int)($_GET['id'] ?? 0);
$target_slug = $_GET['slug'] ?? '';

if ($target_user_id === 0) {
    die("Invalid User ID.");
}

/*
|--------------------------------------------------------------------------
| GET SELLER PROFILE USING user_id
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("SELECT * FROM sellers WHERE user_id = ? AND seller_slug = ? LIMIT 1");
$stmt->execute([$target_user_id, $target_slug]);
$seller = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$seller) {
    die("Merchant profile not found.");
}

$seller_primary_id = $seller['id'];
$seller_user_id = $seller['user_id'];

/*
|--------------------------------------------------------------------------
| TOTAL SALES
|--------------------------------------------------------------------------
*/
$salesQuery = $pdo->prepare("
    SELECT COUNT(*) 
    FROM orders 
    WHERE seller_id = ? 
    AND payment_status = 'Paid'
");
$salesQuery->execute([$seller_user_id]);
$total_sales = $salesQuery->fetchColumn();

/*
|--------------------------------------------------------------------------
| PRODUCTS
|--------------------------------------------------------------------------
*/
$page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
$limit = 8;
$offset = ($page - 1) * $limit;

$itemsQuery = $pdo->prepare("
    SELECT
        i.*,
        c.category_name,
        (
            SELECT COUNT(*)
            FROM orders o
            WHERE o.item_id = i.id
            AND o.payment_status = 'Paid'
        ) AS total_sales,
        (
            SELECT COUNT(*)
            FROM reviews r
            WHERE r.item_id = i.id
        ) AS total_reviews,
        (
            SELECT ROUND(AVG(r.rating), 1)
            FROM reviews r
            WHERE r.item_id = i.id
        ) AS average_rating
    FROM items i
    LEFT JOIN categories c ON i.category_id = c.id
    WHERE i.seller_id = ?
    AND i.status = 'active'
    ORDER BY i.id DESC
    LIMIT ? OFFSET ?
");

$itemsQuery->execute([
    $seller_primary_id,
    $limit,
    $offset
]);

$products = $itemsQuery->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| REVIEWS
|--------------------------------------------------------------------------
*/
$rev_page = isset($_GET['rp']) ? (int)$_GET['rp'] : 1;
$rev_offset = ($rev_page - 1) * 5;

$revQuery = $pdo->prepare("
    SELECT *
    FROM reviews
    WHERE seller_id = ?
    ORDER BY id DESC
    LIMIT 5 OFFSET ?
");

$revQuery->execute([
    $seller_user_id,
    $rev_offset
]);

$review_list = $revQuery->fetchAll(PDO::FETCH_ASSOC);

	$page_title = $seller['seller_name'] ?? 'Seller Profile';

	require_once __DIR__ . '/../sections/header.php';
require_once __DIR__ . '/../sections/navbar.php';
?>

<body class="bg-nftDark text-white antialiased">
    
    <div class="h-64 w-full bg-slate-900 relative">
        <img src="https://images.unsplash.com/photo-1614850523459-c2f4c699c52e?auto=format&fit=crop&q=80&w=2000" class="w-full h-full object-cover opacity-30">
    </div>

    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 -mt-20 pb-20">
        
        <div class="glass-card p-6 rounded-2xl border border-slate-800 bg-nftDark/90 backdrop-blur-xl flex flex-col md:flex-row gap-6 mb-12">
            <div class="w-32 h-32 rounded-2xl border-4 border-nftDark bg-slate-900 -mt-16 overflow-hidden shadow-2xl">
                <img src="<?php echo htmlspecialchars(media_url($seller['profile_picture'] ?? '', 'assets/img/placeholder.png'), ENT_QUOTES, 'UTF-8'); ?>" class="w-full h-full object-cover">
            </div>
            <div class="flex-1">
                <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                        <h1 class="text-3xl font-black uppercase tracking-tight"><?php echo htmlspecialchars($seller['seller_name']); ?></h1>
                        <p class="text-nftAccentCyan text-sm font-mono mt-1"><i class="fa-solid fa-location-dot mr-2"></i><?php echo htmlspecialchars($seller['country']); ?></p>
                    </div>
                    <div class="bg-slate-800/50 px-6 py-3 rounded-xl border border-slate-700/50 text-center">
                        <span class="block text-2xl font-black text-emerald-400"><?php echo (int)$total_sales; ?></span>
                        <span class="text-[10px] uppercase tracking-widest text-nftTextGray">Total Sales</span>
                    </div>
                </div>
                <p class="text-nftTextGray mt-4 text-sm max-w-2xl"><?php echo htmlspecialchars($seller['about']); ?></p>
            </div>
        </div>

        <section class="mb-20">
            <h2 class="text-2xl font-black mb-8 uppercase tracking-widest">// MERCHANT ASSETS</h2>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                <?php foreach ($products as $product): ?>
                    <div class="nft-card-ui p-4 bg-nftCard/30 rounded-2xl border border-slate-800/80 group flex flex-col justify-between">
                        <div>
                            <div class="relative overflow-hidden rounded-xl aspect-[4/3] mb-4 bg-slate-900">
                                <img src="<?php echo htmlspecialchars(media_url($product['feature_image'] ?? '', 'assets/img/placeholder.png'), ENT_QUOTES, 'UTF-8'); ?>"
                                     alt="<?php echo htmlspecialchars($product['item_name']); ?> Visualization Image"
                                     class="w-full h-full object-cover group-hover:scale-105 transition-all duration-500">

                                <div class="absolute top-3 left-3 bg-nftDark/80 backdrop-blur-md px-2.5 py-1 rounded-md text-[10px] font-bold text-nftAccentCyan uppercase">
                                    <?php echo htmlspecialchars($product['category_name'] ?? 'Asset Core'); ?>
                                </div>
                            </div>

                            <div class="flex items-center justify-between mb-1">
                                <span class="text-[11px] text-nftTextGray">
                                    Owner Profile: #<?php echo htmlspecialchars($product['seller_id']); ?>
                                </span>
                                <?php if (!empty($product['ai_brain_used'])): ?>
                                    <span class="text-[11px] text-nftAccentPurple font-bold">
                                        <i class="fa-solid fa-brain mr-1 text-[9px]"></i><?php echo htmlspecialchars($product['ai_brain_used']); ?>
                                    </span>
                                <?php endif; ?>
                            </div>

                            <h3 class="font-bold text-base hover:text-nftAccentCyan transition-colors cursor-pointer truncate">
                                <a href="<?php echo htmlspecialchars(item_url($product)); ?>" class="block" title="<?php echo htmlspecialchars($product['item_name']); ?>">
                                    <?php echo htmlspecialchars($product['item_name']); ?>
                                </a>
                            </h3>

                            <div class="flex items-center justify-between mt-3 text-xs">
                                <div class="flex items-center text-yellow-400">
                                    <i class="fas fa-star mr-1"></i>
                                    <span>
                                        <?php echo $product['average_rating'] ? number_format((float)$product['average_rating'], 1) : '0.0'; ?>
                                    </span>
                                </div>

                                <div class="text-cyan-400">
                                    <i class="fas fa-comment-alt mr-1"></i>
                                    <?php echo (int)$product['total_reviews']; ?> Reviews
                                </div>

                                <div class="text-emerald-400">
                                    <i class="fas fa-shopping-cart mr-1"></i>
                                    <?php echo (int)$product['total_sales']; ?> Sales
                                </div>
                            </div>
                        </div>

                        <div class="flex items-center justify-between mt-4 pt-3 border-t border-slate-800/50">
                            <div>
                                <p class="text-[10px] text-nftTextGray uppercase">License Price</p>
                                <p class="text-base font-extrabold text-white font-mono"><?php echo htmlspecialchars(format_currency($product['amount']), ENT_QUOTES, 'UTF-8'); ?></p>
                            </div>

                            <a href="<?php echo htmlspecialchars(item_url($product)); ?>"
                               class="bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple text-white px-4 py-2 rounded-xl text-xs font-semibold shadow-md opacity-90 hover:opacity-100 transition-all text-center inline-block">
                                <i class="fa-solid fa-cart-shopping mr-1 text-[10px]"></i> Purchase Asset
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </section>

        <section>
            <h2 class="text-2xl font-black mb-8 uppercase tracking-widest">// CLIENT FEEDBACK</h2>
            <div class="space-y-4">
                <?php if (!empty($review_list)): foreach ($review_list as $rev): ?>
                    <div class="glass-card p-6 rounded-2xl border border-slate-800 bg-slate-900/20">
                        <div class="flex justify-between items-start">
                            <h4 class="font-bold text-sm"><?php echo htmlspecialchars($rev['client_name']); ?></h4>
                            <div class="text-nftAccentPurple">
                                <?php for($i=0; $i<$rev['rating']; $i++) echo '<i class="fa-solid fa-star text-xs"></i>'; ?>
                            </div>
                        </div>
                        <p class="text-nftTextGray text-xs mt-2 italic">"<?php echo htmlspecialchars($rev['review_text']); ?>"</p>
                    </div>
                <?php endforeach; else: ?>
                    <p class="text-nftTextGray">No feedback available for this merchant.</p>
                <?php endif; ?>
            </div>
        </section>
    </main>

    <?php require_once __DIR__ . '/../sections/footer.php'; ?>
</body>
