<?php
/* sidebar.php - theme-aware sidebar (matches kit markup)
   - expects ui_sidebar_menu (optional) else falls back to demo menu
*/
if(session_status()===PHP_SESSION_NONE)session_start();
require_once __DIR__.'/config.php';
$BASE = defined('BASE_URL')?BASE_URL:'/';
$theme_mode = $_SESSION['theme_mode'] ?? 'light';

// fetch sidebar rows if table exists
$menu_rows = [];
if(isset($conn)){
    $q = "SELECT * FROM ui_sidebar_menu WHERE is_active=1 ORDER BY sort_order ASC";
    if($res=@mysqli_query($conn,$q)){
        while($r=@mysqli_fetch_assoc($res))$menu_rows[]=$r;
    }
}
// fallback demo menu (simple)
if(empty($menu_rows)){
    $menu_rows = [
        ['group_label'=>'Main Menu','label'=>'Home','href'=>$BASE.'xhtml/index.html','icon_url_light'=>'xhtml/assets/images/icon/home.svg','icon_url_dark'=>'xhtml/assets/images/icon/home-dark.svg','subtitle'=>''],
        ['group_label'=>'Main Menu','label'=>'Pages','href'=>$BASE.'xhtml/pages.html','icon_url_light'=>'xhtml/assets/images/icon/pages.svg','icon_url_dark'=>'xhtml/assets/images/icon/pages-dark.svg','subtitle'=>''],
        ['group_label'=>'Main Menu','label'=>'UI Components','href'=>$BASE.'xhtml/ui-components.html','icon_url_light'=>'xhtml/assets/images/icon/ui.svg','icon_url_dark'=>'xhtml/assets/images/icon/ui-dark.svg','subtitle'=>''],
    ];
}

// render grouped list
?>
<aside class="sidebar">
  <div class="author-box">
    <div class="dz-media"><img src="<?php echo htmlspecialchars($BASE.'xhtml/assets/images/stories/small/pic1.jpg'); ?>" alt="author-image"></div>
    <div class="dz-info"><span>Good Morning</span><h5 class="name">User</h5></div>
  </div>
  <ul class="nav navbar-nav">
<?php
$curGroup = null;
foreach($menu_rows as $m){
  $g = $m['group_label'] ?? 'Menu';
  if($g!==$curGroup){ echo ($curGroup!==null?"</ul></li>":"").'<li class="nav-label">'.htmlspecialchars($g).'</li>'; echo "<li>"; echo "<ul class='sub-menu'>"; $curGroup=$g; }
  $href = $m['href'] ?? '#';
  $icon = ($theme_mode==='dark') ? ($m['icon_url_dark'] ?? $m['icon_url_light'] ?? '') : ($m['icon_url_light'] ?? '');
  // normalize icon path
  if($icon && !preg_match('@^(https?://|/)@',$icon)) $icon = $BASE . ltrim($icon,'/');
  echo '<li><a class="nav-link" href="'.htmlspecialchars($href).'"><span class="dz-icon">';
  if($icon) echo '<img src="'.htmlspecialchars($icon).'" alt="" style="height:20px;vertical-align:middle">';
  echo '</span><span>'.htmlspecialchars($m['label'] ?? 'Item').'</span></a></li>';
}
if($curGroup!==null) echo "</ul></li>";
?>
  </ul>
</aside>
