<?php
/**
 * GlobalExpress - Integrated UK Shopping Catalog
 * Updated to work with ASOS, H&M (real API) and Tesco (mock)
 * Amazon disabled until API keys are available
 */

session_start();
error_reporting(E_ALL);
ini_set('display_errors', 0); // Set to 1 for debugging
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/shopping_errors.log');

// Database configuration
require_once __DIR__ . '/config/database.php';

// API Clients
require_once __DIR__ . '/includes/apis/AsosAPI.php';
// require_once __DIR__ . '/includes/apis/AmazonAPI.php'; // Disabled - no API keys yet
require_once __DIR__ . '/includes/apis/TescoAPI.php';
require_once __DIR__ . '/includes/apis/HMApi.php';

// Helper functions
require_once __DIR__ . '/includes/helpers.php';

// Check if user is logged in
$user_id = $_SESSION['user_id'] ?? null;
$user = null;

if ($user_id) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
}

// Get search parameters
$search_query = $_GET['q'] ?? '';
$category = $_GET['category'] ?? 'all';
$store = $_GET['store'] ?? 'all';
$sort = $_GET['sort'] ?? 'relevance';
$min_price = $_GET['min_price'] ?? 0;
$max_price = $_GET['max_price'] ?? 10000;

// Exchange rate (GBP to AZN)
$exchange_rate = EXCHANGE_RATE_GBP_TO_AZN;

// Delivery and fees configuration
$delivery_fee_air = DELIVERY_FEE_PER_KG;
$customs_rate = CUSTOMS_RATE;
$ge_commission = GE_COMMISSION_RATE;

// Initialize API clients (only for available stores)
$asosAPI = new AsosAPI();
// $amazonAPI = new AmazonAPI(); // Disabled
$tescoAPI = new TescoAPI();
$hmAPI = new HMApi();

// Available stores (Amazon removed for now)
$available_stores = ['asos', 'tesco', 'hm'];

// Search products if query exists
$products = [];
$search_performed = false;
$errors = [];

