<?php
/** Layout utama aplikasi. */
use App\Core\Acl;
use App\Core\Flash;
use App\Core\Request;

$flashes = Flash::pull();
$uri = Request::uri();
$modulAktif = $modul_aktif ?? '';
?>
<!DOCTYPE html>
<html lang="id" data-bs-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="csrf-token" content="<?= attr(csrfToken()) ?>">
<meta name="base-url" content="<?= attr(url('/')) ?>">
<title><?= e(($judul ?? 'Dashboard') . ' — ' . ($app_name ?? 'SIPIUTANG')) ?></title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' rx='7' fill='%231f3864'/><text x='16' y='23' font-size='18' font-family='Arial' font-weight='bold' fill='white' text-anchor='middle'>S</text></svg>">
<link href="<?= asset('vendor/bootstrap.min.css') ?>" rel="stylesheet">
<link href="<?= asset('vendor/bootstrap-icons.css') ?>" rel="stylesheet">
<link href="<?= asset('css/app.css') ?>" rel="stylesheet">
<?= \App\Core\View::section('head') ?>
</head>
<body>

<!-- ============================ SIDEBAR ============================ -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <a href="<?= url('/') ?>">
      <span class="brand-mark">S</span>
      <span class="brand-text">
        <strong><?= e($app_name ?? 'SIPIUTANG') ?></strong>
        <small>Sistem Piutang &amp; Penagihan</small>
      </span>
    </a>
    <button class="btn btn-sm sidebar-close d-lg-none" type="button" aria-label="Tutup menu">
      <i class="bi bi-x-lg"></i>
    </button>
  </div>

  <ul class="sidebar-menu">
    <?php foreach (($menu ?? []) as $m):
        if (!empty($m['perm'])) { [$mo, $ac] = array_pad(explode('.', $m['perm'], 2), 2, 'view'); if (!can($mo, $ac)) continue; }
        $children = array_values(array_filter($m['children'] ?? [], function ($c) {
            if (empty($c['perm'])) return true;
            [$mo2, $ac2] = array_pad(explode('.', $c['perm'], 2), 2, 'view');
            return can($mo2, $ac2);
        }));
        $isActive = $uri === $m['url'] || ($m['url'] !== '/' && str_starts_with($uri, $m['url']));
        foreach ($children as $c) if ($uri === $c['url'] || ($c['url'] !== '/' && str_starts_with($uri, $c['url']))) $isActive = true;
        $id = 'menu-' . preg_replace('/[^a-z0-9]/', '', strtolower($m['label']));
    ?>
      <li class="<?= $children ? 'has-children' : '' ?> <?= $isActive ? 'active' : '' ?>">
        <?php if ($children): ?>
          <a href="#<?= $id ?>" data-bs-toggle="collapse" class="<?= $isActive ? '' : 'collapsed' ?>" aria-expanded="<?= $isActive ? 'true' : 'false' ?>">
            <i class="bi bi-<?= e($m['icon']) ?>"></i><span><?= e($m['label']) ?></span>
            <i class="bi bi-chevron-down chev"></i>
          </a>
          <ul class="collapse <?= $isActive ? 'show' : '' ?>" id="<?= $id ?>">
            <?php foreach ($children as $c): ?>
              <li class="<?= $uri === $c['url'] ? 'active' : '' ?>">
                <a href="<?= url($c['url']) ?>"><?= e($c['label']) ?></a>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php else: ?>
          <a href="<?= url($m['url']) ?>">
            <i class="bi bi-<?= e($m['icon']) ?>"></i><span><?= e($m['label']) ?></span>
            <?php if ($m['url'] === '/persetujuan' && ($approval_badge ?? 0) > 0): ?>
              <span class="badge bg-danger rounded-pill ms-auto"><?= (int)$approval_badge ?></span>
            <?php endif; ?>
          </a>
        <?php endif; ?>
      </li>
    <?php endforeach; ?>
  </ul>

  <div class="sidebar-footer">
    <small>Versi <?= e($app_version ?? '1.0.0') ?></small>
  </div>
</nav>
<div class="sidebar-backdrop d-lg-none"></div>

