<?php
// index.php - Homepage with Jumia Kenya-style centered layout, compact product cards, advertisements slideshow, and sidebar
session_start();
include_once 'config.php';
include_once 'header.php';
?>

<style>
    /* Jumia-style Advertisements Slideshow */
    #adCarousel .carousel-item {
        height: 400px;
        background-size: cover;
        background-position: center;
        border-radius: 8px;
    }
    #adCarousel .carousel-caption {
        background: rgba(0, 0, 0, 0.7);
        border-radius: 8px;
        padding: 15px;
        bottom: 20px;
        text-align: left;
        color: #fff;
    }
    #adCarousel .carousel-caption h5 {
        font-size: 1.8rem;
        font-weight: bold;
        color: #f68b1e; /* Jumia orange */
    }
    #adCarousel .carousel-caption p {
        font-size: 1rem;
        margin-bottom: 10px;
    }
    #adCarousel .carousel-caption .btn {
        background-color: #f68b1e;
        border-color: #f68b1e;
        font-weight: bold;
        padding: 8px 20px;
    }
    #adCarousel .carousel-control-prev, #adCarousel .carousel-control-next {
        width: 5%;
        background: rgba(0, 0, 0, 0.3);
    }
    /* Sidebar */
    .sidebar {
        background-color: #f8f9fa;
        padding: 15px;
        border-right: 1px solid #dee2e6;
    }
    .sidebar h5 {
        color: #0D6EFD;
        font-size: 1.1rem;
        margin-bottom: 15px;
    }
    .sidebar .nav-link {
        color: #6C757D;
        padding: 8px 0;
        font-size: 0.9rem;
    }
    .sidebar .nav-link:hover {
        color: #f68b1e;
    }
    .sidebar .flash-sale-banner {
        background-color: #fff3e0;
        border: 1px solid #f68b1e;
        padding: 10px;
        text-align: center;
        margin-top: 20px;
        border-radius: 4px;
    }
    .sidebar .flash-sale-banner img {
        max-width: 100%;
        height: auto;
        border-radius: 4px;
    }
    /* Main Content */
    .main-content {
        padding: 15px;
    }
    .category-card {
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    .category-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 6px 15px rgba(0,0,0,0.15);
    }
    .flash-sale {
        background-color: #e9ecef;
        border-left: 4px solid #0D6EFD;
    }
    .product-card {
        width: 200px;
        height: 350px;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    .product-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 6px 15px rgba(0,0,0,0.15);
    }
    .product-card .card-img-top {
        height: 150px;
        object-fit: cover;
        width: 100%;
    }
    .product-card .card-body {
        flex-grow: 1;
        display: flex;
        flex-direction: column;
        padding: 5px;
    }
    .product-card .card-title {
        font-size: 0.8rem;
        margin-bottom: 0.2rem;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .product-card .card-text {
        font-size: 0.7rem;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        margin-bottom: 0.2rem;
    }
    .product-card .text-primary {
        font-size: 0.8rem;
        margin-bottom: 0.2rem;
    }
    .product-card .text-muted {
        font-size: 0.7rem;
        margin-bottom: 0.2rem;
    }
    .product-card .btn-sm {
        font-size: 0.7rem;
        padding: 0.15rem 0.3rem;
    }
    .product-card .d-grid {
        margin-top: auto;
        gap: 0.2rem;
    }
    .flash-sale-badge {
        font-size: 0.65rem;
        padding: 0.15rem 0.3rem;
        background-color: #0D6EFD;
        z-index: 1;
    }
    .product-row {
        --bs-gutter-x: 0.25rem; /* Tighter horizontal spacing (~4px) */
    }
    /* Chat Box */
    .chat-btn {
        position: fixed;
        bottom: 20px;
        right: 20px;
        background-color: #f68b1e;
        color: #fff;
        border: none;
        border-radius: 50%;
        width: 50px;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        cursor: pointer;
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        z-index: 1000;
    }
    .chat-btn:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 10px rgba(0,0,0,0.3);
    }
    .chat-box {
        position: fixed;
        bottom: 80px;
        right: 20px;
        width: 300px;
        height: 400px;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        display: none;
        flex-direction: column;
        z-index: 1000;
    }
    .chat-header {
        background-color: #0D6EFD;
        color: #fff;
        padding: 10px;
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .chat-header h5 {
        margin: 0;
        font-size: 1rem;
    }
    .chat-header .close-chat {
        background: none;
        border: none;
        color: #fff;
        font-size: 1rem;
        cursor: pointer;
    }
    .chat-body {
        flex-grow: 1;
        padding: 10px;
        overflow-y: auto;
        background-color: #f8f9fa;
    }
    .chat-message {
        margin-bottom: 10px;
        padding: 8px;
        border-radius: 8px;
        max-width: 80%;
    }
    .chat-message.user {
        background-color: #0D6EFD;
        color: #fff;
        margin-left: auto;
    }
    .chat-message.bot {
        background-color: #e9ecef;
        color: #333;
        margin-right: auto;
    }
    .chat-footer {
        padding: 10px;
        border-top: 1px solid #dee2e6;
        display: flex;
        align-items: center;
    }
    .chat-footer input {
        flex-grow: 1;
        border: 1px solid #dee2e6;
        border-radius: 4px;
        padding: 8px;
        font-size: 0.9rem;
    }
    .chat-footer button {
        background-color: #f68b1e;
        border: none;
        color: #fff;
        padding: 8px 12px;
        border-radius: 4px;
        margin-left: 5px;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }
    .chat-footer button:hover {
        background-color: #d94f1f;
    }
    @media (max-width: 576px) {
        .chat-box {
            width: 90%;
            max-width: 300px;
            bottom: 60px;
            right: 10px;
        }
        .chat-btn {
            bottom: 10px;
            right: 10px;
        }
    }
</style>

<!-- Advertisements Slideshow -->
<section class="mb-4">
    <div class="container">
        <div id="adCarousel" class="carousel slide" data-bs-ride="carousel">
            <div class="carousel-inner">
                <div class="carousel-item active" style="background-image: url('images/ad4.png');">
                    <div class="carousel-caption">
                        <h5>50% Off Fashion Sale!</h5>
                        <p>Shop Doll Shoes and Slides at unbeatable prices.</p>
                        <a href="products.php?category=<?php echo $conn->query("SELECT id FROM categories WHERE name = 'Fashion'")->fetch_assoc()['id'] ?? 3; ?>" class="btn btn-primary">Shop Now</a>
                    </div>
                </div>
                <div class="carousel-item" style="background-image: url('images/ad2.png');">
                    <div class="carousel-caption">
                        <h5>New Stationery Arrivals</h5>
                        <p>Get premium notebooks and pens for back to school.</p>
                        <a href="products.php?category=<?php echo $conn->query("SELECT id FROM categories WHERE name = 'Stationery'")->fetch_assoc()['id'] ?? 1; ?>" class="btn btn-primary">Explore</a>
                    </div>
                </div>
                <div class="carousel-item" style="background-image: url('images/ad3.png');">
                    <div class="carousel-caption">
                        <h5>Sports Gear Discount</h5>
                        <p>Up to 30% off on soccer balls and rackets.</p>
                        <a href="products.php?category=<?php echo $conn->query("SELECT id FROM categories WHERE name = 'Sports'")->fetch_assoc()['id'] ?? 2; ?>" class="btn btn-primary">Buy Now</a>
                    </div>
                </div>
            </div>
            <button class="carousel-control-prev" type="button" data-bs-target="#adCarousel" data-bs-slide="prev">
                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Previous</span>
            </button>
            <button class="carousel-control-next" type="button" data-bs-target="#adCarousel" data-bs-slide="next">
                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Next</span>
            </button>
        </div>
    </div>
</section>

<!-- Main Content with Sidebar -->
<div class="container">
    <div class="row">
        <!-- Sidebar -->
        <div class="col-md-3 sidebar">
            <h5>Shop by Category</h5>
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="products.php">All Categories</a>
                </li>
                <?php
                $cats = $conn->query("SELECT * FROM categories WHERE parent_id IS NULL");
                while ($cat = $cats->fetch_assoc()): ?>
                    <li class="nav-item">
                        <a class="nav-link" href="products.php?category=<?php echo $cat['id']; ?>">
                            <i class="fas fa-<?php echo $cat['name'] == 'Fashion' ? 'tshirt' : ($cat['name'] == 'Stationery' ? 'pen' : 'futbol'); ?> me-2"></i>
                            <?php echo htmlspecialchars($cat['name']); ?>
                        </a>
                        <?php
                        $subcats = $conn->query("SELECT * FROM categories WHERE parent_id = " . $cat['id']);
                        if ($subcats->num_rows > 0): ?>
                            <ul class="nav flex-column ms-3">
                                <?php while ($subcat = $subcats->fetch_assoc()): ?>
                                    <li class="nav-item">
                                        <a class="nav-link" href="products.php?category=<?php echo $subcat['id']; ?>">
                                            <?php echo htmlspecialchars($subcat['name']); ?>
                                        </a>
                                    </li>
                                <?php endwhile; ?>
                            </ul>
                        <?php endif; ?>
                    </li>
                <?php endwhile; ?>
            </ul>
            <div class="flash-sale-banner">
                <h6>Flash Sale!</h6>
                <p>Up to 20% off select items</p>
                <img src="images/flash.jfif" alt="Flash Sale Banner">
                <a href="flash_sales.php" class="btn btn-sm btn-primary mt-2">Shop Now</a>
            </div>
        </div>
        <!-- Main Content -->
        <div class="col-md-9 main-content">
            <!-- Categories Section -->
            <section class="mb-4">
                <h2 class="text-center mb-3">Shop by Category</h2>
                <div class="row justify-content-center">
                    <?php
                    $cats = $conn->query("SELECT * FROM categories WHERE parent_id IS NULL ORDER BY sort_order, name");
                    while ($cat = $cats->fetch_assoc()):
                        $subcats = $conn->query("SELECT * FROM categories WHERE parent_id = " . $cat['id']);
                    ?>
                        <div class="col-md-4 mb-3">
                            <div class="card category-card text-center h-100">
                                <div class="card-body">
                                    <i class="fas fa-<?php echo $cat['name'] == 'Fashion' ? 'tshirt' : ($cat['name'] == 'Stationery' ? 'pen' : 'futbol'); ?> fa-3x text-primary mb-2"></i>
                                    <h5 class="card-title"><?php echo htmlspecialchars($cat['name']); ?></h5>
                                    <?php if ($subcats->num_rows > 0): ?>
                                        <select class="form-select mb-2" onchange="window.location.href=this.value">
                                            <option value="products.php?category=<?php echo $cat['id']; ?>">All <?php echo htmlspecialchars($cat['name']); ?></option>
                                            <?php while ($subcat = $subcats->fetch_assoc()): ?>
                                                <option value="products.php?category=<?php echo $subcat['id']; ?>"><?php echo htmlspecialchars($subcat['name']); ?></option>
                                            <?php endwhile; ?>
                                        </select>
                                    <?php else: ?>
                                        <a href="products.php?category=<?php echo $cat['id']; ?>" class="btn btn-outline-primary btn-sm">Explore</a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endwhile; ?>
                </div>
                <div class="text-center mt-2">
                    <a href="products.php" class="btn btn-outline-primary btn-sm">View All Categories</a>
                </div>
            </section>

            <!-- Featured Products -->
            <section class="mb-4">
                <h2 class="text-center mb-3">Featured Products</h2>
                <div class="row justify-content-center product-row row-cols-md-3 g-2">
                    <?php
                    // Fetch categories in sort_order
                    $cats = $conn->query("SELECT id FROM categories WHERE parent_id IS NULL ORDER BY sort_order, name");
                    $product_count = 0;
                    while ($cat = $cats->fetch_assoc()) {
                        // Fetch up to 2 products per category
                        $result = $conn->query("SELECT p.*, c.name as category FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE p.category_id = " . $cat['id'] . " ORDER BY p.created_at DESC LIMIT 2");
                        while ($row = $result->fetch_assoc()) {
                            if ($product_count >= 6) break 2; // Stop after 6 products
                    ?>
                            <div class="col">
                                <div class="card product-card">
                                    <?php if ($row['is_flash_sale']): ?>
                                        <span class="flash-sale-badge badge position-absolute top-0 start-0 m-1">Flash Sale</span>
                                    <?php endif; ?>
                                    <img src="<?php echo $row['image'] ?? 'images/moses.png'; ?>" class="card-img-top" alt="<?php echo htmlspecialchars($row['name']); ?>">
                                    <div class="card-body">
                                        <h6 class="card-title"><?php echo htmlspecialchars($row['name']); ?></h6>
                                        <p class="card-text"><?php echo htmlspecialchars(substr($row['description'], 0, 60)); ?>...</p>
                                        <?php if ($row['is_flash_sale']): ?>
                                            <p class="text-decoration-line-through text-muted">KES <?php echo number_format($row['price'] * 1.2, 2); ?></p>
                                            <p class="text-primary fw-bold">KES <?php echo number_format($row['price'], 2); ?> <span class="badge bg-primary">20% OFF</span></p>
                                        <?php else: ?>
                                            <p class="text-primary fw-bold">KES <?php echo number_format($row['price'], 2); ?></p>
                                        <?php endif; ?>
                                        <div class="d-grid">
                                            <a href="product.php?id=<?php echo $row['id']; ?>" class="btn btn-outline-primary btn-sm">View Details</a>
                                            <form method="get" action="cart.php">
                                                <input type="hidden" name="action" value="add">
                                                <input type="hidden" name="product_id" value="<?php echo $row['id']; ?>">
                                                <input type="hidden" name="return_url" value="<?php echo urlencode($_SERVER['REQUEST_URI']); ?>">
                                                <button type="submit" class="btn btn-primary btn-sm">Add to Cart</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                    <?php
                            $product_count++;
                        }
                    }
                    if ($product_count == 0): ?>
                        <p class="text-center">No featured products available at the moment.</p>
                    <?php endif; ?>
                </div>
                <div class="text-center mt-2">
                    <a href="products.php" class="btn btn-outline-primary btn-sm">View All Products</a>
                </div>
            </section>

            <!-- Flash Sales Section -->
            <section class="mb-4 bg-light py-3">
                <h2 class="text-center mb-3"><i class="fas fa-fire text-primary me-2"></i>Flash Sales - Limited Time!</h2>
                <div class="row justify-content-center product-row row-cols-md-3 g-2">
                    <?php
                    // Fetch categories in sort_order
                    $cats = $conn->query("SELECT id FROM categories WHERE parent_id IS NULL ORDER BY sort_order, name");
                    $flash_count = 0;
                    while ($cat = $cats->fetch_assoc()) {
                        // Fetch up to 2 flash sale products per category
                        $flash = $conn->query("SELECT p.*, c.name as category FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE p.is_flash_sale = 1 AND p.category_id = " . $cat['id'] . " ORDER BY p.created_at DESC LIMIT 2");
                        while ($row = $flash->fetch_assoc()) {
                            if ($flash_count >= 4) break 2; // Stop after 4 products
                    ?>
                            <div class="col">
                                <div class="card product-card">
                                    <span class="flash-sale-badge badge position-absolute top-0 start-0 m-1">Flash Sale</span>
                                    <img src="<?php echo $row['image'] ?? 'images/moses.png'; ?>" class="card-img-top" alt="<?php echo htmlspecialchars($row['name']); ?>">
                                    <div class="card-body">
                                        <h6 class="card-title"><?php echo htmlspecialchars($row['name']); ?></h6>
                                        <p class="card-text"><?php echo htmlspecialchars(substr($row['description'], 0, 60)); ?>...</p>
                                        <p class="text-decoration-line-through text-muted">KES <?php echo number_format($row['price'] * 1.2, 2); ?></p>
                                        <p class="text-primary fw-bold">KES <?php echo number_format($row['price'], 2); ?> <span class="badge bg-primary">20% OFF</span></p>
                                        <div class="d-grid">
                                            <a href="product.php?id=<?php echo $row['id']; ?>" class="btn btn-outline-primary btn-sm">View Details</a>
                                            <form method="get" action="cart.php">
                                                <input type="hidden" name="action" value="add">
                                                <input type="hidden" name="product_id" value="<?php echo $row['id']; ?>">
                                                <input type="hidden" name="return_url" value="<?php echo urlencode($_SERVER['REQUEST_URI']); ?>">
                                                <button type="submit" class="btn btn-primary btn-sm">Add to Cart</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                    <?php
                            $flash_count++;
                        }
                    }
                    if ($flash_count == 0): ?>
                        <p class="text-center">No flash sale products available at the moment.</p>
                    <?php endif; ?>
                </div>
                <div class="text-center mt-2">
                    <a href="flash_sales.php" class="btn btn-outline-primary btn-sm">View All Flash Sales</a>
                </div>
            </section>

            <!-- Promotions -->
            <section class="text-center py-3 bg-primary text-white">
                <h3>Big Deals This Week!</h3>
                <p>Up to 50% off on Fashion, Stationery & Sports. Free Shipping on all orders.</p>
                <a href="products.php" class="btn btn-light btn-sm">Shop Deals</a>
            </section>
        </div>
    </div>
</div>

<!-- Chat Box -->
<div class="chat-btn" id="chatBtn">
    <i class="fas fa-comment"></i>
</div>
<div class="chat-box" id="chatBox">
    <div class="chat-header">
        <h5>Customer Support</h5>
        <button class="close-chat" onclick="toggleChatBox()"><i class="fas fa-times"></i></button>
    </div>
    <div class="chat-body" id="chatBody">
        <!-- Messages will be appended here -->
    </div>
    <div class="chat-footer">
        <input type="text" id="chatInput" placeholder="Type your message..." onkeypress="if(event.key === 'Enter') sendMessage()">
        <button onclick="sendMessage()"><i class="fas fa-paper-plane"></i></button>
    </div>
</div>

<script>
    // Get user ID from PHP session or generate guest ID
    const userId = '<?php echo isset($_SESSION['user_id']) ? htmlspecialchars($_SESSION['user_id']) : 'guest_' . mt_rand(100000, 999999); ?>';
    const chatStorageKey = `chatMessages_${userId}`;

    // Chat box functionality
    function toggleChatBox() {
        const chatBox = document.getElementById('chatBox');
        const chatBtn = document.getElementById('chatBtn');
        if (chatBox.style.display === 'flex') {
            chatBox.style.display = 'none';
            chatBtn.innerHTML = '<i class="fas fa-comment"></i>';
        } else {
            chatBox.style.display = 'flex';
            chatBtn.innerHTML = '<i class="fas fa-times"></i>';
            loadMessages();
        }
    }

    function sendMessage() {
        const input = document.getElementById('chatInput');
        const message = input.value.trim();
        if (!message) return;

        appendMessage('user', message);
        saveMessage('user', message);
        input.value = '';

        // Automated response
        setTimeout(() => {
            const response = getBotResponse(message.toLowerCase());
            appendMessage('bot', response);
            saveMessage('bot', response);
        }, 500);
    }

    function appendMessage(sender, text) {
        const chatBody = document.getElementById('chatBody');
        const messageDiv = document.createElement('div');
        messageDiv.className = `chat-message ${sender}`;
        messageDiv.textContent = text;
        chatBody.appendChild(messageDiv);
        chatBody.scrollTop = chatBody.scrollHeight;
    }

    function saveMessage(sender, text) {
        let messages = JSON.parse(sessionStorage.getItem(chatStorageKey) || '[]');
        messages.push({ sender, text, timestamp: new Date().toISOString() });
        sessionStorage.setItem(chatStorageKey, JSON.stringify(messages));
    }

    function loadMessages() {
        const chatBody = document.getElementById('chatBody');
        chatBody.innerHTML = '';
        let messages = JSON.parse(sessionStorage.getItem(chatStorageKey) || '[]');
        messages.forEach(msg => appendMessage(msg.sender, msg.text));
    }

    function getBotResponse(message) {
        if (message.includes('track') || message.includes('order status')) {
            return 'Please provide your order number, and we’ll check the status for you!';
        } else if (message.includes('return') || message.includes('refund')) {
            return 'You can return eligible items within 7 days. Please visit our Returns Policy page for details or provide your order number to start a return.';
        } else if (message.includes('contact') || message.includes('support')) {
            return 'Reach us at mautimasea14@gmail.com or call +254 746 071 550. How else can we assist you?';
        } else if (message.includes('delivery') || message.includes('shipping')) {
            return 'Delivery times vary by location. Please provide your order number or check our Terms and Conditions page for shipping details.';
        } else {
            return 'I’m here to help! Try asking about order tracking, returns, or contact details.';
        }
    }

    // Initialize chat
    document.getElementById('chatBtn').addEventListener('click', toggleChatBox);
</script>

<?php include_once 'footer.php'; ?>