<?php
/**
 * Category Menu Helper
 * Generates the exact HTML structure for the categories mega menu
 * Based on Cartzilla/home-electronics.html - 100% markup preservation
 * 
 * UPDATED: Now supports both old system (products table) and new categories system
 */

require_once __DIR__ . '/Product.php';
require_once __DIR__ . '/B2B.php';
require_once __DIR__ . '/Database.php';
require_once __DIR__ . '/CategoryManager.php';

// Check if new categories system is available
$db = Database::getInstance();
$newSystemAvailable = false;
try {
    $result = $db->fetchOne("SHOW TABLES LIKE 'categories'");
    $newSystemAvailable = !empty($result);
} catch (Exception $e) {
    $newSystemAvailable = false;
}

/**
 * Map category names to Cartzilla icons
 */
function getCategoryIcon($categoryName) {
    $iconMap = [
        'Computers & Accessories' => 'ci-computer',
        'Computers' => 'ci-computer',
        'Smartphones & Tablets' => 'ci-smartphone-2',
        'Smartphones' => 'ci-smartphone-2',
        'TV, Video & Audio' => 'ci-monitor-2',
        'TV' => 'ci-monitor-2',
        'Speakers & Home Music' => 'ci-speaker-2',
        'Speakers' => 'ci-speaker-2',
        'Cameras, Photo & Video' => 'ci-camera-2',
        'Cameras' => 'ci-camera-2',
        'Printers & Ink' => 'ci-printer-2',
        'Printers' => 'ci-printer-2',
        'Charging Stations' => 'ci-battery-2',
        'Headphones' => 'ci-headphones-2',
        'Wearable Electronics' => 'ci-watch-2',
        'Powerbanks' => 'ci-powerbank',
        'HDD/SSD Data Storage' => 'ci-hard-drive-2',
        'Data Storage' => 'ci-hard-drive-2',
        'Video Games' => 'ci-game',
    ];
    
    // Try exact match first
    if (isset($iconMap[$categoryName])) {
        return $iconMap[$categoryName];
    }
    
    // Try partial match
    foreach ($iconMap as $key => $icon) {
        if (stripos($categoryName, $key) !== false || stripos($key, $categoryName) !== false) {
            return $icon;
        }
    }
    
    // Default icon
    return 'ci-grid';
}

/**
 * Get featured product for category banner
 * Priority: 1. banner_product_id from category, 2. product with sale_price, 3. first product
 */
function getCategoryBannerProduct($categoryId, $productObj) {
    $db = Database::getInstance();
    
    // First, check if category has a specific banner_product_id set
    $category = $db->fetchOne(
        "SELECT banner_product_id, banner_image FROM categories WHERE id = ?",
        [$categoryId]
    );
    
    if ($category && !empty($category['banner_product_id'])) {
        $product = $db->fetchOne(
            "SELECT p.*, c.name as category_name, c.slug as category_slug
             FROM products p
             LEFT JOIN categories c ON p.category_id = c.id
             WHERE p.id = ? AND p.is_active = 1",
            [$category['banner_product_id']]
        );
        if ($product) {
            return $product;
        }
    }
    
    // Try to get product with sale_price
    $product = $db->fetchOne(
        "SELECT p.*, c.name as category_name, c.slug as category_slug
         FROM products p
         LEFT JOIN categories c ON p.category_id = c.id
         WHERE p.category_id = ? AND p.is_active = 1 AND p.sale_price IS NOT NULL AND p.sale_price < p.price
         ORDER BY (p.price - p.sale_price) DESC, p.created_at DESC
         LIMIT 1",
        [$categoryId]
    );
    
    // If no sale product, get first product from category
    if (!$product) {
        $product = $db->fetchOne(
            "SELECT p.*, c.name as category_name, c.slug as category_slug
             FROM products p
             LEFT JOIN categories c ON p.category_id = c.id
             WHERE p.category_id = ? AND p.is_active = 1
             ORDER BY p.created_at DESC
             LIMIT 1",
            [$categoryId]
        );
    }
    
    return $product;
}

/**
 * Render category mega menu
 * @param bool $isHomePage - If true, adds 'dropdown-menu-static' class (only on index/home)
 */