if (!empty($search_query)) {
    $search_performed = true;
    
    // Log search
    try {
        $stmt = $pdo->prepare("
            INSERT INTO product_search_history (user_id, search_query, store, category, ip_address, created_at)
            VALUES (?, ?, ?, ?, ?, NOW())
        ");
        $stmt->execute([$user_id, $search_query, $store, $category, $_SERVER['REMOTE_ADDR'] ?? null]);
    } catch (PDOException $e) {
        error_log("Search history log error: " . $e->getMessage());
    }
    
    // Parallel API calls (with error handling)
    try {
        // ASOS - Real API
        if (($store === 'all' || $store === 'asos') && in_array('asos', $available_stores)) {
            try {
                $asos_products = $asosAPI->search($search_query, [
                    'category' => $category,
                    'sort' => $sort,
                    'limit' => 20
                ]);
                if ($asos_products) {
                    $products['asos'] = processProducts($asos_products, 'asos', $exchange_rate);
                }
            } catch (Exception $e) {
                $errors[] = "ASOS: " . $e->getMessage();
                error_log("ASOS API Error: " . $e->getMessage());
            }
        }
        
        // Amazon - DISABLED (no API keys yet)
        /*
        if (($store === 'all' || $store === 'amazon') && in_array('amazon', $available_stores)) {
            try {
                $amazon_products = $amazonAPI->search($search_query, [
                    'category' => $category,
                    'sort' => $sort,
                    'limit' => 20
                ]);
                if ($amazon_products) {
                    $products['amazon'] = processProducts($amazon_products, 'amazon', $exchange_rate);
                }
            } catch (Exception $e) {
                $errors[] = "Amazon: " . $e->getMessage();
                error_log("Amazon API Error: " . $e->getMessage());
            }
        }
        */
        
        // Tesco - Mock Data
        if (($store === 'all' || $store === 'tesco') && in_array('tesco', $available_stores)) {
            try {
                $tesco_products = $tescoAPI->search($search_query, [
                    'category' => $category,
                    'sort' => $sort,
                    'limit' => 20
                ]);
                if ($tesco_products) {
                    $products['tesco'] = processProducts($tesco_products, 'tesco', $exchange_rate);
                }
            } catch (Exception $e) {
                $errors[] = "Tesco: " . $e->getMessage();
                error_log("Tesco API Error: " . $e->getMessage());
            }
        }
        
        // H&M - Real API
        if (($store === 'all' || $store === 'hm') && in_array('hm', $available_stores)) {
            try {
                $hm_products = $hmAPI->search($search_query, [
                    'category' => $category,
                    'sort' => $sort,
                    'limit' => 20
                ]);
                if ($hm_products) {
                    $products['hm'] = processProducts($hm_products, 'hm', $exchange_rate);
                }
            } catch (Exception $e) {
                $errors[] = "H&M: " . $e->getMessage();
                error_log("H&M API Error: " . $e->getMessage());
            }
        }
        
    } catch (Exception $e) {
        $error = "Error fetching products: " . $e->getMessage();
        error_log($error);
    }
}


/**
 * Process and enrich products with GlobalExpress pricing
 */
function processProducts($raw_products, $store, $exchange_rate) {
    global $delivery_fee_air, $customs_rate, $ge_commission;
    
    if (empty($raw_products)) {
        return [];
    }
    
    $processed = [];
    
    foreach ($raw_products as $product) {
        // Skip invalid products
        if (!isset($product['price']) || $product['price'] <= 0) {
            continue;
        }
        
        // Calculate all costs
        $price_gbp = $product['price'];
        $price_azn = $price_gbp * $exchange_rate;
        
        // Estimate weight (from API or default)
        $weight = $product['weight'] ?? 0.5; // kg
        
        // Calculate delivery
        $delivery_cost = $weight * $delivery_fee_air;
        
        // Calculate customs
        $customs_cost = $price_azn * $customs_rate;
        
        // Calculate GE commission
        $commission = $price_azn * $ge_commission;
        
        // Total price
        $total_price = $price_azn + $delivery_cost + $customs_cost + $commission;
        
        $processed[] = [
            'id' => $product['id'],
            'store' => $store,
            'name' => $product['name'],
            'brand' => $product['brand'] ?? '',
            'description' => $product['description'] ?? '',
            'image' => $product['image'],
            'images' => $product['images'] ?? [],
            'url' => $product['url'],
            'category' => $product['category'] ?? '',
            'rating' => $product['rating'] ?? 0,
            'reviews_count' => $product['reviews_count'] ?? 0,
            'availability' => $product['availability'] ?? 'in_stock',
            
            // Pricing breakdown
            'price_gbp' => $price_gbp,
            'price_azn' => $price_azn,
            'weight' => $weight,
            'delivery_cost' => $delivery_cost,
            'customs_cost' => $customs_cost,
            'commission' => $commission,
            'total_price' => $total_price,
            
            // Additional info
            'size_options' => $product['sizes'] ?? [],
            'color_options' => $product['colors'] ?? [],
            'estimated_delivery' => calculateDeliveryTime($store),
        ];
    }
    
    return $processed;
}

// Flatten products for display
$all_products = [];
foreach ($products as $store_products) {
    $all_products = array_merge($all_products, $store_products);
}

// Filter by price
$all_products = array_filter($all_products, function($p) use ($min_price, $max_price) {
    return $p['total_price'] >= $min_price && $p['total_price'] <= $max_price;
});

// Sort products
usort($all_products, function($a, $b) use ($sort) {
    switch ($sort) {
        case 'price_low':
            return $a['total_price'] <=> $b['total_price'];
        case 'price_high':
            return $b['total_price'] <=> $a['total_price'];
        case 'rating':
            return $b['rating'] <=> $a['rating'];
        default:
            return 0;
    }
});

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>UK Shopping - GlobalExpress</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary: #528d8e;
            --primary-dark: #3a6566;
            --accent: #ff6b6b;
            --text-dark: #2c3e50;
            --text-light: #ffffff;
            --bg-light: #f8fafb;
            --border: #e1e8ed;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--bg-light);
            color: var(--text-dark);
        }

        .header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
            color: white;
            padding: 1.5rem 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 2rem;
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .logo {
            font-size: 1.8rem;
            font-weight: 700;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .user-info a {
            color: white;
            text-decoration: none;
            font-weight: 500;
        }

        .search-section {
            background: white;
            padding: 2rem;
            margin: 2rem auto;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .search-form {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }

        .search-input {
            flex: 1;
            min-width: 300px;
            padding: 1rem;
            border: 2px solid var(--border);
            border-radius: 8px;
            font-size: 1rem;
        }

        .search-button {
            padding: 1rem 2rem;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
        }

        .search-button:hover {
            background: var(--primary-dark);
        }

        .stores-tabs {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1rem;
            border-bottom: 2px solid var(--border);
            overflow-x: auto;
        }

        .store-tab {
            padding: 1rem 1.5rem;
            background: transparent;
            border: none;
            border-bottom: 3px solid transparent;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            color: var(--text-dark);
            transition: all 0.3s;
            white-space: nowrap;
            text-decoration: none;
            display: inline-block;
        }

        .store-tab:hover {
            color: var(--primary);
        }

        .store-tab.active {
            color: var(--primary);
            border-bottom-color: var(--primary);
        }

        .store-tab.disabled {
            opacity: 0.5;
            cursor: not-allowed;
            text-decoration: line-through;
        }

        .products-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 2rem;
            margin-bottom: 3rem;
        }

        .product-card {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            transition: all 0.3s;
            display: flex;
            flex-direction: column;
        }

        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0,0,0,0.15);
        }

        .product-image-container {
            position: relative;
            padding-top: 120%;
            background: #f5f5f5;
            overflow: hidden;
        }

        .product-image-container img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .store-badge {
            position: absolute;
            top: 10px;
            left: 10px;
            padding: 0.4rem 0.8rem;
            background: white;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .store-badge.asos { color: #e91e63; }
        .store-badge.amazon { color: #ff9900; }
        .store-badge.tesco { color: #0050b3; }
        .store-badge.hm { color: #e50010; }

        .product-info {
            padding: 1.5rem;
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .product-name {
            font-size: 1rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: var(--text-dark);
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .price-breakdown {
            background: var(--bg-light);
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            font-size: 0.9rem;
        }

        .price-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
            color: #666;
        }

        .price-row.total {
            border-top: 2px solid var(--border);
            padding-top: 0.5rem;
            margin-top: 0.5rem;
            font-weight: 700;
            font-size: 1.1rem;
            color: var(--text-dark);
        }

        .btn-primary {
            padding: 0.9rem;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary:hover {
            background: var(--primary-dark);
        }

        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
            background: white;
            border-radius: 12px;
        }

        .empty-state-icon {
            font-size: 5rem;
            margin-bottom: 1rem;
        }

        .info-banner {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 1rem 1.5rem;
            margin-bottom: 2rem;
            border-radius: 4px;
        }

        .error-banner {
            background: #f8d7da;
            border-left: 4px solid #dc3545;
            padding: 1rem 1.5rem;
            margin-bottom: 2rem;
            border-radius: 4px;
            color: #721c24;
        }

        @media (max-width: 768px) {
            .products-grid {
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
                gap: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="container">
            <div class="header-content">
                <div class="logo">
                    🛍️ GlobalExpress UK Shopping
                </div>
                <div class="user-info">
                    <?php if ($user): ?>
                        <span>Welcome, <?= htmlspecialchars($user['full_name']) ?></span>
                        <a href="cart.php">Cart</a>
                        <a href="dashboard.php">Dashboard</a>
                    <?php else: ?>
                        <a href="login.php">Login</a>
                        <a href="register.php">Register</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <?php if (!empty($errors)): ?>
        <div class="error-banner">
            <strong>⚠️ API Errors:</strong><br>
            <?php foreach ($errors as $error): ?>
                • <?= htmlspecialchars($error) ?><br>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <div class="search-section">
            <form method="GET" class="search-form">
                <input 
                    type="text" 
                    name="q" 
                    class="search-input" 
                    placeholder="Search products from UK stores..."
                    value="<?= htmlspecialchars($search_query) ?>"
                >
                <button type="submit" class="search-button">
                    🔍 Search
                </button>
            </form>

            <div class="stores-tabs">
                <a href="?q=<?= urlencode($search_query) ?>&store=all" 
                   class="store-tab <?= $store === 'all' ? 'active' : '' ?>">
                    🌐 All Stores
                </a>
                <a href="?q=<?= urlencode($search_query) ?>&store=asos" 
                   class="store-tab <?= $store === 'asos' ? 'active' : '' ?>">
                    👗 ASOS
                </a>
                <span class="store-tab disabled" title="Amazon API not configured yet">
                    📦 Amazon UK
                </span>
                <a href="?q=<?= urlencode($search_query) ?>&store=tesco" 
                   class="store-tab <?= $store === 'tesco' ? 'active' : '' ?>">
                    🛒 Tesco
                </a>
                <a href="?q=<?= urlencode($search_query) ?>&store=hm" 
                   class="store-tab <?= $store === 'hm' ? 'active' : '' ?>">
                    👕 H&M
                </a>
            </div>
        </div>

        <?php if (!$search_performed): ?>
            <div class="info-banner">
                <strong>✨ Available Stores:</strong> ASOS (✓), H&M (✓), Tesco (demo data)<br>
                <strong>📦 Coming Soon:</strong> Amazon UK (API keys pending)
            </div>

            <div class="empty-state">
                <div class="empty-state-icon">🔍</div>
                <h3>Start Shopping from UK!</h3>
                <p>Search for products from ASOS, H&M, and more</p>
            </div>

        <?php elseif (empty($all_products)): ?>
            <div class="empty-state">
                <div class="empty-state-icon">😔</div>
                <h3>No Products Found</h3>
                <p>Try different keywords or check another store</p>
            </div>

        <?php else: ?>
            <div class="products-grid">
                <?php foreach ($all_products as $product): ?>
                <div class="product-card">
                    <div class="product-image-container">
                        <img src="<?= htmlspecialchars($product['image']) ?>" 
                             alt="<?= htmlspecialchars($product['name']) ?>">
                        <div class="store-badge <?= $product['store'] ?>">
                            <?= strtoupper($product['store']) ?>
                        </div>
                    </div>

                    <div class="product-info">
                        <div class="product-name">
                            <?= htmlspecialchars($product['name']) ?>
                        </div>

                        <div class="price-breakdown">
                            <div class="price-row">
                                <span>Product:</span>
                                <span>₼<?= number_format($product['price_azn'], 2) ?></span>
                            </div>
                            <div class="price-row">
                                <span>Delivery:</span>
                                <span>₼<?= number_format($product['delivery_cost'], 2) ?></span>
                            </div>
                            <div class="price-row">
                                <span>Customs:</span>
                                <span>₼<?= number_format($product['customs_cost'], 2) ?></span>
                            </div>
                            <div class="price-row">
                                <span>Service:</span>
                                <span>₼<?= number_format($product['commission'], 2) ?></span>
                            </div>
                            <div class="price-row total">
                                <span>Total:</span>
                                <span>₼<?= number_format($product['total_price'], 2) ?></span>
                            </div>
                        </div>

                        <button class="btn-primary" onclick="addToCart('<?= $product['store'] ?>', '<?= $product['id'] ?>')">
                            Add to Cart
                        </button>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function addToCart(store, productId) {
            <?php if (!$user): ?>
                alert('Please login to add items to cart');
                window.location.href = 'login.php';
                return;
            <?php endif; ?>

            fetch('api/cart/add.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ store: store, product_id: productId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Product added to cart!');
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                alert('Error adding to cart');
                console.error(error);
            });
        }
    </script>
</body>
</html>