<?php
/**
 * 로그인 후 메인 — 정보 집약형 대시보드 (KPI·다중 표·알림·로그 한 화면)
 * 상단 메뉴바는 lg_dashboard.php 와 동일
 *
 * @var string $lgLabel
 */
$lgLabel = $lgLabel ?? '북구';
$mbName  = session()->get('mb_name') ?? '담당자';
$dashClassic = base_url('dashboard/classic-mock');
$dashModern  = base_url('dashboard/modern');
$dashDense   = base_url('dashboard/dense');
$dashCharts  = base_url('dashboard/charts');
$dashBlend   = base_url('dashboard/blend');

$kpiTop = [
    ['icon' => 'fa-triangle-exclamation', 'c' => 'text-amber-700', 'bg' => 'bg-amber-50', 'v' => '3', 'l' => '재고부족', 'sub' => '품목'],
    ['icon' => 'fa-cart-shopping', 'c' => 'text-sky-700', 'bg' => 'bg-sky-50', 'v' => '12', 'l' => '구매신청', 'sub' => '미처리'],
    ['icon' => 'fa-truck', 'c' => 'text-emerald-700', 'bg' => 'bg-emerald-50', 'v' => '8', 'l' => '발주·입고', 'sub' => '금주'],
    ['icon' => 'fa-user-clock', 'c' => 'text-violet-700', 'bg' => 'bg-violet-50', 'v' => '4', 'l' => '회원승인', 'sub' => '대기'],
    ['icon' => 'fa-store', 'c' => 'text-rose-700', 'bg' => 'bg-rose-50', 'v' => '127', 'l' => '지정판매소', 'sub' => '등록'],
    ['icon' => 'fa-boxes-stacked', 'c' => 'text-slate-700', 'bg' => 'bg-slate-100', 'v' => '48.2k', 'l' => '봉투재고', 'sub' => '장 합계'],
    ['icon' => 'fa-file-invoice', 'c' => 'text-orange-700', 'bg' => 'bg-orange-50', 'v' => '6', 'l' => '세금계산서', 'sub' => '발행대기'],
    ['icon' => 'fa-headset', 'c' => 'text-cyan-700', 'bg' => 'bg-cyan-50', 'v' => '2', 'l' => '민원·문의', 'sub' => '오늘'],
];

$stockRows = [
    ['일반 5L', '12,400', '안전', '3.2주'],
    ['일반 10L', '8,200', '주의', '1.8주'],
    ['일반 20L', '2,100', '부족', '0.6주'],
    ['음식물 스티커', '15,000', '안전', '5.1주'],
    ['재사용봉투', '4,300', '안전', '2.4주'],
    ['특수규격 A', '890', '부족', '0.3주'],
];

$orderRows = [
    ['PO-2025-0218', '○○상사', '일반 5L×2박스', '발주확인', '02-26 10:20'],
    ['PO-2025-0217', '△△유통', '스티커 500매', '납품중', '02-26 09:05'],
    ['PO-2025-0216', '□□종량제', '20L 혼합', '입고완료', '02-25 16:40'],
    ['REQ-8841', '행복마트 북구점', '5L 2,000장', '접수', '02-26 09:12'],
    ['REQ-8839', '○○슈퍼', '스티커 500', '처리중', '02-26 08:45'],
];

$logRows = [
    ['10:42', 'system', '일일 재고 스냅샷 생성 완료'],
    ['10:18', 'user', esc($mbName) . ' 로그인 (IP 마스킹)'],
    ['09:55', 'batch', '구매신청 자동 분배 3건'],
    ['09:30', 'admin', '판매소 코드 2건 갱신'],
    ['08:12', 'api', '세금계산서 연동 응답 정상'],
];

$storeSummary = [
    ['행복마트 북구점', '42', '정상', '02-26'],
    ['○○슈퍼', '38', '정상', '02-25'],
    ['△△상회', '15', '연체1건', '02-20'],
    ['□□마트', '29', '정상', '02-26'],
    ['◇◇할인점', '51', '정상', '02-26'],
];

$approvals = [
    ['김○○', '판매소', '02-26', '서류검토'],
    ['이○○', '일반', '02-25', '본인확인'],
    ['박○○', '판매소', '02-25', '주소불일치'],
];

$notices = [
    '2월 말 정기 재고 실사 안내 — 2/28 17:00 마감',
    '봉투 단가 조정 예고 — 3/1 적용 예정 (안내문 배포 완료)',
];
?>
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>GBLS — 종합 현황 (정보집약)</title>
  <script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