<!-- ============================ KONTEN ============================ -->
<div class="main">
  <header class="topbar">
    <button class="btn btn-link topbar-toggle d-lg-none p-0 me-2" type="button" aria-label="Buka menu">
      <i class="bi bi-list fs-3"></i>
    </button>

    <div class="topbar-title">
      <h1><?= e($judul ?? 'Dashboard') ?></h1>
      <?php if (!empty($subjudul)): ?><p><?= e($subjudul) ?></p><?php endif; ?>
    </div>

    <form class="topbar-search d-none d-md-flex" action="<?= url('/invoice') ?>" method="get" role="search">
      <i class="bi bi-search"></i>
      <input type="search" name="cari_teks" class="form-control" placeholder="Cari invoice, faktur pajak, SO, customer…"
             value="<?= attr(Request::get('cari_teks', '')) ?>" aria-label="Pencarian global">
    </form>

    <div class="dropdown ms-auto">
      <button class="btn user-btn dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
        <span class="avatar"><?= e(mb_substr((string)($current_user['name'] ?? 'U'), 0, 1)) ?></span>
        <span class="d-none d-sm-inline text-start">
          <strong><?= e($current_user['name'] ?? '') ?></strong>
          <small><?= e($current_user['role_name'] ?? '') ?></small>
        </span>
      </button>
      <ul class="dropdown-menu dropdown-menu-end shadow">
        <li><h6 class="dropdown-header"><?= e($current_user['email'] ?? '') ?></h6></li>
        <li><a class="dropdown-item" href="<?= url('/profil') ?>"><i class="bi bi-person me-2"></i>Profil Saya</a></li>
        <li><a class="dropdown-item" href="<?= url('/ganti-sandi') ?>"><i class="bi bi-key me-2"></i>Ganti Kata Sandi</a></li>
        <?php if (can('pengaturan', 'view')): ?>
          <li><a class="dropdown-item" href="<?= url('/pengaturan') ?>"><i class="bi bi-gear me-2"></i>Pengaturan</a></li>
        <?php endif; ?>
        <li><hr class="dropdown-divider"></li>
        <li>
          <form method="post" action="<?= url('/keluar') ?>" class="px-0">
            <?= csrf() ?>
            <button class="dropdown-item text-danger" type="submit"><i class="bi bi-box-arrow-right me-2"></i>Keluar</button>
          </form>
        </li>
      </ul>
    </div>
  </header>

  <main class="content">
    <?php if ($peringatanCakupan = App\Core\Acl::scopeWarning()): ?>
      <div class="alert alert-warning d-flex align-items-start" role="alert">
        <i class="bi bi-shield-exclamation me-2 mt-1"></i>
        <div><strong>Cakupan data terbatas.</strong> <?= e($peringatanCakupan) ?></div>
      </div>
    <?php endif; ?>
    <?php foreach ($flashes as $f): ?>
      <div class="alert alert-<?= e($f['type']) ?> alert-dismissible fade show" role="alert">
        <i class="bi bi-<?= $f['type'] === 'success' ? 'check-circle-fill' : ($f['type'] === 'danger' ? 'exclamation-octagon-fill' : ($f['type'] === 'warning' ? 'exclamation-triangle-fill' : 'info-circle-fill')) ?> me-2"></i>
        <?= e($f['message']) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Tutup"></button>
      </div>
    <?php endforeach; ?>

    <?= $content ?? '' ?>
  </main>

  <footer class="footer">
    <span><?= e($company_name ?? '') ?> &middot; <?= e($app_name ?? '') ?> v<?= e($app_version ?? '') ?></span>
    <span class="text-body-tertiary"><?= e(tglPanjang(App\Core\Dates::today())) ?></span>
  </footer>
</div>

<!-- Dialog konfirmasi generik -->
<div class="modal fade" id="modalKonfirmasi" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-question-circle me-2 text-warning"></i>Konfirmasi</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
      </div>
      <div class="modal-body" id="modalKonfirmasiPesan">Apakah Anda yakin?</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button>
        <button type="button" class="btn btn-danger" id="modalKonfirmasiOk">Ya, Lanjutkan</button>
      </div>
    </div>
  </div>
</div>

<div class="loading-overlay" id="loadingOverlay" aria-hidden="true">
  <div class="spinner-border text-primary" role="status"><span class="visually-hidden">Memuat…</span></div>
  <p>Sedang memproses…</p>
</div>

<script src="<?= asset('vendor/bootstrap.bundle.min.js') ?>"></script>
<script src="<?= asset('vendor/chart.umd.min.js') ?>"></script>
<script src="<?= asset('js/app.js') ?>"></script>
<?= \App\Core\View::section('scripts') ?>
</body>
</html>
