<?php
/**
 * ============================================================
 * CATEGORY MANAGER - Sistem Complet de Gestiune Categorii
 * ============================================================
 * Versiune: 1.0
 * Data: 2025-11-30
 * Descriere: Clasa pentru gestionarea categoriilor cu mega-menu dinamic
 * ============================================================
 */

require_once __DIR__ . '/Database.php';

class CategoryManager {
    private $db;
    private static $instance = null;
    
    /**
     * Constructor - Singleton pattern
     */
    private function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Get instance (Singleton)
     */
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Get a single category setting
     */
    public function getSetting($key, $default = null) {
        $setting = $this->db->fetchOne(
            "SELECT setting_value FROM category_settings WHERE setting_key = ?",
            [$key]
        );
        
        return $setting ? $setting['setting_value'] : $default;
    }
    
    /**
     * Get all root categories (parent_id IS NULL)
     */
    public function getRootCategories() {
        return $this->db->fetchAll(
            "SELECT * FROM categories 
             WHERE parent_id IS NULL 
             AND is_active = 1 
             AND show_in_menu = 1 
             ORDER BY position ASC"
        );
    }
    
    /**
     * Get subcategories for a parent category
     */
    public function getSubcategories($parentId) {
        return $this->db->fetchAll(
            "SELECT * FROM categories 
             WHERE parent_id = ? 
             AND is_active = 1 
             ORDER BY position ASC",
            [$parentId]
        );
    }
    
    /**
     * Get promo card for a category
     */
    public function getPromoCard($categoryId) {
        return $this->db->fetchOne(
            "SELECT * FROM category_promo_cards 
             WHERE category_id = ? 
             AND is_active = 1 
             ORDER BY position ASC 
             LIMIT 1",
            [$categoryId]
        );
    }
    
    /**
     * Get category by slug
     */
    public function getCategoryBySlug($slug) {
        return $this->db->fetchOne(
            "SELECT * FROM categories WHERE slug = ? AND is_active = 1",
            [$slug]
        );
    }
    
    /**
     * Get category by ID
     */
    public function getCategoryById($id) {
        return $this->db->fetchOne(
            "SELECT * FROM categories WHERE id = ?",
            [$id]
        );
    }
    
    /**
     * Get breadcrumbs for a category
     */
    public function getCategoryBreadcrumbs($categoryId) {
        $breadcrumbs = [];
        $currentId = $categoryId;
        
        while ($currentId) {
            $category = $this->getCategoryById($currentId);
            if (!$category) {
                break;
            }
            
            array_unshift($breadcrumbs, $category);
            $currentId = $category['parent_id'];
        }
        
        return $breadcrumbs;
    }
    
    /**
     * Build complete category tree
     */
    public function buildCategoryTree($parentId = null) {
        if ($parentId === null) {
            $categories = $this->getRootCategories();
        } else {
            $categories = $this->getSubcategories($parentId);
        }
        
        $tree = [];
        foreach ($categories as $category) {
            $category['children'] = $this->buildCategoryTree($category['id']);
            $tree[] = $category;
        }
        
        return $tree;
    }
    