<style data-purpose="global-font-scale">html{font-size:18px}.app-brand,.app-brand *{font-size:16px}</style>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet"/>
  <style>
    body {
      font-family: 'Malgun Gothic', 'Apple SD Gothic Neo', 'Noto Sans KR', sans-serif;
      font-size: 12px;
      color: #333;
    }
    .nav-top a.nav-active {
      color: #2b4c8c;
      font-weight: 600;
      border-bottom: 2px solid #2b4c8c;
      padding-bottom: 2px;
      margin-bottom: -2px;
    }
    .dense-table th, .dense-table td { padding: 0.25rem 0.4rem; line-height: 1.25; }
    .dense-table thead th { font-size: 11px; font-weight: 600; color: #555; background: #f3f4f6; border-bottom: 1px solid #d1d5db; }
    .dense-table tbody td { border-bottom: 1px solid #eee; font-size: 11px; }
    .spark { display: flex; align-items: flex-end; gap: 2px; height: 36px; }
    .spark span { flex: 1; background: linear-gradient(180deg, #3b82f6, #93c5fd); border-radius: 1px; min-width: 4px; }
  </style>
</head>
<body class="bg-[#f0f2f5] flex flex-col min-h-screen">
  <header class="border-b border-gray-300 bg-white shadow-sm shrink-0" data-purpose="top-navigation">
    <div class="flex items-center justify-between px-3 py-1.5 gap-3 flex-wrap">
      <div class="flex items-center gap-2 shrink-0">
        <?= view('components/header_brand', [
            'href' => base_url(),
            'linkClass' => 'flex items-center gap-2 text-green-700 font-bold text-base hover:opacity-90',
            'svgClass' => 'h-6 w-6 shrink-0',
        ]) ?>
        <span class="hidden sm:inline text-[11px] text-gray-500 border-l border-gray-300 pl-2">
          <?= esc($lgLabel) ?> · <strong class="text-gray-700"><?= esc($mbName) ?></strong>님
        </span>
      </div>
      <nav class="nav-top hidden lg:flex flex-wrap items-center gap-3 xl:gap-4 text-[13px] font-medium text-gray-700">
        <a class="nav-active flex items-center gap-1 whitespace-nowrap" href="<?= esc($dashDense) ?>">
          <i class="fa-solid fa-gauge-high"></i> 업무 현황
        </a>
        <a class="flex items-center gap-1 hover:text-blue-600 whitespace-nowrap" href="#"><i class="fa-regular fa-file-lines"></i> 문서 관리</a>
        <a class="flex items-center gap-1 hover:text-blue-600 whitespace-nowrap" href="#"><i class="fa-solid fa-box-open"></i> 규격</a>
        <a class="flex items-center gap-1 hover:text-blue-600 whitespace-nowrap" href="#"><i class="fa-solid fa-bag-shopping"></i> 봉투 양식</a>
        <a class="flex items-center gap-1 hover:text-blue-600 whitespace-nowrap" href="#"><i class="fa-solid fa-table"></i> 데이터 양식</a>
        <a class="flex items-center gap-1 hover:text-blue-600 whitespace-nowrap" href="#"><i class="fa-solid fa-clock-rotate-left"></i> 사용 내역</a>
        <a class="flex items-center gap-1 hover:text-blue-600 whitespace-nowrap" href="<?= base_url('bag/inventory-inquiry') ?>"><i class="fa-solid fa-boxes-stacked"></i> 재고 현황</a>
        <a class="flex items-center gap-1 hover:text-blue-600 whitespace-nowrap" href="<?= base_url('bag/waste-suibal-enterprise') ?>"><i class="fa-solid fa-table-list"></i> 수불 현황</a>
        <a class="flex items-center gap-1 hover:text-blue-600 whitespace-nowrap" href="#"><i class="fa-solid fa-chart-line"></i> 통계 분석</a>
        <a class="flex items-center gap-1 hover:text-blue-600 whitespace-nowrap" href="#"><i class="fa-solid fa-gear"></i> 설정</a>
      </nav>
      <div class="flex items-center gap-1.5 shrink-0 text-[11px]">
        <a href="<?= esc($dashClassic) ?>" class="text-[#2b4c8c] hover:underline whitespace-nowrap hidden md:inline">클래식</a>
        <span class="text-gray-300 hidden md:inline">|</span>
        <a href="<?= esc($dashModern) ?>" class="text-[#2b4c8c] hover:underline whitespace-nowrap hidden md:inline">모던</a>
        <span class="text-gray-300 hidden md:inline">|</span>
        <a href="<?= esc($dashBlend) ?>" class="text-[#2b4c8c] hover:underline whitespace-nowrap hidden md:inline" title="표+차트 혼합">혼합</a>
        <span class="text-gray-300 hidden md:inline">|</span>
        <a href="<?= esc($dashCharts) ?>" class="text-[#2b4c8c] hover:underline whitespace-nowrap hidden md:inline" title="그래프 대시보드">차트</a>
        <a href="<?= base_url('logout') ?>" class="text-gray-500 hover:text-gray-800 p-1 ml-1" title="로그아웃">
          <i class="fa-solid fa-arrow-right-from-bracket"></i>
        </a>
      </div>
    </div>
  </header>

  <!-- 컴팩트 컨텍스트 바 -->
  <div class="bg-[#eff5fb] border-b border-gray-300 px-3 py-1 flex flex-wrap items-center justify-between gap-2 text-[11px] shrink-0">
    <span class="font-semibold text-gray-800">
      <i class="fa-solid fa-table-columns text-[#2b4c8c] mr-1"></i>종합 운영 현황
      <span class="font-normal text-gray-500 ml-1">· KPI · 재고 · 발주/신청 · 로그 · 판매소</span>
    </span>
    <div class="flex flex-wrap items-center gap-2 text-gray-600">
      <span><i class="fa-regular fa-calendar mr-0.5"></i><?= date('Y-m-d (D) H:i') ?></span>
      <span class="text-gray-300">|</span>
      <span>기준지자체 <strong class="text-gray-800"><?= esc($lgLabel) ?></strong></span>
      <button type="button" class="bg-[#243a5e] text-white px-2 py-0.5 rounded text-[11px]"><i class="fa-solid fa-rotate mr-0.5"></i>새로고침</button>
    </div>
  </div>

  <main class="flex-1 overflow-y-auto p-2 sm:p-3">
    <?php if (session()->getFlashdata('success')): ?>
    <div class="mb-2 p-2 rounded border border-green-200 bg-green-50 text-green-800 text-[11px]"><?= esc(session()->getFlashdata('success')) ?></div>
    <?php endif; ?>

    <!-- 공지 티커 -->
    <div class="mb-2 flex flex-wrap gap-2">
      <?php foreach ($notices as $n): ?>
      <div class="flex-1 min-w-[200px] flex items-center gap-2 bg-amber-50 border border-amber-200 text-amber-900 px-2 py-1 rounded text-[11px]">
        <i class="fa-solid fa-bullhorn shrink-0"></i>
        <span class="truncate" title="<?= esc($n) ?>"><?= esc($n) ?></span>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- KPI 8칸 -->
    <div class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-1.5 mb-2">
      <?php foreach ($kpiTop as $k): ?>
      <div class="bg-white border border-gray-200 rounded px-2 py-1.5 flex items-center gap-2 shadow-sm">
        <div class="w-8 h-8 rounded <?= $k['bg'] ?> <?= $k['c'] ?> flex items-center justify-center shrink-0 text-sm">
          <i class="fa-solid <?= esc($k['icon'], 'attr') ?>"></i>
        </div>
        <div class="min-w-0">
          <div class="text-base font-bold text-gray-900 leading-tight"><?= esc($k['v']) ?></div>
          <div class="text-[10px] text-gray-500 leading-tight"><?= esc($k['l']) ?></div>
          <div class="text-[9px] text-gray-400"><?= esc($k['sub']) ?></div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>

    <div class="grid grid-cols-1 xl:grid-cols-12 gap-2 mb-2">
      <!-- 재고 품목 -->
      <section class="xl:col-span-4 bg-white border border-gray-200 rounded shadow-sm overflow-hidden">
        <div class="px-2 py-1 border-b border-gray-200 bg-gray-50 flex justify-between items-center">
          <h2 class="text-[11px] font-bold text-gray-800"><i class="fa-solid fa-warehouse text-[#2b4c8c] mr-1"></i>품목별 재고·소진예상</h2>
          <a href="<?= base_url('bag/inventory-inquiry') ?>" class="text-[10px] text-blue-600 hover:underline">상세</a>
        </div>
        <div class="overflow-x-auto max-h-[220px] overflow-y-auto">
          <table class="w-full dense-table text-left">
            <thead>
              <tr>
                <th>품목</th>
                <th class="text-right">재고(장)</th>
                <th>상태</th>
                <th class="text-right">소진</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($stockRows as $r): ?>
              <tr>
                <td class="font-medium text-gray-800"><?= esc($r[0]) ?></td>
                <td class="text-right tabular-nums"><?= esc($r[1]) ?></td>
                <td>
                  <?php
                  $badge = match ($r[2]) {
                      '안전' => 'bg-emerald-100 text-emerald-800',
                      '주의' => 'bg-amber-100 text-amber-800',
                      '부족' => 'bg-red-100 text-red-800',
                      default => 'bg-gray-100 text-gray-700',
                  };
                  ?>
                  <span class="text-[10px] px-1 py-0 rounded <?= $badge ?>"><?= esc($r[2]) ?></span>
                </td>
                <td class="text-right text-gray-600"><?= esc($r[3]) ?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>

      <!-- 발주·구매신청 -->
      <section class="xl:col-span-4 bg-white border border-gray-200 rounded shadow-sm overflow-hidden">
        <div class="px-2 py-1 border-b border-gray-200 bg-gray-50 flex justify-between items-center">
          <h2 class="text-[11px] font-bold text-gray-800"><i class="fa-solid fa-list-check text-[#2b4c8c] mr-1"></i>발주 / 구매신청 진행</h2>
          <span class="text-[10px] text-gray-500">최근 5건</span>
        </div>
        <div class="overflow-x-auto max-h-[220px] overflow-y-auto">
          <table class="w-full dense-table text-left">
            <thead>
              <tr>
                <th>문서</th>
                <th>상대</th>
                <th>내용</th>
                <th>단계</th>
                <th class="text-right">시각</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($orderRows as $r): ?>
              <tr>
                <td class="text-blue-700 font-mono text-[10px]"><?= esc($r[0]) ?></td>
                <td class="truncate max-w-[4.5rem]" title="<?= esc($r[1]) ?>"><?= esc($r[1]) ?></td>
                <td class="truncate max-w-[5rem]" title="<?= esc($r[2]) ?>"><?= esc($r[2]) ?></td>
                <td><span class="text-[10px] bg-slate-100 px-1 rounded"><?= esc($r[3]) ?></span></td>
                <td class="text-right text-gray-500 text-[10px] whitespace-nowrap"><?= esc($r[4]) ?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>

      <!-- 시스템 로그 + 주간 막대 -->
      <section class="xl:col-span-4 bg-white border border-gray-200 rounded shadow-sm overflow-hidden flex flex-col">
        <div class="px-2 py-1 border-b border-gray-200 bg-gray-50">
          <h2 class="text-[11px] font-bold text-gray-800"><i class="fa-solid fa-clock-rotate-left text-[#2b4c8c] mr-1"></i>최근 이벤트 로그</h2>
        </div>
        <ul class="flex-1 max-h-[140px] overflow-y-auto divide-y divide-gray-100 px-2 py-0.5">
          <?php foreach ($logRows as $L): ?>
          <li class="py-1 flex gap-2 text-[10px]">
            <span class="text-gray-400 font-mono shrink-0 w-8"><?= esc($L[0]) ?></span>
            <span class="shrink-0 w-12 text-center rounded bg-gray-100 text-gray-600"><?= esc($L[1]) ?></span>
            <span class="text-gray-700"><?= $L[2] ?></span>
          </li>
          <?php endforeach; ?>
        </ul>
        <div class="border-t border-gray-100 px-2 py-1.5 bg-gray-50/80">
          <div class="text-[10px] font-semibold text-gray-600 mb-1">주간 봉투 출고(천 장, 목업)</div>
          <div class="spark" title="주간 추이">
            <?php foreach ([40, 55, 48, 62, 58, 71, 65] as $h): ?>
            <span style="height: <?= (int) $h ?>%"></span>
            <?php endforeach; ?>
          </div>
          <div class="flex justify-between text-[9px] text-gray-400 mt-0.5">
            <span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span>토</span><span>일</span>
          </div>
        </div>
      </section>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-2 mb-2">
      <!-- 판매소 요약 -->
      <section class="bg-white border border-gray-200 rounded shadow-sm overflow-hidden">
        <div class="px-2 py-1 border-b border-gray-200 bg-gray-50 flex justify-between items-center">
          <h2 class="text-[11px] font-bold text-gray-800"><i class="fa-solid fa-store text-[#2b4c8c] mr-1"></i>지정판매소 요약</h2>
          <span class="text-[10px] text-gray-500">상위 5곳</span>
        </div>
        <table class="w-full dense-table">
          <thead>
            <tr>
              <th>판매소명</th>
              <th class="text-right">월 봉투(백장)</th>
              <th>상태</th>
              <th class="text-right">최종거래</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($storeSummary as $s): ?>
            <tr>
              <td class="font-medium"><?= esc($s[0]) ?></td>
              <td class="text-right tabular-nums"><?= esc($s[1]) ?></td>
              <td>
                <?php if ($s[2] === '정상'): ?>
                <span class="text-[10px] text-emerald-700"><?= esc($s[2]) ?></span>
                <?php else: ?>
                <span class="text-[10px] text-red-600"><?= esc($s[2]) ?></span>
                <?php endif; ?>
              </td>
              <td class="text-right text-gray-500"><?= esc($s[3]) ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </section>

      <!-- 승인 대기 + 요약 숫자 -->
      <section class="bg-white border border-gray-200 rounded shadow-sm overflow-hidden">
        <div class="px-2 py-1 border-b border-gray-200 bg-gray-50">
          <h2 class="text-[11px] font-bold text-gray-800"><i class="fa-solid fa-user-check text-[#2b4c8c] mr-1"></i>회원·판매소 승인 대기</h2>
        </div>
        <div class="grid grid-cols-3 gap-1 p-1.5 border-b border-gray-100 bg-gray-50/50 text-center">
          <div>
            <div class="text-lg font-bold text-[#2b4c8c]">4</div>
            <div class="text-[9px] text-gray-500">전체 대기</div>
          </div>
          <div>
            <div class="text-lg font-bold text-amber-600">2</div>
            <div class="text-[9px] text-gray-500">오늘 접수</div>
          </div>
          <div>
            <div class="text-lg font-bold text-gray-600">1.2일</div>
            <div class="text-[9px] text-gray-500">평균 처리</div>
          </div>
        </div>
        <table class="w-full dense-table">
          <thead>
            <tr>
              <th>신청자</th>
              <th>유형</th>
              <th>접수일</th>
              <th>메모</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($approvals as $a): ?>
            <tr>
              <td><?= esc($a[0]) ?></td>
              <td><?= esc($a[1]) ?></td>
              <td class="text-gray-600"><?= esc($a[2]) ?></td>
              <td class="text-gray-500 truncate max-w-[6rem]"><?= esc($a[3]) ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </section>
    </div>

    <!-- 하단: 비율 도넛 + 텍스트 브리핑 -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-2">
      <div class="bg-white border border-gray-200 rounded shadow-sm p-2 flex items-center gap-3">
        <div class="relative w-16 h-16 shrink-0 rounded-full" style="background: conic-gradient(#2b4c8c 0% 40%, #10b981 40% 70%, #f59e0b 70% 92%, #e5e7eb 92% 100%);">
          <div class="absolute inset-2 rounded-full bg-white flex items-center justify-center text-[10px] font-bold text-gray-700">비중</div>
        </div>
        <div class="text-[10px] text-gray-600 space-y-0.5">
          <div><span class="inline-block w-2 h-2 rounded-full bg-[#243a5e] mr-1"></span>일반 40%</div>
          <div><span class="inline-block w-2 h-2 rounded-full bg-emerald-500 mr-1"></span>스티커 30%</div>
          <div><span class="inline-block w-2 h-2 rounded-full bg-amber-500 mr-1"></span>대형/특수 22%</div>
        </div>
      </div>
      <div class="md:col-span-2 bg-white border border-gray-200 rounded shadow-sm p-2">
        <h3 class="text-[11px] font-bold text-gray-800 mb-1"><i class="fa-solid fa-clipboard-list text-[#2b4c8c] mr-1"></i>운영 브리핑 (목업)</h3>
        <ul class="text-[11px] text-gray-600 space-y-0.5 list-disc list-inside">
          <li>다음 주 예상 구매신청 <strong class="text-gray-900">약 28건</strong> (전주 대비 +12%)</li>
          <li><strong class="text-red-700">일반 20L</strong>·<strong class="text-red-700">특수규격 A</strong> 발주 권고 — 안전재고 미달</li>
          <li>세금계산서 <strong>6건</strong> 미발행 — 담당 회계에 알림 발송됨</li>
          <li>지정판매소 <strong>△△상회</strong> 연체 1건 — 현장 점검 일정 3/3</li>
        </ul>
      </div>
    </div>

    <p class="text-center text-[10px] text-gray-400 mt-2">
      레이아웃: <a href="<?= esc($dashClassic) ?>" class="text-[#2b4c8c] hover:underline">/dashboard</a>
      · <a href="<?= esc($dashModern) ?>" class="text-[#2b4c8c] hover:underline">/dashboard/modern</a>
      · <strong class="text-gray-600">/dashboard/dense</strong> (이 화면)
      · <a href="<?= esc($dashBlend) ?>" class="text-[#2b4c8c] hover:underline">/dashboard/blend</a>
      · <a href="<?= esc($dashCharts) ?>" class="text-[#2b4c8c] hover:underline">/dashboard/charts</a>
    </p>
  </main>
</body>
</html>
