<?php
// Product Detail Page
require_once 'visitor_tracker.php';

// Get product ID from URL
$productId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($productId <= 0) {
    die('Invalid product ID');
}

// Initialize variables
$mainProduct = null;
$relatedProducts = [];
$productNumber = '';

try {
    $tracker = new VisitorTracker();
    $conn = $tracker->getConnection();
    
    if ($conn && !$conn->connect_error) {
        // Get main product details
        $stmt = $conn->prepare("SELECT id, name, link, image FROM products WHERE id = ?");
        $stmt->bind_param('i', $productId);
        $stmt->execute();
        $stmt->bind_result($id, $name, $link, $image);
        
        if ($stmt->fetch()) {
            $mainProduct = [
                'id' => $id,
                'name' => $name,
                'link' => $link,
                'image' => $image
            ];
        }
        $stmt->close();
        
        if (!$mainProduct) {
            die('Product not found');
        }
        
        // Extract base number from product name (e.g., "celana 18B" -> "18")
        // Try to match patterns like "18B", "18", "856A", etc.
        preg_match('/(\d+)[A-Za-z]?$/i', $mainProduct['name'], $matches);
        $baseNumber = isset($matches[1]) ? $matches[1] : '';
        
        if ($baseNumber) {
            // Find all products with same base number
            // Pattern: name ends with baseNumber followed by optional letter
            $searchPattern = "%{$baseNumber}%";
            $stmt = $conn->prepare("
                SELECT id, name, link, image 
                FROM products 
                WHERE name LIKE ? 
                ORDER BY name ASC
            ");
            $stmt->bind_param('s', $searchPattern);
            $stmt->execute();
            $stmt->bind_result($id, $name, $link, $image);
            
            while ($stmt->fetch()) {
                // Verify this is actually a variant (ends with baseNumber + optional letter)
                if (preg_match('/\b' . preg_quote($baseNumber, '/') . '[A-Za-z]?\b/i', $name)) {
                    $relatedProducts[] = [
                        'id' => $id,
                        'name' => $name,
                        'link' => $link,
                        'image' => $image
                    ];
                }
            }
            $stmt->close();
        }
    }
} catch (Exception $e) {
    error_log('Error loading product details: ' . $e->getMessage());
    die('Error loading product');
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php 
        // Extract base number for title
        preg_match('/(\d+)[A-Za-z]?$/i', $mainProduct['name'], $titleMatches);
        $titleNumber = isset($titleMatches[1]) ? $titleMatches[1] : ucfirst($mainProduct['name']);
        echo htmlspecialchars('Produk No - ' . $titleNumber);
    ?> - Detail Produk</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #e3f2fd 0%, #ffffff 100%);
            color: #1a237e;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .back-button {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 24px;
            background: #ffffff;
            border: 2px solid #90caf9;
            color: #1976d2;
            text-decoration: none;
            border-radius: 10px;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s;
            box-shadow: 0 2px 8px rgba(25, 118, 210, 0.1);
            margin-bottom: 30px;
        }

        .back-button:hover {
            background: #e3f2fd;
            border-color: #2196f3;
            transform: translateX(-4px);
            box-shadow: 0 4px 16px rgba(33, 150, 243, 0.3);
        }

        .back-button::before {
            content: '←';
            font-size: 18px;
        }

        .product-detail {
            background: #ffffff;
            border: 3px solid #90caf9;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 8px 32px rgba(25, 118, 210, 0.2);
        }

        .product-header {
            background: linear-gradient(135deg, #1976d2 0%, #2196f3 100%);
            padding: 30px;
            text-align: center;
            border-bottom: 3px solid #1565c0;
        }

        .product-header h1 {
            color: #ffffff;
            font-size: 28px;
            font-weight: 700;
            text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        }

        .product-content {
            padding: 40px;
        }

        .main-image-container {
            text-align: center;
            margin-bottom: 40px;
            background: #f5f5f5;
            border-radius: 12px;
            padding: 20px;
            border: 2px solid #e3f2fd;
        }

        .main-image {
            max-width: 100%;
            height: auto;
            width: auto;
            max-height: 600px;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
            object-fit: contain;
        }

        .variants-section {
            margin-top: 40px;
        }

        .variants-title {
            font-size: 20px;
            font-weight: 700;
            color: #1565c0;
            margin-bottom: 20px;
            text-align: center;
            padding-bottom: 15px;
            border-bottom: 3px solid #90caf9;
        }

        .variants-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .variant-button {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 20px 15px;
            background: #ffffff;
            border: 3px solid #90caf9;
            border-radius: 12px;
            text-decoration: none;
            color: #1976d2;
            font-weight: 600;
            font-size: 15px;
            transition: all 0.3s;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(25, 118, 210, 0.1);
            position: relative;
            overflow: hidden;
            min-height: 80px;
            text-align: center;
        }

        .variant-button:hover {
            background: #e3f2fd;
            border-color: #2196f3;
            transform: translateY(-4px);
            box-shadow: 0 8px 24px rgba(33, 150, 243, 0.3);
        }

        .variant-button.active {
            background: linear-gradient(135deg, #1976d2 0%, #2196f3 100%);
            color: #ffffff;
            border-color: #1565c0;
            box-shadow: 0 6px 20px rgba(25, 118, 210, 0.4);
        }

        .variant-button.active:hover {
            transform: translateY(-2px);
        }

        .variant-name {
            line-height: 1.4;
            word-break: break-word;
        }

        .no-variants {
            text-align: center;
            padding: 40px;
            background: #e3f2fd;
            border: 2px solid #90caf9;
            border-radius: 12px;
            color: #1976d2;
        }

        .no-variants p {
            margin-top: 10px;
            color: #64b5f6;
        }

        @media (max-width: 768px) {
            .product-content {
                padding: 20px;
            }

            .product-header h1 {
                font-size: 22px;
            }

            .main-image {
                max-height: 400px;
            }

            .variants-grid {
                grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
                gap: 12px;
            }

            .variant-button {
                padding: 15px 10px;
                font-size: 13px;
                min-height: 70px;
            }
        }

        @media (max-width: 480px) {
            body {
                padding: 10px;
            }

            .back-button {
                padding: 10px 18px;
                font-size: 13px;
            }

            .product-header {
                padding: 20px;
            }

            .product-header h1 {
                font-size: 18px;
            }

            .variants-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 10px;
            }

            .variant-button {
                padding: 12px 8px;
                font-size: 12px;
                min-height: 60px;
            }
        }

        /* Loading animation */
        .loading {
            text-align: center;
            padding: 60px 20px;
            color: #1976d2;
        }

        .loading::after {
            content: '...';
            animation: dots 1.5s infinite;
        }

        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60%, 100% { content: '...'; }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="index.php" class="back-button">Kembali ke Beranda</a>

        <div class="product-detail">
            <div class="product-header">
                <h1><?php 
                    // Extract base number from product name (e.g., "atasan 15A" -> "15")
                    preg_match('/(\d+)[A-Za-z]?$/i', $mainProduct['name'], $numberMatches);
                    $baseNumber = isset($numberMatches[1]) ? $numberMatches[1] : '';
                    
                    if ($baseNumber) {
                        echo 'Produk No - ' . htmlspecialchars($baseNumber);
                    } else {
                        // Fallback to original name if no number found
                        $displayName = ucfirst(trim($mainProduct['name']));
                        $lastSpacePos = strrpos($displayName, ' ');
                        if ($lastSpacePos !== false) {
                            $displayName = substr_replace($displayName, ' - ', $lastSpacePos, 1);
                        }
                        echo htmlspecialchars($displayName);
                    }
                ?></h1>
            </div>

            <div class="product-content">
                <!-- Main Product Image -->
                <div class="main-image-container">
                    <img src="<?php echo htmlspecialchars($mainProduct['image']); ?>" 
                         alt="<?php echo htmlspecialchars($mainProduct['name']); ?>" 
                         class="main-image"
                         onload="this.style.opacity=1"
                         style="opacity:0; transition: opacity 0.3s;">
                </div>

                <!-- Product Variants -->
                <?php if (count($relatedProducts) > 0): ?>
                <div class="variants-section">
                    <h2 class="variants-title">
                        Link Varian Produk (<?php echo count($relatedProducts); ?> Varian)
                    </h2>
                    <div class="variants-grid">
                        <?php foreach ($relatedProducts as $variant): ?>
                            <?php
                                // Format nama produk: "celana 18B" -> "Celana - 18B"
                                $displayName = ucfirst(trim($variant['name']));
                                $lastSpacePos = strrpos($displayName, ' ');
                                if ($lastSpacePos !== false) {
                                    $displayName = substr_replace($displayName, ' - ', $lastSpacePos, 1);
                                }
                            ?>
                            <a href="<?php echo htmlspecialchars($variant['link']); ?>" 
                               target="_blank"
                               class="variant-button"
                               onclick="trackVariantClick('<?php echo htmlspecialchars($variant['name']); ?>', '<?php echo htmlspecialchars($variant['link']); ?>')">
                                <span class="variant-name"><?php echo htmlspecialchars($displayName); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php else: ?>
                <div class="no-variants">
                    <h3>Tidak Ada Varian Lain</h3>
                    <p>Produk ini tidak memiliki varian lain yang tersedia</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        // Track variant click
        function trackVariantClick(productName, productLink) {
            const numberMatch = productName.match(/\d+/);
            const productNumber = numberMatch ? numberMatch[0] : '';
            
            fetch('track_click.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `product_name=${encodeURIComponent(productName)}&product_link=${encodeURIComponent(productLink)}&product_number=${encodeURIComponent(productNumber)}&source=detail_page`
            }).catch(err => console.log('Track error:', err));
        }

        // Smooth image loading
        document.addEventListener('DOMContentLoaded', function() {
            const mainImage = document.querySelector('.main-image');
            if (mainImage && mainImage.complete) {
                mainImage.style.opacity = '1';
            }
        });

        // Keyboard navigation
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                window.location.href = 'index.php';
            }
        });
    </script>

    <?php include 'footer.php'; ?>
</body>
</html>

