<!DOCTYPE html>
<html lang="en" data-bs-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= isset($title) ? htmlspecialchars($title) : 'Admin - ' . APP_NAME ?></title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<link href="<?= APP_URL ?>/assets/css/style.css?v=<?= time() ?>" rel="stylesheet">
<link href="<?= APP_URL ?>/assets/css/admin.css?v=<?= time() ?>" rel="stylesheet">
</head>
<body class="admin-body">

<!-- Sidebar -->
<div class="admin-sidebar" id="sidebar">
  <div class="sidebar-header">
    <a href="<?= APP_URL ?>/admin" class="d-flex align-items-center gap-2 text-decoration-none">
      <i class="bi bi-buildings-fill text-primary fs-2"></i>
      <div>
        <div class="fw-700 text-white fs-6 lh-1">Zabibu</div>
        <div class="text-white small opacity-75">Residence Admin</div>
      </div>
    </a>
    <button class="btn btn-sm btn-link text-white d-lg-none ms-auto" id="sidebarToggle">
      <i class="bi bi-x-lg"></i>
    </button>
  </div>

  <!-- User Info -->
  <div class="sidebar-user">
    <div class="d-flex align-items-center gap-2">
      <div class="avatar-sm bg-primary rounded-circle d-flex align-items-center justify-content-center text-white fw-600">
        <?= strtoupper(substr($_SESSION['user_name'] ?? 'A', 0, 1)) ?>
      </div>
      <div class="flex-1 overflow-hidden">
        <div class="text-white fw-500 small text-truncate"><?= htmlspecialchars($_SESSION['user_name'] ?? 'Admin') ?></div>
        <div style="font-size:0.72rem;color:rgba(255,255,255,0.75)"><?= ucfirst(str_replace('_',' ', $_SESSION['user_role'] ?? '')) ?></div>
      </div>
    </div>
  </div>

  <!-- Navigation -->
  <nav class="sidebar-nav">
    <?php
      $role           = $_SESSION['user_role'] ?? '';
      $isSuperAdmin   = $role === 'super_admin';
      $isOwner        = $role === 'property_owner';
      $isManager      = $role === 'property_manager';
      $isAccountant   = $role === 'accountant';
      $isReceptionist = $role === 'receptionist';

      $canProperties  = $isSuperAdmin || $isOwner || $isManager;
      $canTenants     = $isSuperAdmin || $isOwner || $isManager || $isReceptionist;
      $canFinance     = $isSuperAdmin || $isOwner || $isAccountant;
      $canOperations  = $isSuperAdmin || $isOwner || $isManager || $isReceptionist;
      $canReports     = $isSuperAdmin || $isOwner || $isManager || $isAccountant;
      $canSystem      = $isSuperAdmin;
    ?>

    <div class="nav-section">MAIN</div>
    <a href="<?= APP_URL ?>/admin" class="nav-link <?= strpos($_SERVER['REQUEST_URI'],'admin') !== false && !strpos($_SERVER['REQUEST_URI'],'admin/') ? 'active' : '' ?>">
      <i class="bi bi-speedometer2"></i> Dashboard
    </a>

    <?php if ($canProperties): ?>
    <div class="nav-section">PROPERTIES</div>
    <a href="<?= APP_URL ?>/admin/properties" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/properties') ? 'active' : '' ?>">
      <i class="bi bi-buildings"></i> Properties
    </a>
    <a href="<?= APP_URL ?>/admin/buildings" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/buildings') ? 'active' : '' ?>">
      <i class="bi bi-building"></i> Buildings
    </a>
    <a href="<?= APP_URL ?>/admin/units" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/units') ? 'active' : '' ?>">
      <i class="bi bi-door-closed"></i> Units / Rooms
    </a>
    <?php endif; ?>

    <?php if ($canTenants): ?>
    <div class="nav-section">TENANTS</div>
    <a href="<?= APP_URL ?>/admin/tenants" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/tenants') ? 'active' : '' ?>">
      <i class="bi bi-people"></i> Tenants
    </a>
    <a href="<?= APP_URL ?>/admin/leases" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/leases') ? 'active' : '' ?>">
      <i class="bi bi-file-earmark-text"></i> Leases
    </a>
    <a href="<?= APP_URL ?>/admin/bookings" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/bookings') ? 'active' : '' ?>">
      <i class="bi bi-calendar-check"></i> Bookings
      <?php
      $pendingCount = 0;
      try {
        $db = \Core\Database::getInstance();
        $pendingCount = (int)$db->fetchColumn("SELECT COUNT(*) FROM bookings WHERE status='pending'");
      } catch (Exception $e) {}
      if ($pendingCount > 0): ?>
        <span class="badge bg-warning ms-auto"><?= $pendingCount ?></span>
      <?php endif; ?>
    </a>
    <?php endif; ?>

    <?php if ($canFinance): ?>
    <div class="nav-section">FINANCE</div>
    <a href="<?= APP_URL ?>/admin/payments" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/payments') ? 'active' : '' ?>">
      <i class="bi bi-credit-card"></i> Payments
    </a>
    <a href="<?= APP_URL ?>/admin/invoices" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/invoices') ? 'active' : '' ?>">
      <i class="bi bi-receipt"></i> Invoices
    </a>
    <a href="<?= APP_URL ?>/admin/expenses" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/expenses') ? 'active' : '' ?>">
      <i class="bi bi-cash-stack"></i> Expenses
    </a>
    <?php endif; ?>

    <?php if ($canOperations): ?>
    <div class="nav-section">OPERATIONS</div>
    <a href="<?= APP_URL ?>/admin/maintenance" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/maintenance') ? 'active' : '' ?>">
      <i class="bi bi-tools"></i> Maintenance
      <?php
      $openMaint = 0;
      try {
        $db = \Core\Database::getInstance();
        $openMaint = (int)$db->fetchColumn("SELECT COUNT(*) FROM maintenance_requests WHERE status IN ('open','in_progress') AND priority='emergency'");
      } catch (Exception $e) {}
      if ($openMaint > 0): ?>
        <span class="badge bg-danger ms-auto"><?= $openMaint ?></span>
      <?php endif; ?>
    </a>
    <a href="<?= APP_URL ?>/admin/notifications" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/notifications') ? 'active' : '' ?>">
      <i class="bi bi-bell"></i> Notifications
    </a>
    <?php endif; ?>

    <?php if ($canReports): ?>
    <div class="nav-section">REPORTS</div>
    <a href="<?= APP_URL ?>/admin/reports" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/reports') ? 'active' : '' ?>">
      <i class="bi bi-bar-chart"></i> Reports
    </a>
    <?php endif; ?>

    <?php if ($canSystem): ?>
    <div class="nav-section">SYSTEM</div>
    <a href="<?= APP_URL ?>/admin/users" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/users') ? 'active' : '' ?>">
      <i class="bi bi-person-gear"></i> Users
    </a>
    <a href="<?= APP_URL ?>/admin/settings" class="nav-link <?= str_contains($_SERVER['REQUEST_URI'],'/settings') ? 'active' : '' ?>">
      <i class="bi bi-gear"></i> Settings
    </a>
    <?php endif; ?>
  </nav>