    /**
     * Render promo card HTML
     */
    public function renderPromoCard($card) {
        if (!$card) {
            return '';
        }
        
        $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 ' . htmlspecialchars($card['bg_color']) . ' rounded-5 py-4 px-3">';
        $html .= '    <div class="text-center px-2">';
        
        // Icon (optional)
        if (!empty($card['icon'])) {
            $html .= '      <i class="' . htmlspecialchars($card['icon']) . ' fs-2 text-dark-emphasis mb-3"></i>';
        }
        
        // Badge (optional)
        if (!empty($card['badge_text'])) {
            $badgeColor = htmlspecialchars($card['badge_bg_color']);
            $html .= '      <span class="badge bg-' . $badgeColor . ' bg-opacity-10 text-' . $badgeColor . ' fs-sm rounded-pill mb-2">' . htmlspecialchars($card['badge_text']) . '</span>';
        }
        
        // Subtitle or description
        if (!empty($card['subtitle'])) {
            $html .= '      <div class="fs-sm text-light-emphasis mb-2">' . htmlspecialchars($card['subtitle']) . '</div>';
        } elseif (!empty($card['description'])) {
            $html .= '      <div class="fs-sm text-light-emphasis mb-2">' . htmlspecialchars($card['description']) . '</div>';
        }
        
        // Price (optional)
        if (!empty($card['price_original']) || !empty($card['price_sale'])) {
            $html .= '      <div class="fs-sm text-light-emphasis mb-2">';
            if (!empty($card['price_label'])) {
                $html .= htmlspecialchars($card['price_label']) . ' ';
            }
            if (!empty($card['price_original'])) {
                $html .= '<del>' . number_format($card['price_original'], 2) . ' RON</del> ';
            }
            if (!empty($card['price_sale'])) {
                $html .= number_format($card['price_sale'], 2) . ' RON';
            }
            $html .= '      </div>';
        }
        
        // Title
        $html .= '      <div class="h2 mb-4">' . htmlspecialchars($card['title']) . '</div>';
        $html .= '    </div>';
        
        // Image
        $imageAlt = !empty($card['image_alt']) ? htmlspecialchars($card['image_alt']) : htmlspecialchars($card['title']);
        $html .= '    <img src="' . htmlspecialchars($card['image_url']) . '" width="252" alt="' . $imageAlt . '">';
        
        // Button CTA
        $html .= '    <div class="text-center mt-4">';
        $html .= '      <a class="btn btn-sm btn-primary stretched-link" href="' . htmlspecialchars($card['button_url']) . '">' . htmlspecialchars($card['button_text']) . '</a>';
        $html .= '    </div>';
        $html .= '  </div>';
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * Render category item (nivel 2)
     */
    private function renderCategoryItem($item) {
        $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="' . htmlspecialchars($item['url']) . '">';
        $html .= htmlspecialchars($item['name']);
        $html .= '  </a>';
        $html .= '</li>';
        
        return $html;
    }
    
    /**
     * Render subcategory column
     */
    private function renderSubcategoryColumn($subcategory) {
        $items = $this->getSubcategories($subcategory['id']);
        
        $html = '<div style="min-width: 194px">';
        $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="' . htmlspecialchars($subcategory['url']) . '">';
        $html .= htmlspecialchars($subcategory['name']);
        $html .= '    </a>';
        $html .= '  </div>';
        
        if (!empty($items)) {
            $html .= '  <ul class="nav flex-column gap-2 mt-n2">';
            foreach ($items as $item) {
                $html .= $this->renderCategoryItem($item);
            }
            $html .= '  </ul>';
        }
        
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * Render mega menu content for a category
     */
    private function renderMegaMenuContent($category) {
        $subcategories = $this->getSubcategories($category['id']);
        $promoCard = $this->getPromoCard($category['id']);
        
        if (empty($subcategories) && !$promoCard) {
            return '';
        }
        
        $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">';
        
        // Calculate available height dynamically based on root categories count
        $rootCategories = $this->getRootCategories();
        $rootCategoryCount = count($rootCategories);
        $baseMinHeight = floatval($this->getSetting('min_menu_height', '561.33'));
        
        // Calculate actual menu height
        if ($rootCategoryCount > 12) {
            $heightPerCategory = $baseMinHeight / 12;
            $actualMenuHeight = $rootCategoryCount * $heightPerCategory;
        } else {
            $actualMenuHeight = $baseMinHeight;
        }
        
        // Subtract only dropdown menu padding: 32px (p-4 = 1rem top + 1rem bottom)
        // This gives us the actual content area height
        $availableHeight = $actualMenuHeight - 32;
        
        // Height calculations per item type (more accurate measurements):
        // - Subcategory header (nivel 1): ~32px (h6 + line-height)
        // - Item (nivel 2): ~28px (nav-link with gap-2)
        // - Spacing between subcategories: ~8px (pt-2)
        $headerHeight = 32;
        $itemHeight = 28;
        $spacingHeight = 8;
        
        // Build a flat list of all elements with their individual data
        $allElements = [];
        foreach ($subcategories as $index => $subcategory) {
            $items = $this->getSubcategories($subcategory['id']);
            
            // Add subcategory header
            $allElements[] = [
                'type' => 'header',
                'subcategory' => $subcategory,
                'height' => $headerHeight + ($index > 0 ? $spacingHeight : 0),
                'needsSpacing' => ($index > 0)
            ];
            
            // Add all items under this subcategory
            foreach ($items as $item) {
                $allElements[] = [
                    'type' => 'item',
                    'item' => $item,
                    'parent_subcategory' => $subcategory,
                    'height' => $itemHeight,
                    'needsSpacing' => false
                ];
            }
        }
        
        // Distribute elements into columns
        $columns = [];
        $currentColumn = [];
        $currentHeight = 0;
        
        foreach ($allElements as $element) {
            // Check if we need to start a new column
            if ($currentHeight > 0 && ($currentHeight + $element['height']) > $availableHeight) {
                $columns[] = $currentColumn;
                $currentColumn = [];
                $currentHeight = 0;
                
                // Reset spacing for first item in new column
                $element['needsSpacing'] = false;
            }
            
            $currentColumn[] = $element;
            $currentHeight += $element['height'];
        }
        
        // Add remaining items to last column
        if (!empty($currentColumn)) {
            $columns[] = $currentColumn;
        }
        
        // Render columns
        foreach ($columns as $column) {
            $html .= '<div style="min-width: 194px">';
            $inList = false;
            
            foreach ($column as $element) {
                if ($element['type'] === 'header') {
                    // Close previous list if open
                    if ($inList) {
                        $html .= '</ul>';
                        $inList = false;
                    }
                    
                    $spacingClass = $element['needsSpacing'] ? ' pt-2' : '';
                    
                    // Subcategory header (nivel 1)
                    $html .= '<div class="d-flex w-100' . $spacingClass . '">';
                    $html .= '  <a class="animate-underline animate-target d-inline h6 text-dark-emphasis text-decoration-none text-truncate" href="' . htmlspecialchars($element['subcategory']['url']) . '">';
                    $html .= htmlspecialchars($element['subcategory']['name']);
                    $html .= '  </a>';
                    $html .= '</div>';
                    
                    // Start list for items
                    $html .= '<ul class="nav flex-column gap-2 mt-n2">';
                    $inList = true;
                    
                } elseif ($element['type'] === 'item') {
                    // Start list if not already started
                    if (!$inList) {
                        $html .= '<ul class="nav flex-column gap-2 mt-n2">';
                        $inList = true;
                    }
                    
                    // Render item
                    $html .= $this->renderCategoryItem($element['item']);
                }
            }
            
            // Close any open list
            if ($inList) {
                $html .= '</ul>';
            }
            
            $html .= '</div>'; // Close column
        }
        
        // Render promo card (if exists)
        if ($promoCard) {
            $html .= $this->renderPromoCard($promoCard);
        }
        
        $html .= '  </div>';
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * Render single category menu item
     */
    private function renderCategoryMenuItem($category, $isFirst = false) {
        $hasMegamenu = !empty($category['has_megamenu']);
        
        $html = '<li class="dropend position-static">';
        
        // Trigger div
        $topPadding = $isFirst ? 'pt-2 ' : '';
        $bottomPadding = 'pb-1 ';
        
        $html .= '  <div class="position-relative rounded ' . $topPadding . $bottomPadding . 'px-lg-2" tabindex="0" 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="' . htmlspecialchars($category['url']) . '">';
        if (!empty($category['icon'])) {
            $html .= '      <i class="' . htmlspecialchars($category['icon']) . ' fs-xl opacity-60 pe-1 me-2"></i>';
        }
        $html .= '      <span class="text-truncate">' . htmlspecialchars($category['name']) . '</span>';
        $html .= '      <i class="ci-chevron-right fs-base ms-auto me-n1"></i>';
        $html .= '    </a>';
        
        // Mobile div
        $html .= '    <div class="dropdown-item fw-medium stretched-link d-lg-none">';
        if (!empty($category['icon'])) {
            $html .= '      <i class="' . htmlspecialchars($category['icon']) . ' fs-xl opacity-60 pe-1 me-2"></i>';
        }
        $html .= htmlspecialchars($category['name']);
        $html .= '      <i class="ci-chevron-down fs-base ms-auto me-n1"></i>';
        $html .= '    </div>';
        $html .= '  </div>';
        
        // Mega menu content
        if ($hasMegamenu) {
            $html .= $this->renderMegaMenuContent($category);
        }
        
        $html .= '</li>';
        
        return $html;
    }
    
    /**
     * Render complete categories menu
     * @param bool $isHomePage - Add dropdown-menu-static class for homepage
     */
    public function renderCategoriesMenu($isHomePage = false) {
        $categories = $this->getRootCategories();
        
        if (empty($categories)) {
            return '<!-- No active categories -->';
        }
        
        // Check setting from database (can override parameter)
        $staticMenuSetting = $this->getSetting('homepage_static_menu', '1');
        $useStaticMenu = $isHomePage && ($staticMenuSetting == '1');
        
        $staticClass = $useStaticMenu ? 'dropdown-menu-static ' : '';
        
        // Calculate minimum height dynamically based on number of root categories
        $rootCategoryCount = count($categories);
        $baseMinHeight = floatval($this->getSetting('min_menu_height', '561.33'));
        
        // If we have more than 12 categories, calculate proportionally
        if ($rootCategoryCount > 12) {
            // Each category takes 561.33 / 12 = ~46.78px
            $heightPerCategory = $baseMinHeight / 12;
            $calculatedHeight = $rootCategoryCount * $heightPerCategory;
            $minHeightValue = $calculatedHeight;
        } else {
            // Use base min height for 12 or fewer categories
            $minHeightValue = $baseMinHeight;
        }
        
        $minHeight = 'min-height: ' . round($minHeightValue, 2) . 'px;';
        
        $html = '<ul class="dropdown-menu ' . $staticClass . 'w-100 rounded-top-0 rounded-bottom-4 py-1 p-lg-1" style="' . $minHeight . ' --cz-dropdown-spacer: 0; --cz-dropdown-item-padding-y: .625rem; --cz-dropdown-item-spacer: 0">';
        
        // "All Categories" link for mobile
        $showMobileAllCategories = $this->getSetting('show_mobile_all_categories', '1');
        if ($showMobileAllCategories == '1') {
            $html .= '  <li class="d-lg-none pt-2">';
            $html .= '    <a class="dropdown-item fw-medium" href="/shop-categories-electronics.php">';
            $html .= '      <i class="ci-grid fs-xl opacity-60 pe-1 me-2"></i>';
            $html .= '      Toate categoriile';
            $html .= '      <i class="ci-chevron-right fs-base ms-auto me-n1"></i>';
            $html .= '    </a>';
            $html .= '  </li>';
        }
        
        // Render categories
        $isFirst = true;
        foreach ($categories as $category) {
            $html .= $this->renderCategoryMenuItem($category, $isFirst);
            $isFirst = false;
        }
        
        $html .= '</ul>';
        
        return $html;
    }
}

/**
 * Helper function for backward compatibility
 * Only declare if not already defined (to avoid conflicts)
 */
if (!function_exists('renderCategoryMegaMenu')) {
    function renderCategoryMegaMenu($isHomePage = false) {
        $categoryManager = CategoryManager::getInstance();
        return $categoryManager->renderCategoriesMenu($isHomePage);
    }
}
?>

