<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token-name" content="<?= csrf_token() ?>">
<meta name="csrf-token-value" content="<?= csrf_hash() ?>">
<title><?= $title ?? 'FM ERP' ?> — <?= esc($settings['company_name'] ?? 'FM ERP') ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700;1,9..40,400&display=swap" rel="stylesheet">
<?php
// Dynamic brand colors from settings
$primaryColor   = $settings['primary_color']   ?? '#76002b';
$secondaryColor = $settings['secondary_color'] ?? '#c7ba9a';
// Derive hover (darkened ~15%)
function _hexDarken(string $hex, int $pct = 15): string {
    $hex = ltrim($hex,'#');
    if(strlen($hex)===3) $hex=$hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
    [$r,$g,$b] = [hexdec(substr($hex,0,2)),hexdec(substr($hex,2,2)),hexdec(substr($hex,4,2))];
    $factor = 1 - $pct/100;
    return sprintf('#%02x%02x%02x', max(0,(int)($r*$factor)), max(0,(int)($g*$factor)), max(0,(int)($b*$factor)));
}
$primaryHover   = _hexDarken($primaryColor, 15);
$secondaryHover = _hexDarken($secondaryColor, 15);
// RGB values for rgba() usage
function _hexToRgb(string $hex): string {
    $hex = ltrim($hex,'#');
    if(strlen($hex)===3) $hex=$hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
    return hexdec(substr($hex,0,2)).','.hexdec(substr($hex,2,2)).','.hexdec(substr($hex,4,2));
}
$primaryRgb   = _hexToRgb($primaryColor);
$secondaryRgb = _hexToRgb($secondaryColor);
?>
<style>
:root{
  --fm-primary:<?= $primaryColor ?>;
  --fm-primary-hover:<?= $primaryHover ?>;
  --fm-secondary:<?= $secondaryColor ?>;
  --fm-secondary-hover:<?= $secondaryHover ?>;
  /* Legacy aliases kept for backward compat */
  --fm-navy:<?= $primaryColor ?>;
  --fm-blue:#1565c0;
  --fm-teal:#00897b;
  --fm-green:#2e7d32;
  --fm-orange:#e65100;
  --fm-red:#c62828;
  --fm-gold:<?= $secondaryColor ?>;
  --fm-light:#f5f0ee;
  --fm-sidebar:224px;
  --fm-sidebar-collapsed:64px
}
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'DM Sans',system-ui,sans-serif;background:var(--fm-light);color:#1a2332;min-height:100vh;display:flex}
/* SIDEBAR */
.sidebar{width:var(--fm-sidebar);height:100vh;background:linear-gradient(180deg,<?= $primaryColor ?> 0%,<?= $primaryHover ?> 60%,<?= _hexDarken($primaryColor,30) ?> 100%);display:flex;flex-direction:column;position:fixed;top:0;left:0;z-index:1000;transition:.3s;overflow:hidden}
.sidebar-brand{padding:18px 20px 12px;border-bottom:1px solid rgba(255,255,255,.15);flex-shrink:0}
.sidebar-brand .brand-logo{max-height:40px;max-width:140px;object-fit:contain;margin-bottom:6px;display:block}
.sidebar-brand .brand-title{color:#fff;font-size:.95rem;font-weight:700;letter-spacing:.3px;line-height:1.2}
.sidebar-brand .brand-sub{color:rgba(255,255,255,.55);font-size:.62rem;text-transform:uppercase;letter-spacing:1px;margin-top:2px}
.sidebar-nav{flex:1;overflow-y:auto;padding:8px 0;min-height:0}
.sidebar-nav::-webkit-scrollbar{width:4px}
.sidebar-nav::-webkit-scrollbar-track{background:transparent}
.sidebar-nav::-webkit-scrollbar-thumb{background:rgba(255,255,255,.2);border-radius:4px}
.sidebar-nav::-webkit-scrollbar-thumb:hover{background:rgba(255,255,255,.35)}
.nav-section-label{color:rgba(255,255,255,.35);font-size:.6rem;font-weight:700;text-transform:uppercase;letter-spacing:1.5px;padding:12px 20px 4px}
.nav-link-item{display:flex;align-items:center;gap:10px;padding:9px 20px;color:rgba(255,255,255,.75);text-decoration:none;font-size:.82rem;font-weight:500;transition:.2s;border-left:3px solid transparent;white-space:nowrap}
.nav-link-item:hover{color:#fff;background:rgba(255,255,255,.1);border-left-color:rgba(255,255,255,.3)}
.nav-link-item.active{color:#fff;background:rgba(255,255,255,.15);border-left-color:var(--fm-secondary);font-weight:600}
.nav-link-item i{font-size:1rem;width:20px;text-align:center;flex-shrink:0}
.sidebar-footer{padding:12px 16px;border-top:1px solid rgba(255,255,255,.1);flex-shrink:0}
/* MAIN */
.main-wrapper{margin-left:var(--fm-sidebar);flex:1;display:flex;flex-direction:column;min-height:100vh;transition:.3s}
.topbar{background:#fff;border-bottom:1px solid #e8edf3;padding:0 24px;height:58px;display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:100;box-shadow:0 1px 4px rgba(0,0,0,.06)}
.topbar-left{display:flex;align-items:center;gap:12px}
.topbar-brand{display:flex;align-items:center;gap:10px}
.topbar-brand .topbar-logo{max-height:30px;max-width:100px;object-fit:contain}
.topbar-brand .topbar-name{font-size:.85rem;font-weight:700;color:var(--fm-primary)}
.page-main{padding:24px;flex:1}
/* CARDS */
.fm-card{background:#fff;border-radius:12px;box-shadow:0 1px 6px rgba(0,0,0,.06);border:1px solid #e8edf3;overflow:hidden}
.fm-card-body{padding:20px}
.card-header-fm{padding:14px 20px;border-bottom:1px solid #f0f4f8;display:flex;align-items:center;justify-content:space-between}
.card-header-fm h5{font-size:.9rem;font-weight:700;color:var(--fm-primary);margin:0;display:flex;align-items:center;gap:8px}
/* KPI */
.kpi-card{background:#fff;border-radius:12px;padding:18px;box-shadow:0 1px 6px rgba(0,0,0,.06);border-left:4px solid #ccc}
.kpi-card.kpi-primary{border-left-color:var(--fm-primary)}
.kpi-card.kpi-secondary{border-left-color:var(--fm-secondary)}
.kpi-card.kpi-blue{border-left-color:var(--fm-blue)}.kpi-card.kpi-green{border-left-color:var(--fm-green)}
.kpi-card.kpi-orange{border-left-color:var(--fm-orange)}.kpi-card.kpi-red{border-left-color:var(--fm-red)}
.kpi-card.kpi-teal{border-left-color:var(--fm-teal)}.kpi-card.kpi-gold{border-left-color:var(--fm-secondary)}
.kpi-card.kpi-navy{border-left-color:var(--fm-primary)}
.kpi-icon{width:44px;height:44px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:1.3rem;background:rgba(<?= $primaryRgb ?>,.12);color:var(--fm-primary)}
.kpi-card.kpi-blue .kpi-icon{background:rgba(21,101,192,.1);color:var(--fm-blue)}
.kpi-card.kpi-green .kpi-icon{background:rgba(46,125,50,.1);color:var(--fm-green)}
.kpi-card.kpi-orange .kpi-icon{background:rgba(230,81,0,.1);color:var(--fm-orange)}
.kpi-card.kpi-red .kpi-icon{background:rgba(198,40,40,.1);color:var(--fm-red)}
.kpi-card.kpi-teal .kpi-icon{background:rgba(0,137,123,.1);color:var(--fm-teal)}
.kpi-card.kpi-gold .kpi-icon,.kpi-card.kpi-secondary .kpi-icon{background:rgba(<?= $secondaryRgb ?>,.15);color:var(--fm-secondary)}
.kpi-card.kpi-navy .kpi-icon,.kpi-card.kpi-primary .kpi-icon{background:rgba(<?= $primaryRgb ?>,.12);color:var(--fm-primary)}
.kpi-label{font-size:.72rem;color:#6b7a8d;font-weight:600;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px}
.kpi-value{font-size:1.55rem;font-weight:700;color:#1a2332;line-height:1.1}
.kpi-sub{font-size:.72rem;color:#6b7a8d;margin-top:2px}
/* PAGE HEADER */
.page-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;flex-wrap:wrap;gap:10px}
.page-header h1{font-size:1.35rem;font-weight:700;color:var(--fm-primary);margin:0}
/* TABLES */
.fm-table{width:100%;border-collapse:collapse}
.fm-table th{background:#f8fafc;color:#5a6472;font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.5px;padding:11px 14px;border-bottom:2px solid #e8edf3;white-space:nowrap}
.fm-table td{padding:11px 14px;border-bottom:1px solid #f0f4f8;font-size:.83rem;vertical-align:middle}
.fm-table tr:hover td{background:#fdf8f6}
/* BADGES */
.fm-badge{display:inline-flex;align-items:center;padding:3px 10px;border-radius:20px;font-size:.7rem;font-weight:600;white-space:nowrap}
.badge-status-new{background:#eff6ff;color:#1d4ed8}.badge-status-assigned{background:#fef9c3;color:#854d0e}
.badge-status-in_progress{background:#dbeafe;color:#1e40af}.badge-status-completed{background:#dcfce7;color:#166534}
.badge-status-on_hold{background:#f3e8ff;color:#7c3aed}.badge-status-closed{background:#f1f5f9;color:#475569}
.badge-status-cancelled{background:#fee2e2;color:#991b1b}.badge-status-active{background:#dcfce7;color:#166534}
.badge-status-inactive{background:#f1f5f9;color:#475569}.badge-status-pending{background:#fef9c3;color:#854d0e}
.badge-status-paid{background:#dcfce7;color:#166534}.badge-status-overdue{background:#fee2e2;color:#991b1b}
.badge-status-sent{background:#dbeafe;color:#1e40af}.badge-status-draft{background:#f1f5f9;color:#475569}
.badge-status-expired{background:#fee2e2;color:#991b1b}.badge-status-reviewed{background:#dbeafe;color:#1e40af}
.badge-status-converted{background:#dcfce7;color:#166534}.badge-status-rejected{background:#fee2e2;color:#991b1b}
.badge-priority-critical{background:#fee2e2;color:#991b1b}.badge-priority-high{background:#ffedd5;color:#9a3412}
.badge-priority-medium{background:#fef9c3;color:#854d0e}.badge-priority-low{background:#dcfce7;color:#166534}
/* BUTTONS */
.btn-fm-primary{background:var(--fm-primary);color:#fff;border:none;border-radius:8px;padding:8px 18px;font-size:.83rem;font-weight:600;cursor:pointer;transition:.2s;text-decoration:none;display:inline-flex;align-items:center;gap:6px}
.btn-fm-primary:hover{background:var(--fm-primary-hover);color:#fff}
.btn-fm-outline{background:transparent;color:var(--fm-primary);border:1px solid var(--fm-primary);border-radius:8px;padding:7px 18px;font-size:.83rem;font-weight:600;cursor:pointer;transition:.2s;text-decoration:none;display:inline-flex;align-items:center;gap:6px}
.btn-fm-outline:hover{background:var(--fm-primary);color:#fff}
.btn-fm-secondary{background:var(--fm-secondary);color:#fff;border:none;border-radius:8px;padding:8px 18px;font-size:.83rem;font-weight:600;cursor:pointer;transition:.2s;text-decoration:none;display:inline-flex;align-items:center;gap:6px}
.btn-fm-secondary:hover{background:var(--fm-secondary-hover);color:#fff}
.btn-action{width:30px;height:30px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;font-size:.8rem;cursor:pointer;text-decoration:none;border:none}
/* FORMS */
.fm-form-section{background:#fdf8f6;border-radius:10px;padding:18px;margin-bottom:16px}
.fm-form-section h6{font-size:.8rem;font-weight:700;color:var(--fm-primary);text-transform:uppercase;letter-spacing:.5px;margin-bottom:14px;display:flex;align-items:center;gap:8px}
.form-label{font-size:.8rem;font-weight:600;color:#374151;margin-bottom:5px}
.form-control,.form-select{font-size:.83rem;border-radius:8px;border:1px solid #d1d5db;padding:8px 12px}
.form-control:focus,.form-select:focus{border-color:var(--fm-primary);box-shadow:0 0 0 3px rgba(<?= $primaryRgb ?>,.15);outline:none}
/* ALERTS */
.sla-warn{background:#fffbeb!important}
.alert{border-radius:10px;font-size:.85rem;padding:12px 16px}
/* USER AVATAR */
.user-avatar{width:34px;height:34px;border-radius:50%;background:linear-gradient(135deg,var(--fm-primary),var(--fm-secondary));color:#fff;display:flex;align-items:center;justify-content:center;font-size:.75rem;font-weight:700;flex-shrink:0}
.x-small{font-size:.72rem}
/* TABS */
.nav-tabs .nav-link{font-size:.82rem;font-weight:500;color:#6b7a8d;border:none;border-bottom:2px solid transparent;padding:10px 16px;border-radius:0}
.nav-tabs .nav-link:hover{color:var(--fm-primary);border-bottom-color:#d1d5db}
.nav-tabs .nav-link.active{color:var(--fm-primary);font-weight:700;border-bottom-color:var(--fm-primary);background:none}
.tab-content{min-height:200px}
/* MOBILE */
@media(max-width:768px){.sidebar{transform:translateX(-100%)}.sidebar.show{transform:none}.main-wrapper{margin-left:0}.page-main{padding:14px}}
/* text-primary override */
.text-primary{color:var(--fm-primary)!important}
a.text-primary:hover{color:var(--fm-primary-hover)!important}
.bg-primary{background-color:var(--fm-primary)!important}
</style>
</head>
<body>

<!-- SIDEBAR -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <?php if (!empty($companyLogoUrl)): ?>
    <img src="<?= esc($companyLogoUrl) ?>" alt="<?= esc($settings['company_name'] ?? 'Logo') ?>" class="brand-logo">
    <?php else: ?>
    <div class="brand-title"><i class="bi bi-buildings me-2" style="color:var(--fm-secondary)"></i><?= esc($settings['company_name'] ?? 'FM ERP') ?></div>
    <?php endif; ?>
    <div class="brand-sub"><?= esc($settings['company_tagline'] ?? 'Facility Management System') ?></div>
  </div>

  <div class="sidebar-nav">
    <?php $url = current_url(); ?>
    <?= view('layouts/sidebar_nav', ['url' => $url]) ?>
  </div><!-- /.sidebar-nav -->

  <div class="sidebar-footer">
    <a href="<?= base_url('logout') ?>" class="nav-link-item text-danger" style="padding:8px 4px;border-left:none">
      <i class="bi bi-box-arrow-left"></i>Sign Out
    </a>
  </div>
</nav>

<!-- MAIN WRAPPER -->
<div class="main-wrapper" id="mainWrapper">

  <!-- TOP BAR -->
  <div class="topbar">
    <div class="topbar-left">
      <button class="btn btn-sm btn-light d-md-none" onclick="document.getElementById('sidebar').classList.toggle('show')">
        <i class="bi bi-list fs-5"></i>
      </button>
      <!-- Logo/name in topbar for mobile or when sidebar is hidden -->
      <div class="topbar-brand d-md-none">
        <?php if (!empty($companyLogoUrl)): ?>
        <img src="<?= esc($companyLogoUrl) ?>" alt="Logo" class="topbar-logo">
        <?php else: ?>
        <span class="topbar-name"><?= esc($settings['company_name'] ?? 'FM ERP') ?></span>
        <?php endif; ?>
      </div>
      <span class="small text-muted d-none d-md-inline"><?= $title ?? '' ?></span>
    </div>
    <div class="d-flex align-items-center gap-3">
      <?php if (($user_role ?? '') === 'super_admin' && !empty($companies)): ?>
      <?= form_open(base_url('settings/switch-company'), ['class' => 'd-flex align-items-center gap-1']) ?>
      <?= csrf_field() ?>
      <select name="company_id" class="form-select form-select-sm" style="max-width:160px" onchange="this.form.submit()" title="Company context">
        <option value="">All Companies</option>
        <?php foreach ($companies as $co): ?>
        <option value="<?= $co['id'] ?>" <?= (string)($company_id ?? '') === (string)$co['id'] ? 'selected' : '' ?>><?= esc($co['name']) ?></option>
        <?php endforeach; ?>
      </select>
      <?= form_close() ?>
      <?php endif; ?>
      <!-- Notifications bell -->
      <a href="<?= base_url('notifications') ?>" class="position-relative text-muted text-decoration-none">
        <i class="bi bi-bell fs-5"></i>
        <?php if (!empty($unreadCount) && $unreadCount > 0): ?>
        <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" style="font-size:.6rem"><?= $unreadCount ?></span>
        <?php endif; ?>
      </a>
      <!-- User -->
      <div class="dropdown">
        <button class="btn btn-sm d-flex align-items-center gap-2 border-0 bg-transparent" data-bs-toggle="dropdown">
          <div class="user-avatar"><?= strtoupper(substr($currentUser['name'] ?? 'U', 0, 1)) ?></div>
          <div class="text-start d-none d-md-block">
            <div class="fw-semibold small" style="line-height:1.2"><?= esc($currentUser['name'] ?? '') ?></div>
            <div class="x-small text-muted"><?= esc($currentUser['role_display'] ?? ucfirst($currentUser['role_name'] ?? '')) ?></div>
          </div>
          <i class="bi bi-chevron-down small text-muted"></i>
        </button>
        <ul class="dropdown-menu dropdown-menu-end shadow-sm border-0" style="min-width:180px">
          <li><a class="dropdown-item small" href="<?= base_url('profile') ?>"><i class="bi bi-person me-2"></i>Profile</a></li>
          <li><a class="dropdown-item small" href="<?= base_url('settings') ?>"><i class="bi bi-gear me-2"></i>Settings</a></li>
          <li><hr class="dropdown-divider"></li>
          <li><a class="dropdown-item small text-danger" href="<?= base_url('logout') ?>"><i class="bi bi-box-arrow-left me-2"></i>Sign Out</a></li>
        </ul>
      </div>
    </div>
  </div>

  <!-- FLASH MESSAGES (global) -->
  <div class="px-4 pt-3">
    <?php if (session()->getFlashdata('success')): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
      <i class="bi bi-check-circle me-2"></i><?= session()->getFlashdata('success') ?>
      <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    <?php if (session()->getFlashdata('error')): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
      <i class="bi bi-exclamation-circle me-2"></i><?= session()->getFlashdata('error') ?>
      <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    <?php if (session()->getFlashdata('warning')): ?>
    <div class="alert alert-warning alert-dismissible fade show" role="alert">
      <i class="bi bi-exclamation-triangle me-2"></i><?= session()->getFlashdata('warning') ?>
      <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
  </div>

  <!-- PAGE CONTENT -->
  <div class="page-main">
    <?= $this->renderSection('content') ?>
  </div>

</div><!-- /.main-wrapper -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Auto-dismiss alerts after 5s
document.querySelectorAll('.alert.fade.show').forEach(el => {
  setTimeout(() => { new bootstrap.Alert(el).close(); }, 5000);
});
</script>
<?= $this->renderSection('scripts') ?>
</body>
</html>