function renderCategoryMegaMenu($isHomePage = false) {
    global $newSystemAvailable;
    
    // Use new categories system if available
    if ($newSystemAvailable) {
        $categoryManager = CategoryManager::getInstance();
        return $categoryManager->renderCategoriesMenu($isHomePage);
    }
    
    // Fallback to old system
    $productObj = new Product();
    $b2b = new B2B();
    
    // Get main categories (parent_id IS NULL)
    $mainCategories = $productObj->getCategories(null);
    
    // Build static class string
    $staticClass = $isHomePage ? 'dropdown-menu-static' : '';
    
    // Start menu HTML
    $html = '<ul class="dropdown-menu ' . $staticClass . ' w-100 rounded-top-0 rounded-bottom-4 py-1 p-lg-1" style="--cz-dropdown-spacer: 0; --cz-dropdown-item-padding-y: .625rem; --cz-dropdown-item-spacer: 0">';
    
    // "All Categories" link (mobile only)
    $html .= '<li class="d-lg-none pt-2">
      <a class="dropdown-item fw-medium" href="/categorii">
        <i class="ci-grid fs-xl opacity-60 pe-1 me-2"></i>
        Toate categoriile
        <i class="ci-chevron-right fs-base ms-auto me-n1"></i>
      </a>
    </li>';
    
    // Render each main category
    foreach ($mainCategories as $mainCategory) {
        if (!$mainCategory['is_active']) {
            continue;
        }
        
        // Get subcategories
        $subcategories = $productObj->getCategories($mainCategory['id']);
        
        // Get banner product for this category
        $bannerProduct = getCategoryBannerProduct($mainCategory['id'], $productObj);
        
        // Get icon
        $icon = getCategoryIcon($mainCategory['name']);
        
        // Category slug for links
        $categorySlug = htmlspecialchars($mainCategory['slug']);
        $categoryName = htmlspecialchars($mainCategory['name']);
        
        // Start category item
        $html .= '<li class="dropend position-static">';
        $html .= '<div class="position-relative rounded pt-2 pb-1 px-lg-2" data-bs-toggle="dropdown" data-bs-trigger="hover">';
        
        // Desktop link
        $html .= '<a class="dropdown-item fw-medium stretched-link d-none d-lg-flex" href="/catalog/' . $categorySlug . '">';
        $html .= '<i class="' . $icon . ' fs-xl opacity-60 pe-1 me-2"></i>';
        $html .= '<span class="text-truncate">' . $categoryName . '</span>';
        $html .= '<i class="ci-chevron-right fs-base ms-auto me-n1"></i>';
        $html .= '</a>';
        
        // Mobile link
        $html .= '<div class="dropdown-item fw-medium text-wrap stretched-link d-lg-none">';
        $html .= '<i class="' . $icon . ' fs-xl opacity-60 pe-1 me-2"></i>';
        $html .= $categoryName;
        $html .= '<i class="ci-chevron-down fs-base ms-auto me-n1"></i>';
        $html .= '</div>';
        
        $html .= '</div>';
        
        // Dropdown menu with subcategories
        $html .= '<div class="dropdown-menu rounded-4 p-4" style="top: 1rem; height: calc(100% - .1875rem); --cz-dropdown-spacer: .3125rem; animation: none;">';
        $html .= '<div class="d-flex flex-column flex-lg-row h-100 gap-4">';
        
        // Group subcategories into columns (max 2-3 columns)
        $subcatColumns = [];
        $currentColumn = [];
        $itemsPerColumn = max(7, ceil(count($subcategories) / 2));
        
        foreach ($subcategories as $index => $subcat) {
            if (!$subcat['is_active']) {
                continue;
            }
            $currentColumn[] = $subcat;
            if (count($currentColumn) >= $itemsPerColumn && count($subcatColumns) < 2) {
                $subcatColumns[] = $currentColumn;
                $currentColumn = [];
            }
        }
        if (!empty($currentColumn)) {
            $subcatColumns[] = $currentColumn;
        }
        
        // If no subcategories, create a single column with link to category
        if (empty($subcatColumns)) {
            $subcatColumns[] = [];
        }
        
        // Render subcategory columns
        foreach ($subcatColumns as $colIndex => $column) {
            $html .= '<div style="min-width: 194px">';
            
            // If first column and has subcategories, show category name as header
            if ($colIndex === 0 && !empty($column)) {
                $html .= '<div class="d-flex w-100">';
                $html .= '<a class="animate-underline animate-target d-inline h6 text-dark-emphasis text-decoration-none text-truncate" href="/catalog/' . $categorySlug . '">' . $categoryName . '</a>';
                $html .= '</div>';
            }
            
            // Subcategories list
            $html .= '<ul class="nav flex-column gap-2 mt-n2">';
            foreach ($column as $subcat) {
                $subcatSlug = htmlspecialchars($subcat['slug']);
                $subcatName = htmlspecialchars($subcat['name']);
                $html .= '<li class="d-flex w-100 pt-1">';
                $html .= '<a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="/catalog/' . $subcatSlug . '">' . $subcatName . '</a>';
                $html .= '</li>';
            }
            $html .= '</ul>';
            $html .= '</div>';
        }
        
        // Banner promotional (desktop only)
        // Check if category has banner_image set
        $db = Database::getInstance();
        $categoryBannerImage = null;
        $categoryData = $db->fetchOne("SELECT banner_image FROM categories WHERE id = ?", [$mainCategory['id']]);
        if ($categoryData && !empty($categoryData['banner_image'])) {
            $categoryBannerImage = $categoryData['banner_image'];
        }
        
        if ($bannerProduct || $categoryBannerImage) {
            if ($bannerProduct) {
                $bannerPrice = $bannerProduct['sale_price'] ?? $bannerProduct['price'];
                $bannerOldPrice = ($bannerProduct['sale_price'] && $bannerProduct['sale_price'] < $bannerProduct['price']) ? $bannerProduct['price'] : null;
                $discount = $bannerOldPrice ? round((($bannerOldPrice - $bannerPrice) / $bannerOldPrice) * 100) : 0;
                $bannerImage = $categoryBannerImage ?: ($bannerProduct['image'] ?? '/assets/img/mega-menu/electronics/01.png');
                if (!str_starts_with($bannerImage, 'http') && !str_starts_with($bannerImage, '/')) {
                    if (str_starts_with($bannerImage, 'assets/')) {
                        $bannerImage = '/' . $bannerImage;
                    } else {
                        $bannerImage = '/assets/img/shop/electronics/' . $bannerImage;
                    }
                }
                $bannerSlug = htmlspecialchars($bannerProduct['slug']);
                $bannerName = htmlspecialchars($bannerProduct['name']);
            } else {
                // Use category banner image without product
                $bannerImage = $categoryBannerImage;
                if (!str_starts_with($bannerImage, 'http') && !str_starts_with($bannerImage, '/')) {
                    if (str_starts_with($bannerImage, 'assets/')) {
                        $bannerImage = '/' . $bannerImage;
                    } else {
                        $bannerImage = '/assets/img/mega-menu/electronics/' . $bannerImage;
                    }
                }
                $bannerSlug = $categorySlug;
                $bannerName = $categoryName;
                $bannerPrice = null;
                $bannerOldPrice = null;
                $discount = 0;
            }
            
            $html .= '<div class="d-none d-lg-block">';
            $html .= '<div class="d-none d-xl-block" style="width: 284px"></div>';
            $html .= '<div class="d-xl-none" style="width: 240px"></div>';
            $html .= '<div class="position-relative d-flex flex-column justify-content-center h-100 bg-body-secondary rounded-5 py-4 px-3">';
            $html .= '<div class="text-center px-2">';
            if ($bannerProduct) {
                if ($discount > 0) {
                    $html .= '<span class="badge bg-danger bg-opacity-10 text-danger fs-sm rounded-pill mb-2">Economisește până la ' . number_format($discount, 0) . '%</span>';
                }
                if ($bannerOldPrice) {
                    $html .= '<div class="fs-sm text-light-emphasis mb-2">De la <del>' . number_format($bannerOldPrice, 2) . ' RON</del> ' . number_format($bannerPrice, 2) . ' RON</div>';
                } elseif ($bannerPrice) {
                    $html .= '<div class="fs-sm text-light-emphasis mb-2">De la ' . number_format($bannerPrice, 2) . ' RON</div>';
                }
            }
            $html .= '<div class="h2 mb-4">' . $bannerName . '</div>';
            $html .= '</div>';
            $html .= '<img src="' . htmlspecialchars($bannerImage) . '" width="252" alt="' . $bannerName . '">';
            $html .= '<div class="text-center mt-4">';
            if ($bannerProduct) {
                $html .= '<a class="btn btn-sm btn-primary stretched-link" href="/produs/' . $bannerSlug . '">Cumpără acum</a>';
            } else {
                $html .= '<a class="btn btn-sm btn-primary stretched-link" href="/catalog/' . $bannerSlug . '">Vezi produse</a>';
            }
            $html .= '</div>';
            $html .= '</div>';
            $html .= '</div>';
        } else {
            // Fallback banner if no product
            $html .= '<div class="d-none d-lg-block">';
            $html .= '<div class="d-none d-xl-block" style="width: 284px"></div>';
            $html .= '<div class="d-xl-none" style="width: 240px"></div>';
            $html .= '<div class="position-relative d-flex flex-column justify-content-center h-100 bg-body-secondary rounded-5 py-4 px-3">';
            $html .= '<div class="text-center px-2">';
            $html .= '<div class="h2 mb-4">' . $categoryName . '</div>';
            $html .= '</div>';
            $html .= '<div class="text-center mt-4">';
            $html .= '<a class="btn btn-sm btn-primary stretched-link" href="/catalog/' . $categorySlug . '">Vezi produse</a>';
            $html .= '</div>';
            $html .= '</div>';
            $html .= '</div>';
        }
        
        $html .= '</div>'; // End dropdown-menu inner div
        $html .= '</div>'; // End dropdown-menu
        $html .= '</li>'; // End category item
    }
    
    $html .= '</ul>'; // End main menu
    
    return $html;
}
?>