</div>

<!-- Main Content -->
<div class="admin-main" id="adminMain">
  <!-- Top Bar -->
  <header class="admin-topbar">
    <div class="d-flex align-items-center gap-3">
      <button class="btn btn-sm btn-link text-dark p-0" id="sidebarToggleBtn">
        <i class="bi bi-list fs-4"></i>
      </button>
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb mb-0 small">
          <li class="breadcrumb-item"><a href="<?= APP_URL ?>/admin" class="text-decoration-none">Home</a></li>
          <?php if (isset($breadcrumb)): foreach ($breadcrumb as $b): ?>
          <li class="breadcrumb-item <?= isset($b['url']) ? '' : 'active' ?>">
            <?= isset($b['url']) ? '<a href="'.$b['url'].'" class="text-decoration-none">'.$b['label'].'</a>' : $b['label'] ?>
          </li>
          <?php endforeach; endif; ?>
        </ol>
      </nav>
    </div>
    <div class="d-flex align-items-center gap-2">
      <!-- View Website -->
      <a href="<?= APP_URL ?>/" target="_blank" class="btn btn-sm btn-outline-primary d-flex align-items-center gap-1" title="View Website">
        <i class="bi bi-box-arrow-up-right"></i>
        <span class="d-none d-md-inline fw-600" style="font-size:.8rem">View Site</span>
      </a>
      <!-- Dark Mode Toggle -->
      <button class="btn btn-sm btn-outline-secondary rounded-circle" id="darkModeBtn" title="Toggle Dark Mode">
        <i class="bi bi-moon-fill" id="darkModeIcon"></i>
      </button>
      <!-- Notifications -->
      <div class="dropdown">
        <button class="btn btn-sm btn-outline-secondary rounded-circle position-relative" data-bs-toggle="dropdown">
          <i class="bi bi-bell"></i>
          <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" style="font-size:9px">3</span>
        </button>
        <ul class="dropdown-menu dropdown-menu-end shadow" style="width:320px">
          <li class="px-3 py-2 border-bottom"><strong>Notifications</strong></li>
          <li><a class="dropdown-item py-2" href="#"><i class="bi bi-exclamation-triangle text-danger me-2"></i>Emergency maintenance request</a></li>
          <li><a class="dropdown-item py-2" href="#"><i class="bi bi-calendar-check text-warning me-2"></i>2 leases expiring soon</a></li>
          <li><a class="dropdown-item py-2" href="#"><i class="bi bi-cash text-success me-2"></i>New payment received</a></li>
          <li class="border-top"><a class="dropdown-item text-center text-primary small" href="<?= APP_URL ?>/admin/notifications">View all</a></li>
        </ul>
      </div>
      <!-- User Menu -->
      <div class="dropdown">
        <button class="btn btn-sm btn-outline-secondary d-flex align-items-center gap-1" data-bs-toggle="dropdown">
          <div class="avatar-xs bg-primary rounded-circle d-flex align-items-center justify-content-center text-white fw-600" style="width:26px;height:26px;font-size:12px">
            <?= strtoupper(substr($_SESSION['user_name'] ?? 'A', 0, 1)) ?>
          </div>
          <span class="small d-none d-md-inline"><?= htmlspecialchars($_SESSION['user_name'] ?? 'Admin') ?></span>
          <i class="bi bi-chevron-down small"></i>
        </button>
        <ul class="dropdown-menu dropdown-menu-end shadow">
          <li><a class="dropdown-item" href="<?= APP_URL ?>/admin"><i class="bi bi-speedometer2 me-2"></i>Dashboard</a></li>
          <li><a class="dropdown-item" href="<?= APP_URL ?>/"><i class="bi bi-house me-2"></i>View Website</a></li>
          <li><hr class="dropdown-divider"></li>
          <li><a class="dropdown-item text-danger" href="<?= APP_URL ?>/logout"><i class="bi bi-box-arrow-right me-2"></i>Logout</a></li>
        </ul>
      </div>
    </div>
  </header>

  <!-- Page Content -->
  <div class="admin-content-wrapper">
  <div class="admin-content">
    <?php 
    use App\Helpers\Helper;
    $flash = Helper::getFlash();
    if ($flash): ?>
    <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show" role="alert">
      <i class="bi bi-<?= $flash['type']==='success'?'check-circle':'exclamation-triangle' ?> me-2"></i>
      <?= $flash['message'] ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <?= $content ?>
  </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script src="<?= APP_URL ?>/assets/js/app.js"></script>
<script src="<?= APP_URL ?>/assets/js/admin.js"></script>
</body>
</html>
