<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>사용량 조회 · 주문 - 청춘약국</title>
    <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=Noto+Sans+KR:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-primary: #0f172a;
            --bg-secondary: #1e293b;
            --bg-card: #1e293b;
            --bg-card-hover: #334155;
            --border: #334155;
            --text-primary: #f1f5f9;
            --text-secondary: #94a3b8;
            --text-muted: #64748b;
            --accent-teal: #14b8a6;
            --accent-blue: #3b82f6;
            --accent-purple: #a855f7;
            --accent-amber: #f59e0b;
            --accent-emerald: #10b981;
            --accent-rose: #f43f5e;
            --accent-orange: #f97316;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            -webkit-font-smoothing: antialiased;
            min-height: 100vh;
        }

        /* ══════════════════ 헤더 ══════════════════ */
        .header {
            background: linear-gradient(135deg, #7c3aed 0%, #8b5cf6 50%, #a78bfa 100%);
            padding: 20px 24px;
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        }
        .header-inner {
            max-width: 1600px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header-left h1 {
            font-size: 22px;
            font-weight: 700;
            letter-spacing: -0.5px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .header-left p {
            font-size: 13px;
            opacity: 0.85;
            margin-top: 4px;
        }
        .header-nav {
            display: flex;
            gap: 8px;
        }
        .header-nav a {
            color: rgba(255,255,255,0.85);
            text-decoration: none;
            font-size: 13px;
            font-weight: 500;
            padding: 8px 14px;
            border-radius: 8px;
            background: rgba(255,255,255,0.1);
            transition: all 0.2s;
        }
        .header-nav a:hover {
            background: rgba(255,255,255,0.2);
            color: #fff;
        }

        /* ══════════════════ 컨텐츠 ══════════════════ */
        .content {
            max-width: 1600px;
            margin: 0 auto;
            padding: 24px;
        }

        /* ══════════════════ 검색 영역 ══════════════════ */
        .search-bar {
            background: var(--bg-card);
            border-radius: 16px;
            padding: 20px 24px;
            margin-bottom: 20px;
            border: 1px solid var(--border);
            display: flex;
            gap: 16px;
            flex-wrap: wrap;
            align-items: flex-end;
        }
        .search-group {
            display: flex;
            flex-direction: column;
            gap: 6px;
        }
        .search-group label {
            font-size: 11px;
            font-weight: 600;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .search-group input, .search-group select {
            padding: 10px 14px;
            background: var(--bg-primary);
            border: 1px solid var(--border);
            border-radius: 8px;
            font-size: 14px;
            font-family: inherit;
            color: var(--text-primary);
            min-width: 140px;
            transition: all 0.2s;
        }
        .search-group input[type="date"] {
            min-width: 160px;
        }
        .search-group input:focus, .search-group select:focus {
            outline: none;
            border-color: var(--accent-purple);
            box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.2);
        }
        .search-group input::placeholder { color: var(--text-muted); }
        .search-btn {
            background: linear-gradient(135deg, var(--accent-purple), #7c3aed);
            color: #fff;
            border: none;
            padding: 10px 28px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }
        .search-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(139, 92, 246, 0.4);
        }

        /* ══════════════════ 통계 카드 ══════════════════ */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 16px;
            margin-bottom: 24px;
        }
        .stat-card {
            background: var(--bg-card);
            border-radius: 14px;
            padding: 20px;
            border: 1px solid var(--border);
            position: relative;
            overflow: hidden;
        }
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
        }
        .stat-card.teal::before { background: var(--accent-teal); }
        .stat-card.blue::before { background: var(--accent-blue); }
        .stat-card.purple::before { background: var(--accent-purple); }
        .stat-card.amber::before { background: var(--accent-amber); }
        .stat-card.emerald::before { background: var(--accent-emerald); }
        .stat-card.orange::before { background: var(--accent-orange); }
        
        .stat-icon {
            font-size: 24px;
            margin-bottom: 12px;
        }
        .stat-value {
            font-size: 28px;
            font-weight: 700;
            letter-spacing: -1px;
            margin-bottom: 4px;
        }
        .stat-card.teal .stat-value { color: var(--accent-teal); }
        .stat-card.blue .stat-value { color: var(--accent-blue); }
        .stat-card.purple .stat-value { color: var(--accent-purple); }
        .stat-card.amber .stat-value { color: var(--accent-amber); }
        .stat-card.emerald .stat-value { color: var(--accent-emerald); }
        .stat-card.orange .stat-value { color: var(--accent-orange); }
        
        .stat-label {
            font-size: 12px;
            font-weight: 600;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        /* ══════════════════ 뷰 컨트롤 ══════════════════ */
        .view-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }
        .view-title {
            font-size: 16px;
            font-weight: 600;
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .view-actions {
            display: flex;
            gap: 8px;
        }
        .action-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .action-btn.primary {
            background: linear-gradient(135deg, var(--accent-emerald), var(--accent-teal));
            color: #fff;
        }
        .action-btn.primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
        }
        .action-btn.secondary {
            background: var(--bg-secondary);
            border: 1px solid var(--border);
            color: var(--text-secondary);
        }
        .action-btn.secondary:hover {
            border-color: var(--accent-purple);
            color: var(--accent-purple);
        }
        .action-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* ══════════════════ 테이블 ══════════════════ */
        .table-wrap {
            background: var(--bg-card);
            border-radius: 16px;
            border: 1px solid var(--border);
            overflow: hidden;
        }
        .usage-table {
            width: 100%;
            border-collapse: collapse;
        }
        .usage-table th {
            padding: 14px 16px;
            font-size: 11px;
            font-weight: 600;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            text-align: left;
            background: var(--bg-secondary);
            border-bottom: 1px solid var(--border);
            position: sticky;
            top: 0;
        }
        .usage-table th.center { text-align: center; }
        .usage-table th.right { text-align: right; }
        .usage-table td {
            padding: 14px 16px;
            font-size: 13px;
            border-bottom: 1px solid rgba(255,255,255,0.05);
            vertical-align: middle;
        }
        .usage-table tr:hover {
            background: rgba(255,255,255,0.02);
        }
        .usage-table tr.selected {
            background: rgba(139, 92, 246, 0.1);
        }

        /* 체크박스 */
        .check-col {
            width: 40px;
            text-align: center;
        }
        .custom-check {
            width: 20px;
            height: 20px;
            border: 2px solid var(--border);
            border-radius: 4px;
            cursor: pointer;
            appearance: none;
            background: var(--bg-primary);
            transition: all 0.2s;
        }
        .custom-check:checked {
            background: var(--accent-purple);
            border-color: var(--accent-purple);
        }
        .custom-check:checked::after {
            content: '✓';
            display: block;
            text-align: center;
            color: #fff;
            font-size: 12px;
            font-weight: bold;
            line-height: 16px;
        }

        /* 제품 셀 */
        .product-cell {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .product-thumb {
            width: 40px;
            height: 40px;
            object-fit: cover;
            border-radius: 8px;
            background: var(--bg-secondary);
            flex-shrink: 0;
        }
        .product-thumb-placeholder {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #2a2a3e 0%, #1e1e2e 100%);
            border-radius: 8px;
            flex-shrink: 0;
            border: 1px solid rgba(255,255,255,0.05);
        }
        .product-thumb-placeholder svg {
            width: 20px;
            height: 20px;
            opacity: 0.3;
            fill: #888;
        }
        .product-info {
            display: flex;
            flex-direction: column;
            gap: 2px;
            min-width: 0;
        }
        .product-name {
            font-weight: 600;
            color: var(--text-primary);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .product-code {
            font-family: 'JetBrains Mono', monospace;
            font-size: 11px;
            color: var(--text-muted);
        }

        /* 수량 관련 */
        .qty-cell {
            text-align: center;
            font-family: 'JetBrains Mono', monospace;
            font-weight: 600;
        }
        .qty-high { color: var(--accent-rose); }
        .qty-mid { color: var(--accent-amber); }
        .qty-low { color: var(--accent-emerald); }

        /* 주문 수량 입력 */
        .order-input {
            width: 70px;
            padding: 8px;
            background: var(--bg-primary);
            border: 1px solid var(--border);
            border-radius: 6px;
            font-size: 14px;
            font-family: 'JetBrains Mono', monospace;
            color: var(--text-primary);
            text-align: center;
        }
        .order-input:focus {
            outline: none;
            border-color: var(--accent-purple);
        }
        .order-input:disabled {
            opacity: 0.4;
        }

        /* 공급업체 뱃지 */
        .supplier-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 600;
            background: rgba(99, 102, 241, 0.2);
            color: #818cf8;
        }

        /* ══════════════════ 로딩/빈 상태 ══════════════════ */
        .loading-state, .empty-state {
            text-align: center;
            padding: 80px 20px;
            color: var(--text-muted);
        }
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 3px solid var(--border);
            border-top-color: var(--accent-purple);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 16px;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .empty-icon {
            font-size: 48px;
            margin-bottom: 16px;
        }

        /* ══════════════════ 주문 장바구니 ══════════════════ */
        .cart-drawer {
            position: fixed;
            right: 0;
            top: 0;
            bottom: 0;
            width: 400px;
            background: var(--bg-secondary);
            border-left: 1px solid var(--border);
            transform: translateX(100%);
            transition: transform 0.3s ease;
            z-index: 200;
            display: flex;
            flex-direction: column;
        }
        .cart-drawer.open {
            transform: translateX(0);
        }
        .cart-header {
            padding: 20px 24px;
            background: linear-gradient(135deg, var(--accent-orange), var(--accent-amber));
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .cart-header h2 {
            font-size: 18px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .cart-close {
            background: rgba(255,255,255,0.2);
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 8px;
            color: #fff;
            font-size: 18px;
            cursor: pointer;
        }
        .cart-body {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
        }
        .cart-item {
            background: var(--bg-card);
            border-radius: 12px;
            padding: 14px;
            margin-bottom: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .cart-item-info {
            flex: 1;
            min-width: 0;
        }
        .cart-item-name {
            font-size: 14px;
            font-weight: 600;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .cart-item-qty {
            font-size: 12px;
            color: var(--text-muted);
            margin-top: 4px;
        }
        .cart-item-remove {
            background: rgba(244, 63, 94, 0.2);
            border: none;
            color: var(--accent-rose);
            width: 28px;
            height: 28px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
        }
        .cart-footer {
            padding: 20px 24px;
            background: var(--bg-card);
            border-top: 1px solid var(--border);
        }
        .cart-summary {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }
        .cart-total-label {
            font-size: 14px;
            color: var(--text-secondary);
        }
        .cart-total-value {
            font-size: 24px;
            font-weight: 700;
            color: var(--accent-orange);
        }
        .cart-submit {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, var(--accent-orange), var(--accent-amber));
            border: none;
            border-radius: 10px;
            color: #fff;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.2s;
        }
        .cart-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(249, 115, 22, 0.4);
        }
        .cart-submit:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        /* ══════════════════ 장바구니 FAB ══════════════════ */
        .cart-fab {
            position: fixed;
            bottom: 32px;
            right: 32px;
            width: 64px;
            height: 64px;
            background: linear-gradient(135deg, var(--accent-orange), var(--accent-amber));
            border: none;
            border-radius: 20px;
            color: #fff;
            font-size: 28px;
            cursor: pointer;
            box-shadow: 0 8px 24px rgba(249, 115, 22, 0.4);
            transition: all 0.2s;
            z-index: 150;
        }
        .cart-fab:hover {
            transform: scale(1.05);
        }
        .cart-badge {
            position: absolute;
            top: -6px;
            right: -6px;
            width: 24px;
            height: 24px;
            background: var(--accent-rose);
            border-radius: 50%;
            font-size: 12px;
            font-weight: 700;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* ══════════════════ 토스트 ══════════════════ */
        .toast {
            position: fixed;
            bottom: 100px;
            left: 50%;
            transform: translateX(-50%) translateY(20px);
            padding: 14px 28px;
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 12px;
            color: var(--text-primary);
            font-size: 14px;
            font-weight: 500;
            box-shadow: 0 8px 32px rgba(0,0,0,0.3);
            opacity: 0;
            transition: all 0.3s;
            z-index: 300;
        }
        .toast.show {
            opacity: 1;
            transform: translateX(-50%) translateY(0);
        }
        .toast.success { border-color: var(--accent-emerald); }
        .toast.error { border-color: var(--accent-rose); }

        /* ══════════════════ 반응형 ══════════════════ */
        @media (max-width: 1200px) {
            .stats-grid { grid-template-columns: repeat(3, 1fr); }
        }
        @media (max-width: 768px) {
            .stats-grid { grid-template-columns: repeat(2, 1fr); }
            .header-nav { display: none; }
            .search-bar { flex-direction: column; }
            .search-group { width: 100%; }
            .search-group input, .search-group select { width: 100%; }
            .cart-drawer { width: 100%; }
            .view-controls { flex-direction: column; gap: 12px; }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-inner">
            <div class="header-left">
                <h1>📊 사용량 조회 · 주문</h1>
                <p>기간별 판매 사용량 분석 및 발주</p>
            </div>
            <nav class="header-nav">
                <a href="/admin">📊 대시보드</a>
                <a href="/admin/sales-pos">🧾 판매내역</a>
                <a href="/admin/products">📦 상품관리</a>
            </nav>
        </div>
    </div>

    <div class="content">
        <!-- 검색 -->
        <div class="search-bar">
            <div class="search-group">
                <label>시작일</label>
                <input type="date" id="startDate">
            </div>
            <div class="search-group">
                <label>종료일</label>
                <input type="date" id="endDate">
            </div>
            <div class="search-group">
                <label>검색어</label>
                <input type="text" id="searchInput" placeholder="상품명, 코드...">
            </div>
            <div class="search-group">
                <label>정렬</label>
                <select id="sortSelect">
                    <option value="qty_desc">사용량 많은순</option>
                    <option value="qty_asc">사용량 적은순</option>
                    <option value="name_asc">이름순</option>
                    <option value="amount_desc">금액 높은순</option>
                </select>
            </div>
            <button class="search-btn" onclick="loadUsageData()">🔍 조회</button>
        </div>

        <!-- 통계 -->
        <div class="stats-grid">
            <div class="stat-card purple">
                <div class="stat-icon">📅</div>
                <div class="stat-value" id="statPeriod">-</div>
                <div class="stat-label">조회 기간</div>
            </div>
            <div class="stat-card blue">
                <div class="stat-icon">📦</div>
                <div class="stat-value" id="statProducts">-</div>
                <div class="stat-label">판매 품목</div>
            </div>
            <div class="stat-card teal">
                <div class="stat-icon">🔢</div>
                <div class="stat-value" id="statTotalQty">-</div>
                <div class="stat-label">총 판매수량</div>
            </div>
            <div class="stat-card emerald">
                <div class="stat-icon">💰</div>
                <div class="stat-value" id="statTotalAmount">-</div>
                <div class="stat-label">총 매출액</div>
            </div>
            <div class="stat-card orange">
                <div class="stat-icon">🛒</div>
                <div class="stat-value" id="statCartCount">0</div>
                <div class="stat-label">주문 품목</div>
            </div>
        </div>

        <!-- 컨트롤 -->
        <div class="view-controls">
            <div class="view-title">
                <span>📋 품목별 사용량</span>
                <span id="resultCount" style="font-size:13px;color:var(--text-muted);font-weight:400;"></span>
            </div>
            <div class="view-actions">
                <button class="action-btn secondary" onclick="selectAll()">☑️ 전체 선택</button>
                <button class="action-btn secondary" onclick="selectNone()">⬜ 선택 해제</button>
                <button class="action-btn primary" onclick="addSelectedToCart()">🛒 선택 항목 장바구니 추가</button>
            </div>
        </div>

        <!-- 테이블 -->
        <div class="table-wrap">
            <table class="usage-table">
                <thead>
                    <tr>
                        <th class="check-col"><input type="checkbox" class="custom-check" id="checkAll" onchange="toggleCheckAll()"></th>
                        <th style="width:35%">상품</th>
                        <th>공급업체</th>
                        <th class="center">판매수량</th>
                        <th class="right">매출액</th>
                        <th class="center" style="width:100px">주문수량</th>
                    </tr>
                </thead>
                <tbody id="usageTableBody">
                    <tr>
                        <td colspan="6">
                            <div class="loading-state">
                                <div class="loading-spinner"></div>
                                <div>데이터 로딩 중...</div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 장바구니 FAB -->
    <button class="cart-fab" onclick="openCart()">
        🛒
        <span class="cart-badge" id="cartBadge" style="display:none;">0</span>
    </button>

    <!-- 장바구니 Drawer -->
    <div class="cart-drawer" id="cartDrawer">
        <div class="cart-header">
            <h2>🛒 주문 장바구니</h2>
            <button class="cart-close" onclick="closeCart()">✕</button>
        </div>
        <div class="cart-body" id="cartBody">
            <div class="empty-state">
                <div class="empty-icon">🛒</div>
                <div>장바구니가 비었습니다</div>
            </div>
        </div>
        <div class="cart-footer">
            <div class="cart-summary">
                <span class="cart-total-label">총 주문 품목</span>
                <span class="cart-total-value" id="cartTotalItems">0개</span>
            </div>
            <button class="cart-submit" id="submitOrderBtn" onclick="submitOrder()" disabled>
                📤 주문서 생성하기
            </button>
        </div>
    </div>

    <!-- 토스트 -->
    <div class="toast" id="toast"></div>

    <script>
    let usageData = [];
    let cart = [];  // { drug_code, product_name, supplier, qty }

    // 초기화
    document.addEventListener('DOMContentLoaded', function() {
        // 기본 날짜 설정 (오늘)
        const today = new Date();
        const todayStr = today.toISOString().split('T')[0];
        document.getElementById('startDate').value = todayStr;
        document.getElementById('endDate').value = todayStr;
        
        loadUsageData();
    });

    // ──────────────── 데이터 로드 ────────────────
    function loadUsageData() {
        const startDate = document.getElementById('startDate').value;
        const endDate = document.getElementById('endDate').value;
        const search = document.getElementById('searchInput').value;
        const sort = document.getElementById('sortSelect').value;

        document.getElementById('usageTableBody').innerHTML = `
            <tr><td colspan="6">
                <div class="loading-state">
                    <div class="loading-spinner"></div>
                    <div>데이터 로딩 중...</div>
                </div>
            </td></tr>`;

        let url = `/api/usage?start_date=${startDate}&end_date=${endDate}&sort=${sort}`;
        if (search) url += `&search=${encodeURIComponent(search)}`;

        fetch(url)
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    usageData = data.items;
                    
                    // 통계 업데이트
                    document.getElementById('statPeriod').textContent = data.stats.period_days + '일';
                    document.getElementById('statProducts').textContent = data.stats.product_count.toLocaleString();
                    document.getElementById('statTotalQty').textContent = data.stats.total_qty.toLocaleString();
                    document.getElementById('statTotalAmount').textContent = formatPrice(data.stats.total_amount);
                    document.getElementById('resultCount').textContent = `(${data.items.length}개)`;
                    
                    renderTable();
                } else {
                    document.getElementById('usageTableBody').innerHTML = `
                        <tr><td colspan="6">
                            <div class="empty-state">
                                <div class="empty-icon">⚠️</div>
                                <div>오류: ${data.error}</div>
                            </div>
                        </td></tr>`;
                }
            })
            .catch(err => {
                document.getElementById('usageTableBody').innerHTML = `
                    <tr><td colspan="6">
                        <div class="empty-state">
                            <div class="empty-icon">❌</div>
                            <div>데이터 로드 실패</div>
                        </div>
                    </td></tr>`;
            });
    }

    // ──────────────── 테이블 렌더링 ────────────────
    function renderTable() {
        const tbody = document.getElementById('usageTableBody');
        
        if (usageData.length === 0) {
            tbody.innerHTML = `
                <tr><td colspan="6">
                    <div class="empty-state">
                        <div class="empty-icon">📭</div>
                        <div>해당 기간 판매 내역이 없습니다</div>
                    </div>
                </td></tr>`;
            return;
        }

        tbody.innerHTML = usageData.map((item, idx) => {
            const qtyClass = item.total_qty >= 10 ? 'qty-high' : item.total_qty >= 5 ? 'qty-mid' : 'qty-low';
            const inCart = cart.find(c => c.drug_code === item.drug_code);
            
            return `
                <tr data-idx="${idx}" class="${inCart ? 'selected' : ''}">
                    <td class="check-col">
                        <input type="checkbox" class="custom-check item-check" data-idx="${idx}" ${inCart ? 'checked' : ''}>
                    </td>
                    <td>
                        <div class="product-cell">
                            ${item.thumbnail 
                                ? `<img src="data:image/jpeg;base64,${item.thumbnail}" class="product-thumb" alt="">`
                                : `<div class="product-thumb-placeholder"><svg viewBox="0 0 24 24"><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14zm-5-7l-3 3.72L9 13l-3 4h12l-4-5z"/></svg></div>`
                            }
                            <div class="product-info">
                                <span class="product-name">${escapeHtml(item.product_name)}</span>
                                <span class="product-code">${item.drug_code}</span>
                            </div>
                        </div>
                    </td>
                    <td>
                        ${item.supplier ? `<span class="supplier-badge">${escapeHtml(item.supplier)}</span>` : '<span style="color:var(--text-muted)">-</span>'}
                    </td>
                    <td class="qty-cell ${qtyClass}">${item.total_qty}</td>
                    <td style="text-align:right;font-family:'JetBrains Mono',monospace;">
                        ${formatPrice(item.total_amount)}원
                    </td>
                    <td style="text-align:center;">
                        <input type="number" class="order-input" 
                            data-idx="${idx}" 
                            min="0" 
                            value="${inCart ? inCart.qty : item.total_qty}"
                            placeholder="0">
                    </td>
                </tr>
            `;
        }).join('');
    }

    // ──────────────── 선택 ────────────────
    function toggleCheckAll() {
        const checked = document.getElementById('checkAll').checked;
        document.querySelectorAll('.item-check').forEach(cb => {
            cb.checked = checked;
            const row = cb.closest('tr');
            row.classList.toggle('selected', checked);
        });
    }

    function selectAll() {
        document.getElementById('checkAll').checked = true;
        toggleCheckAll();
    }

    function selectNone() {
        document.getElementById('checkAll').checked = false;
        toggleCheckAll();
    }

    // ──────────────── 장바구니 ────────────────
    function addSelectedToCart() {
        const checked = document.querySelectorAll('.item-check:checked');
        
        if (checked.length === 0) {
            showToast('선택된 품목이 없습니다', 'error');
            return;
        }

        let added = 0;
        checked.forEach(cb => {
            const idx = parseInt(cb.dataset.idx);
            const item = usageData[idx];
            const qtyInput = document.querySelector(`.order-input[data-idx="${idx}"]`);
            const qty = parseInt(qtyInput.value) || item.total_qty;
            
            if (qty > 0) {
                const existing = cart.find(c => c.drug_code === item.drug_code);
                if (existing) {
                    existing.qty = qty;
                } else {
                    cart.push({
                        drug_code: item.drug_code,
                        product_name: item.product_name,
                        supplier: item.supplier,
                        qty: qty
                    });
                    added++;
                }
            }
        });

        updateCartUI();
        renderTable();
        showToast(`${added}개 품목이 장바구니에 추가되었습니다`, 'success');
    }

    function removeFromCart(drugCode) {
        cart = cart.filter(c => c.drug_code !== drugCode);
        updateCartUI();
        renderTable();
    }

    function updateCartUI() {
        const badge = document.getElementById('cartBadge');
        const count = cart.length;
        
        badge.textContent = count;
        badge.style.display = count > 0 ? 'flex' : 'none';
        document.getElementById('statCartCount').textContent = count;
        document.getElementById('cartTotalItems').textContent = count + '개';
        document.getElementById('submitOrderBtn').disabled = count === 0;

        const body = document.getElementById('cartBody');
        if (count === 0) {
            body.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">🛒</div>
                    <div>장바구니가 비었습니다</div>
                </div>`;
        } else {
            body.innerHTML = cart.map(item => `
                <div class="cart-item">
                    <div class="cart-item-info">
                        <div class="cart-item-name">${escapeHtml(item.product_name)}</div>
                        <div class="cart-item-qty">${item.supplier || '-'} · ${item.qty}개</div>
                    </div>
                    <button class="cart-item-remove" onclick="removeFromCart('${item.drug_code}')">✕</button>
                </div>
            `).join('');
        }
    }

    function openCart() {
        document.getElementById('cartDrawer').classList.add('open');
    }

    function closeCart() {
        document.getElementById('cartDrawer').classList.remove('open');
    }

    // ──────────────── 주문 제출 ────────────────
    function submitOrder() {
        if (cart.length === 0) return;

        // 공급업체별 그룹화
        const bySupplier = {};
        cart.forEach(item => {
            const sup = item.supplier || '미지정';
            if (!bySupplier[sup]) bySupplier[sup] = [];
            bySupplier[sup].push(item);
        });

        // 주문서 텍스트 생성
        let orderText = `📦 청춘약국 발주서\n`;
        orderText += `━━━━━━━━━━━━━━━━━━━━\n`;
        orderText += `📅 작성일: ${new Date().toLocaleDateString('ko-KR')}\n\n`;

        Object.entries(bySupplier).forEach(([supplier, items]) => {
            orderText += `\n【 ${supplier} 】\n`;
            orderText += `─────────────────────\n`;
            items.forEach((item, i) => {
                orderText += `${i+1}. ${item.product_name}\n`;
                orderText += `   수량: ${item.qty}개\n`;
            });
        });

        orderText += `\n━━━━━━━━━━━━━━━━━━━━\n`;
        orderText += `총 ${cart.length}개 품목\n`;

        // 클립보드 복사
        navigator.clipboard.writeText(orderText).then(() => {
            showToast('주문서가 클립보드에 복사되었습니다!', 'success');
        }).catch(() => {
            // 폴백: textarea 사용
            const ta = document.createElement('textarea');
            ta.value = orderText;
            document.body.appendChild(ta);
            ta.select();
            document.execCommand('copy');
            document.body.removeChild(ta);
            showToast('주문서가 클립보드에 복사되었습니다!', 'success');
        });

        // TODO: API 연동시 서버로 전송
        // fetch('/api/orders', { method: 'POST', body: JSON.stringify({ items: cart }) });
    }

    // ──────────────── 유틸 ────────────────
    function formatPrice(num) {
        return new Intl.NumberFormat('ko-KR').format(num);
    }

    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
    }

    function showToast(message, type = 'info') {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.className = 'toast ' + type + ' show';
        setTimeout(() => toast.classList.remove('show'), 3000);
    }

    // 엔터키 검색
    document.getElementById('searchInput').addEventListener('keypress', e => {
        if (e.key === 'Enter') loadUsageData();
    });
    </script>
</body>
</html>
