<?php
/**
 * Agentic Square - Premium Product Information & Acquisition Interface
 * Path: item-details.php (Main Directory)
 */

// Initialize Primary Application Execution Configs
require_once __DIR__ . '/config/config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 1. Capture and prioritize the item URL slug/id identifier parameters
$item_slug = isset($_GET['slug']) ? trim($_GET['slug']) : '';
$item_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (empty($item_slug)) {
    header('Location: ' . app_url('index.php'));
    exit;
}

try {
    if ($item_id <= 0) {
        $canonicalStmt = $pdo->prepare("
            SELECT id, item_slug
            FROM items
            WHERE item_slug = ? AND status = 'active'
            LIMIT 1
        ");
        $canonicalStmt->execute([$item_slug]);
        $canonicalItem = $canonicalStmt->fetch(PDO::FETCH_ASSOC);

        if (!$canonicalItem) {
            header('Location: ' . app_url('index.php?error=item_not_found'));
            exit;
        }

        header('Location: ' . item_url($canonicalItem), true, 301);
        exit;
    }

    /**
     * RESOURCE HYDRATION QUERY MATRIX
     * Pulls the core asset data parameters, matching category names, and vendor profile criteria.
     */
    $stmt = $pdo->prepare("
        SELECT i.*, c.category_name, s.seller_name, s.profile_picture 
        FROM items i 
        LEFT JOIN categories c ON i.category_id = c.id 
        LEFT JOIN sellers s ON i.seller_id = s.id 
        WHERE i.id = ? AND i.status = 'active' 
        LIMIT 1
    ");
    $stmt->execute([$item_id]);
    $item = $stmt->fetch();

    // Fallback block if the item is not verified active or missing from database indexes
    if (!$item) {
        header('Location: ' . app_url('index.php?error=item_not_found'));
        exit;
    }

    if (!hash_equals((string)$item['item_slug'], (string)$item_slug)) {
        header('Location: ' . item_url($item), true, 301);
        exit;
    }
    
     /* ==========================================================
       TOTAL SALES
    ========================================================== */
    $salesStmt = $pdo->prepare("
        SELECT COUNT(*) as total_sales
        FROM orders
        WHERE item_id = ?
        AND payment_status = 'Paid'
    ");
    $salesStmt->execute([$item['id']]);
    $salesData = $salesStmt->fetch(PDO::FETCH_ASSOC);

    $item['total_sales'] = (int)($salesData['total_sales'] ?? 0);

    /* ==========================================================
       REVIEWS & RATINGS
    ========================================================== */
    $ratingStmt = $pdo->prepare("
        SELECT
            COUNT(*) as total_reviews,
            AVG(rating) as average_rating
        FROM reviews
        WHERE item_id = ?
    ");
    $ratingStmt->execute([$item['id']]);
    $ratingData = $ratingStmt->fetch(PDO::FETCH_ASSOC);

    $total_reviews = (int)($ratingData['total_reviews'] ?? 0);
    $average_rating = round((float)($ratingData['average_rating'] ?? 0), 1);

    $reviewsStmt = $pdo->prepare("
        SELECT *
        FROM reviews
        WHERE item_id = ?
        ORDER BY created_at DESC
    ");
    $reviewsStmt->execute([$item['id']]);
    $reviews = $reviewsStmt->fetchAll(PDO::FETCH_ASSOC);

    /**
     * REAL-TIME ANALYTICS INCREMENT ENGINE
     * Dynamically increments the item views metric on every unique page view trigger.
     */
    $updateViewsStmt = $pdo->prepare("
        UPDATE items 
        SET views = views + 1 
        WHERE id = ? 
        LIMIT 1
    ");
    $updateViewsStmt->execute([(int)$item['id']]);

} catch (Exception $e) {
    die("Market Engine Trace Exception Interruption: " . htmlspecialchars($e->getMessage()));
}

$page_title = $item['item_name'] ?? 'Item Details';

// Construct User Interface Frame Stack Order (Matching index.php Layout Architecture)
require_once __DIR__ . '/sections/header.php';
require_once __DIR__ . '/sections/navbar.php';
?>

<div class="bg-nftDark text-white antialiased min-h-screen pt-28 pb-20">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-10">
        
        <div class="flex items-center space-x-2 text-xs font-bold uppercase tracking-widest text-nftTextGray">
            <a href="<?php echo htmlspecialchars(app_url('index.php'), ENT_QUOTES, 'UTF-8'); ?>" class="hover:text-nftAccentCyan transition-colors">Marketplace</a>
            <span>/</span>
            <a href="<?php echo htmlspecialchars(app_url('category-items/' . (int)$item['category_id']), ENT_QUOTES, 'UTF-8'); ?>" class="hover:text-nftAccentCyan transition-colors"><?php echo htmlspecialchars($item['category_name'] ?? 'Uncategorized'); ?></a>
            <span>/</span>
            <span class="text-nftAccentPurple truncate max-w-[200px] sm:max-w-none"><?php echo htmlspecialchars($item['item_name']); ?></span>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
            
            <div class="lg:col-span-2 space-y-8">
                
                <div class="glass-card p-4 sm:p-6 rounded-2xl border border-slate-800/80 space-y-4 shadow-xl">
                    
                    <div class="w-full aspect-[16/10] rounded-xl bg-slate-950 border border-slate-900 overflow-hidden shadow-inner relative group">
                        <img id="masterGalleryViewport" src="<?php echo htmlspecialchars(media_url($item['feature_image'] ?? '', 'assets/img/placeholder.png'), ENT_QUOTES, 'UTF-8'); ?>" alt="Product Core Representation Showcase" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-[1.01]">
                    </div>

                    <div class="grid grid-cols-3 gap-3">
                        <?php if(!empty($item['feature_image'])): ?>
                            <button type="button" onclick="swapViewportMedia(<?php echo htmlspecialchars(json_encode(media_url($item['feature_image'])), ENT_QUOTES, 'UTF-8'); ?>)" class="aspect-[4/3] rounded-lg bg-slate-950 border border-nftAccentCyan overflow-hidden transition-all hover:border-nftAccentCyan focus:outline-none gallery-thumb-btn">
                                <img src="<?php echo htmlspecialchars(media_url($item['feature_image']), ENT_QUOTES, 'UTF-8'); ?>" class="w-full h-full object-cover">
                            </button>
                        <?php endif; ?>

                        <?php if(!empty($item['screenshot_2'])): ?>
                            <button type="button" onclick="swapViewportMedia(<?php echo htmlspecialchars(json_encode(media_url($item['screenshot_2'])), ENT_QUOTES, 'UTF-8'); ?>)" class="aspect-[4/3] rounded-lg bg-slate-950 border border-slate-900 overflow-hidden transition-all hover:border-nftAccentCyan focus:outline-none gallery-thumb-btn">
                                <img src="<?php echo htmlspecialchars(media_url($item['screenshot_2']), ENT_QUOTES, 'UTF-8'); ?>" class="w-full h-full object-cover">
                            </button>
                        <?php endif; ?>

                        <?php if(!empty($item['screenshot_3'])): ?>
                            <button type="button" onclick="swapViewportMedia(<?php echo htmlspecialchars(json_encode(media_url($item['screenshot_3'])), ENT_QUOTES, 'UTF-8'); ?>)" class="aspect-[4/3] rounded-lg bg-slate-950 border border-slate-900 overflow-hidden transition-all hover:border-nftAccentCyan focus:outline-none gallery-thumb-btn">
                                <img src="<?php echo htmlspecialchars(media_url($item['screenshot_3']), ENT_QUOTES, 'UTF-8'); ?>" class="w-full h-full object-cover">
                            </button>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-6 shadow-lg">
                    
                    <div class="flex items-center space-x-6 border-b border-slate-900/80 pb-4">
                        <button type="button" class="text-sm font-bold uppercase tracking-wider border-b-2 border-nftAccentCyan pb-4 text-white focus:outline-none">
                            Description Specifications
                        </button>
                    </div>

                    <div class="text-slate-300 text-sm font-medium leading-relaxed space-y-4 whitespace-pre-line font-sans antialiased">
                        <?php echo htmlspecialchars($item['item_details']); ?>
                    </div>
                </div>

                <?php if (!empty($item['video_url'])): ?>
                    <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-4 shadow-lg">
                        <h3 class="text-sm font-bold uppercase text-nftAccentPurple tracking-wider border-b border-slate-900 pb-3">// Video Walkthrough Demonstration</h3>
                        
                        <div class="w-full aspect-video rounded-xl bg-slate-950 border border-slate-900 overflow-hidden shadow-inner">
                            <?php 
                            // Extract common YouTube video token parameters seamlessly if applicable
                            if (preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/', $item['video_url'], $matches)) {
                                $youtube_id = $matches[1];
                                echo '<iframe class="w-full h-full" src="https://www.youtube.com/embed/' . $youtube_id . '" title="Product Video Feature Demonstration" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>';
                            } else {
                                // Standard system fallback browser rendering path if general link provided
                                echo '<div class="w-full h-full flex flex-col items-center justify-center p-6 text-center space-y-3 bg-slate-950/40">
                                        <i class="fa-solid fa-play-circle text-4xl text-slate-700"></i>
                                        <p class="text-xs text-slate-400">External media container track configuration active.</p>
                                        <a href="' . htmlspecialchars($item['video_url']) . '" target="_blank" rel="noopener" class="inline-flex items-center gap-1.5 text-xs text-nftAccentCyan font-bold hover:underline">Launch Presentation Stream &rarr;</a>
                                      </div>';
                            }
                            ?>
                        </div>
                    </div>
                <?php endif; ?>
                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 shadow-lg">
    
    <div class="flex items-center justify-between mb-6 border-b border-slate-900 pb-4">
        <div>
            <h3 class="text-lg font-bold text-white">
                Customer Reviews
            </h3>
            <p class="text-sm text-slate-400">
                <?php echo $average_rating; ?>/5 Rating from <?php echo $total_reviews; ?> Reviews
            </p>
        </div>

        <div class="text-right">
            <div class="text-3xl font-bold text-yellow-400">
                <?php echo $average_rating; ?>
            </div>
            <div class="text-yellow-400">
                <?php
                $fullStars = floor($average_rating);

                for($i=1;$i<=5;$i++){
                    if($i <= $fullStars){
                        echo '<i class="fas fa-star"></i>';
                    }else{
                        echo '<i class="far fa-star"></i>';
                    }
                }
                ?>
            </div>
        </div>
    </div>

    <div class="space-y-4">

        <?php foreach($reviews as $review): ?>

        <div class="bg-slate-950/40 border border-slate-800 rounded-xl p-4">

            <div class="flex items-center justify-between mb-2">

                <div>
                    <h4 class="font-semibold text-white">
                        <?php echo htmlspecialchars($review['client_name']); ?>
                    </h4>

                    <div class="text-yellow-400 text-sm">
                        <?php
                        for($i=1;$i<=5;$i++){
                            if($i <= $review['rating']){
                                echo '<i class="fas fa-star"></i>';
                            }else{
                                echo '<i class="far fa-star"></i>';
                            }
                        }
                        ?>
                    </div>
                </div>

                <div class="text-xs text-slate-500">
                    <?php echo date('M d, Y', strtotime($review['created_at'])); ?>
                </div>

            </div>

            <p class="text-sm text-slate-300 leading-relaxed">
                <?php echo nl2br(htmlspecialchars($review['review_text'])); ?>
            </p>

        </div>

        <?php endforeach; ?>

    </div>
</div>
            </div>
            <?php if ($total_reviews > 0): ?>

<?php endif; ?>
            <div class="space-y-6">
                
                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-5 shadow-lg bg-gradient-to-b from-slate-950/30 to-slate-950/80 relative overflow-hidden">
                    
                    <div class="space-y-1">
                        <span class="text-[10px] font-bold uppercase tracking-widest text-nftTextGray block">Standard Commercial License Fee</span>
                        <div class="flex items-baseline space-x-1.5">
                            <span class="text-4xl font-black font-mono tracking-tight text-emerald-400"><?php echo htmlspecialchars(format_currency($item['amount']), ENT_QUOTES, 'UTF-8'); ?></span>
                            <span class="text-xs font-bold text-slate-500 uppercase font-mono"><?php echo htmlspecialchars(get_site_currency(), ENT_QUOTES, 'UTF-8'); ?></span>
                        </div>
                    </div>

                    <hr class="border-slate-900">

                    <div class="space-y-3">
                        <a href="<?php echo htmlspecialchars(app_url('buy-now.php?item_id=' . (int)$item['id']), ENT_QUOTES, 'UTF-8'); ?>" class="w-full bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple hover:from-nftAccentCyan hover:to-nftAccentPurple/90 text-white font-extrabold text-xs uppercase tracking-widest text-center py-4 rounded-xl shadow-md block transition-all hover:shadow-lg active:scale-[0.99] transform">
                            <i class="fa-solid fa-bolt mr-2 text-xs"></i> Acquire & Buy It Now
                        </a>

                        <?php if (!empty($item['demo_url'])): ?>
                            <a href="<?php echo htmlspecialchars($item['demo_url']); ?>" target="_blank" rel="noopener" class="w-full bg-slate-950 hover:bg-slate-900 border border-slate-900 hover:border-slate-800 text-nftAccentCyan font-bold text-xs uppercase tracking-widest text-center py-3.5 rounded-xl block transition-colors">
                                <i class="fa-solid fa-square-rss mr-2 text-xs"></i> Launch Live Frame Demo
                            </a>
                        <?php endif; ?>
                    </div>

                    <div class="flex items-center justify-center space-x-2 text-[11px] font-bold text-nftTextGray uppercase tracking-wider font-mono bg-slate-950/50 py-2 rounded-lg border border-slate-900/60">
                        <i class="fa-solid fa-shield-halved text-emerald-500"></i>
                        <span>Includes <?php echo (int)$item['support_days']; ?> Days Maintenance Window Cover</span>
                    </div>
                </div>

                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-4 shadow-lg">
                    <h3 class="text-xs font-bold uppercase text-slate-400 tracking-wider border-b border-slate-900 pb-3">// Product Property Specifications Array</h3>
                    
                    <div class="divide-y divide-slate-900/60 text-xs font-medium">
                        
                        <div class="flex items-center justify-between py-3">
                            <span class="text-nftTextGray">System Asset ID</span>
                            <span class="font-mono text-white bg-slate-950 px-2 py-0.5 rounded border border-slate-900 text-[11px]">#<?php echo str_pad($item['id'], 6, '0', STR_PAD_LEFT); ?></span>
                        </div>

                        <div class="flex items-center justify-between py-3">
                            <span class="text-nftTextGray">Category Domain</span>
                            <span class="text-slate-200"><?php echo htmlspecialchars($item['category_name'] ?? 'General Asset'); ?></span>
                        </div>

                        <?php if(!empty($item['ai_brain_used'])): ?>
                            <div class="flex items-center justify-between py-3">
                                <span class="text-nftTextGray">AI Core Blueprint Model</span>
                                <span class="text-nftAccentCyan font-bold tracking-wide"><?php echo htmlspecialchars($item['ai_brain_used']); ?></span>
                            </div>
                        <?php endif; ?>

                        <?php if(!empty($item['files_included'])): ?>
                            <div class="flex items-center justify-between py-3">
                                <span class="text-nftTextGray">Packages Inclusions</span>
                                <span class="text-slate-300 text-right max-w-[180px] truncate" title="<?php echo htmlspecialchars($item['files_included']); ?>"><?php echo htmlspecialchars($item['files_included']); ?></span>
                            </div>
                        <?php endif; ?>

                        <div class="flex items-center justify-between py-3">
                            <span class="text-nftTextGray">Registry Data Release</span>
                            <span class="font-mono text-slate-400"><?php echo date('M d, Y', strtotime($item['created_at'])); ?></span>
                        </div>

                        <div class="flex items-center justify-between py-3">
    <span class="text-nftTextGray">Total Sales</span>
    <span class="font-mono font-bold text-emerald-400">
        <?php echo number_format($item['total_sales']); ?>
    </span>
</div>

<div class="flex items-center justify-between py-3">
    <span class="text-nftTextGray">Average Rating</span>
    <span class="font-mono font-bold text-yellow-400">
        <?php echo number_format($average_rating, 1); ?>/5
    </span>
</div>

<div class="flex items-center justify-between py-3">
    <span class="text-nftTextGray">Total Reviews</span>
    <span class="font-mono font-bold text-cyan-400">
        <?php echo number_format($total_reviews); ?>
    </span>
</div>

                    </div>
                </div>

                <div class="glass-card p-4 sm:p-5 rounded-2xl border border-slate-800/80 shadow-md bg-gradient-to-b from-slate-950/10 to-slate-950/40">

    <div class="flex items-center space-x-3.5">
        <div class="w-12 h-12 rounded-xl bg-slate-950 border border-slate-900 overflow-hidden shrink-0 shadow-md">
            <img src="<?php echo htmlspecialchars(media_url($item['profile_picture'] ?? '', 'assets/img/avatar.png'), ENT_QUOTES, 'UTF-8'); ?>" alt="Authorized Registered Vendor Account Profile Photo" class="w-full h-full object-cover">
        </div>

        <div class="space-y-0.5 min-w-0">
            <span class="text-[10px] font-bold uppercase tracking-widest text-nftTextGray block">
                Registered Asset Owner
            </span>

            <h4 class="text-sm font-bold text-white truncate">
                <?php echo htmlspecialchars($item['seller_name'] ?? 'System Core Marketplace'); ?>
            </h4>
        </div>
    </div>

    <div class="mt-4 pt-4 border-t border-slate-800">
        <div class="grid grid-cols-3 gap-3 text-center">

            <div>
                <div class="text-lg font-bold text-emerald-400">
                    <?php echo $item['total_sales']; ?>
                </div>
                <div class="text-[10px] uppercase text-slate-500">
                    Sales
                </div>
            </div>

            <div>
                <div class="text-lg font-bold text-yellow-400">
                    <?php echo number_format($average_rating, 1); ?>
                </div>
                <div class="text-[10px] uppercase text-slate-500">
                    Rating
                </div>
            </div>

            <div>
                <div class="text-lg font-bold text-cyan-400">
                    <?php echo $total_reviews; ?>
                </div>
                <div class="text-[10px] uppercase text-slate-500">
                    Reviews
                </div>
            </div>

        </div>
    </div>

</div>

            </div>

        </div>

    </div>
</div>

<script>
/**
 * VIEWPORT INTERFACE MODULATOR
 * Intercepts dynamic selection triggers to shift frame visualization mappings across alternative showcase media options.
 */
function swapViewportMedia(targetMediaSourceUrl) {
    const targetViewportNode = document.getElementById('masterGalleryViewport');
    if (!targetViewportNode || !targetMediaSourceUrl) return;
    
    targetViewportNode.src = targetMediaSourceUrl;
    
    // Highlight active thumbnail selection
    const buttons = document.querySelectorAll('.gallery-thumb-btn');
    buttons.forEach(btn => {
        btn.classList.remove('border-nftAccentCyan');
        btn.classList.add('border-slate-900');
    });
    
    // Bind to triggered event context anchor pointer
    const firingEventNode = event.currentTarget;
    if (firingEventNode) {
        firingEventNode.classList.remove('border-slate-900');
        firingEventNode.classList.add('border-nftAccentCyan');
    }
}
</script>

<?php 
// Finalize Construction Order Stack Pipeline Flow
require_once __DIR__ . '/sections/footer.php';
?>
