<?php require_once __DIR__ . '/../layouts/header.php'; ?>

<div class="card page-header" style="margin-bottom: 2rem; display: flex; justify-content: space-between; align-items: center;">
    <div>
        <h3>Welcome to NexCore Pharma System</h3>
        <p style="color: var(--text-muted); margin-top: 0.5rem;">
            You are currently managing: <strong style="color: var(--primary-color);"><?php echo htmlspecialchars($branchName); ?></strong>
        </p>
    </div>
    
    <?php if ($_SESSION['role'] === 'admin'): ?>
    <div style="display: flex; align-items: center; gap: 1rem;" class="form-row">
        <label for="branchFilter" style="color: var(--text-muted); font-weight: 500;">Filter by Branch:</label>
        <select id="branchFilter" onchange="filterDashboard()" style="padding: 0.5rem 1rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; min-width: 200px;">
            <option value="all" <?php echo ($selectedBranch === 'all') ? 'selected' : ''; ?>>All Branches</option>
            <?php foreach($branches as $b): ?>
                <option value="<?php echo $b['id']; ?>" <?php echo ($selectedBranch == $b['id']) ? 'selected' : ''; ?> style="background: var(--bg-dark);">
                    <?php echo htmlspecialchars($b['name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <?php endif; ?>
</div>

<style>
.kpi-card {
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    border: 1px solid var(--glass-border) !important;
}
.kpi-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
    border-color: rgba(79, 70, 229, 0.4) !important;
}
.kpi-card.active {
    border-color: var(--primary-color) !important;
    background: rgba(79, 70, 229, 0.15) !important;
    box-shadow: 0 0 15px rgba(79, 70, 229, 0.3);
}
#expiringSoonTable th, #expiringSoonTable td,
#expiredItemsTable th, #expiredItemsTable td {
    white-space: nowrap;
}
#expiringSoonTable td:nth-child(1), #expiredItemsTable td:nth-child(1) {
    white-space: normal; /* Allow medicine details to wrap */
}
.notes-cell {
    white-space: normal !important;
    max-width: 100%;
}
.notes-highlight {
    background: rgba(56, 189, 248, 0.1);
    color: #38bdf8;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.85rem;
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    max-width: 100%;
    cursor: pointer;
    border: 1px solid rgba(56, 189, 248, 0.2);
}
.notes-highlight .note-text {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>

<div class="dashboard-grid" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 1.5rem;">
    <div class="card kpi-card" id="kpi-expiring-card" onclick="toggleKpiTab('expiring')">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; flex-wrap: wrap; gap: 0.25rem;">
            <h4 style="color: var(--text-muted); margin: 0;">Expiring Soon</h4>
            <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 500; background: rgba(255, 255, 255, 0.05); padding: 0.15rem 0.4rem; border-radius: 4px; border: 1px solid rgba(255,255,255,0.03);">As of today</span>
        </div>
        <h2 style="color: #fb7185;"><?php echo isset($expiringSoonCount) ? intval($expiringSoonCount) : 0; ?> Items</h2>
    </div>
    <div class="card kpi-card" id="kpi-expired-card" onclick="toggleKpiTab('expired')">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; flex-wrap: wrap; gap: 0.25rem;">
            <h4 style="color: var(--text-muted); margin: 0;">Expired Items</h4>
            <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 500; background: rgba(255, 255, 255, 0.05); padding: 0.15rem 0.4rem; border-radius: 4px; border: 1px solid rgba(255,255,255,0.03);">As of today</span>
        </div>
        <h2 style="color: #ef4444;"><?php echo isset($expiredCount) ? intval($expiredCount) : 0; ?> Items</h2>
    </div>
    <div class="card kpi-card" id="kpi-returned-card" onclick="toggleKpiTab('returned')">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; flex-wrap: wrap; gap: 0.25rem;">
            <h4 style="color: var(--text-muted); margin: 0;">Returned Items</h4>
            <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 500; background: rgba(255, 255, 255, 0.05); padding: 0.15rem 0.4rem; border-radius: 4px; border: 1px solid rgba(255,255,255,0.03);">As of today</span>
        </div>
        <h2 style="color: #a855f7;"><?php echo isset($returnedCount) ? intval($returnedCount) : 0; ?> Items</h2>
    </div>
</div>

<!-- Tabular view: Expiring Soon -->
<div id="expiringTableContainer" class="card" style="display: none; margin-top: 2rem; animation: slideUp 0.3s ease;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; border-bottom: 1px solid var(--glass-border); padding-bottom: 0.5rem; flex-wrap: wrap; gap: 1rem;">
        <h3 style="color: #ef4444; display: flex; align-items: center; gap: 0.5rem; margin: 0; border: none; padding: 0;">
            <i class="ph ph-warning-octagon"></i> Expiring Soon Items
        </h3>
        
        <div style="display: flex; gap: 0.75rem; align-items: center; flex-wrap: wrap; flex: 1; justify-content: flex-end; min-width: 200px;">
            <input type="text" id="searchExpiringTableInput" onkeyup="filterExpiringTableBySearch()" placeholder="Search Name or Batch..." style="padding: 0.5rem 1rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; flex: 1; min-width: 150px; color-scheme: dark;">
            <button type="button" onclick="exportExpiringTableToCSV()" class="btn-primary" style="margin: 0; padding: 0.5rem 1rem; font-size: 0.95rem; width: auto; display: flex; align-items: center; gap: 0.5rem; white-space: nowrap;">
                <i class="ph ph-download-simple"></i> Export Data
            </button>
        </div>
    </div>
    <div id="expiringSoonTable" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1rem;">
        <?php foreach($expiringSoonRecords as $rec): ?>
        <div class="card grid-card expiring-batch-row" style="padding: 1.5rem; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.4); border-radius: 12px; position: relative;">
            <div style="margin-bottom: 1rem; border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 0.75rem; display: flex; justify-content: space-between; align-items: flex-start;">
                <div>
                    <strong style="font-size: 1.1rem; color: white;">
                        <?php echo htmlspecialchars($rec['medicine_name']); ?>
                        <?php if (!empty($rec['item_code'])): ?>
                            <span class="item-code" style="background: rgba(56, 189, 248, 0.15); color: #38bdf8; padding: 0.15rem 0.4rem; border-radius: 4px; font-size: 0.85rem; margin-left: 0.5rem; vertical-align: middle;">
                                <?php echo htmlspecialchars($rec['item_code']); ?>
                            </span>
                        <?php endif; ?>
                    </strong>
                    <?php if (!empty($rec['generic_name'])): ?>
                        <br><small style="color: var(--text-muted);"><?php echo htmlspecialchars($rec['generic_name']); ?></small>
                    <?php endif; ?>
                </div>
                <button type="button" onclick="openReturnModal(<?php echo $rec['id']; ?>)" style="background: rgba(245, 158, 11, 0.1); border: 1px solid rgba(245, 158, 11, 0.3); color: #f59e0b; padding: 0.2rem 0.6rem; border-radius: 4px; font-size: 0.8rem; cursor: pointer; transition: all 0.3s ease; white-space: nowrap;">
                    <i class="ph ph-arrow-u-up-left"></i> Return
                </button>
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; margin-bottom: 1rem; font-size: 0.9rem;">
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Batch Number</span>
                    <strong style="color: #c084fc;"><?php echo htmlspecialchars($rec['batch_number']); ?></strong>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Branch</span>
                    <span><?php echo htmlspecialchars($rec['branch_name']); ?></span>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Quantity</span>
                    <span><?php echo intval($rec['quantity']); ?></span>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Notify Days</span>
                    <span><?php echo intval($rec['expiry_alert_days']); ?></span>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Expiry Date</span>
                    <strong style="color: #ef4444;"><?php echo htmlspecialchars($rec['expiry_date']); ?></strong>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Days Remaining</span>
                    <span>
                        <?php if (intval($rec['days_left']) === 0): ?>
                            <span style="background: rgba(239, 68, 68, 0.15); color: #ef4444; padding: 0.15rem 0.4rem; border-radius: 4px; font-weight: 500; font-size: 0.8rem;">Expire Today</span>
                        <?php else: ?>
                            <span style="background: rgba(249, 115, 22, 0.15); color: #f97316; padding: 0.15rem 0.4rem; border-radius: 4px; font-weight: 500; font-size: 0.8rem;"><?php echo \App\Utils\DateFormatter::formatDaysFriendly($rec['days_left']); ?> left</span>
                        <?php endif; ?>
                    </span>
                </div>
            </div>

            <div class="notes-cell" style="margin-top: auto; padding-top: 0.75rem; border-top: 1px solid rgba(255,255,255,0.05);">
                <span style="color: var(--text-muted); display: block; font-size: 0.8rem; margin-bottom: 0.25rem;">Notes</span>
                <?php if (!empty($rec['notes'])): ?>
                    <span class="notes-highlight" title="<?php echo htmlspecialchars($rec['notes']); ?>" data-note="<?php echo htmlspecialchars($rec['notes']); ?>" onclick="showSmartNoteInfo(this.getAttribute('data-note'))">
                        <i class="ph ph-note"></i> <span class="note-text"><?php echo htmlspecialchars($rec['notes']); ?></span>
                    </span>
                <?php else: ?>
                    <span style="color: var(--text-muted);">-</span>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
        
        <div id="noExpiringBatchesRow" style="display: <?php echo empty($expiringSoonRecords) ? '' : 'none'; ?>; grid-column: 1 / -1; padding: 2rem; text-align: center; color: var(--text-muted); background: rgba(15,23,42,0.4); border-radius: 12px; border: 1px dashed var(--glass-border);">
            No expiring soon items found.
        </div>
    </div>
    <div id="expiringLoadMoreContainer" style="text-align: center; margin-top: 1.5rem; display: <?php echo $expiringSoonCount > 20 ? 'block' : 'none'; ?>;">
        <button type="button" id="btnExpiringLoadMore" onclick="loadMoreExpiring()" class="btn-primary" style="width: auto; padding: 0.6rem 2rem; font-size: 0.95rem; background: rgba(79, 70, 229, 0.2); border: 1px solid rgba(79, 70, 229, 0.4); color: var(--primary-color);">Load More</button>
    </div>
</div>

<!-- Tabular view: Expired Items -->
<div id="expiredTableContainer" class="card" style="display: none; margin-top: 2rem; animation: slideUp 0.3s ease;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; border-bottom: 1px solid var(--glass-border); padding-bottom: 0.5rem; flex-wrap: wrap; gap: 1rem;">
        <h3 style="color: #ef4444; display: flex; align-items: center; gap: 0.5rem; margin: 0; border: none; padding: 0;">
            <i class="ph ph-x-circle"></i> Expired Items
        </h3>
        <div style="display: flex; gap: 0.75rem; align-items: center; flex-wrap: wrap; flex: 1; justify-content: flex-end; min-width: 200px;">
            <input type="text" id="searchExpiredTableInput" onkeyup="filterExpiredTableBySearch()" placeholder="Search Name or Batch..." style="padding: 0.5rem 1rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; flex: 1; min-width: 150px; color-scheme: dark;">
            <button type="button" onclick="exportExpiredTableToCSV()" class="btn-primary" style="margin: 0; padding: 0.5rem 1rem; font-size: 0.95rem; width: auto; display: flex; align-items: center; gap: 0.5rem; white-space: nowrap;">
                <i class="ph ph-download-simple"></i> Export Data
            </button>
        </div>
    </div>
    <div id="expiredItemsTable" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1rem;">
        <?php foreach($expiredRecords as $rec): ?>
        <div class="card grid-card expired-batch-row" style="padding: 1.5rem; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.4); border-radius: 12px; position: relative;">
            <div style="margin-bottom: 1rem; border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 0.75rem;">
                <strong style="font-size: 1.1rem; color: white;">
                        <?php echo htmlspecialchars($rec['medicine_name']); ?>
                        <?php if (!empty($rec['item_code'])): ?>
                            <span class="item-code" style="background: rgba(56, 189, 248, 0.15); color: #38bdf8; padding: 0.15rem 0.4rem; border-radius: 4px; font-size: 0.85rem; margin-left: 0.5rem; vertical-align: middle;">
                                <?php echo htmlspecialchars($rec['item_code']); ?>
                            </span>
                        <?php endif; ?>
                    </strong>
                <?php if (!empty($rec['generic_name'])): ?>
                    <br><small style="color: var(--text-muted);"><?php echo htmlspecialchars($rec['generic_name']); ?></small>
                <?php endif; ?>
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; margin-bottom: 1rem; font-size: 0.9rem;">
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Batch Number</span>
                    <strong style="color: #c084fc;"><?php echo htmlspecialchars($rec['batch_number']); ?></strong>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Branch</span>
                    <span><?php echo htmlspecialchars($rec['branch_name']); ?></span>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Quantity</span>
                    <span><?php echo intval($rec['quantity']); ?></span>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Days Overdue</span>
                    <span>
                        <span style="background: rgba(239, 68, 68, 0.15); color: #ef4444; padding: 0.15rem 0.4rem; border-radius: 4px; font-weight: 500; font-size: 0.8rem;">
                            <?php echo \App\Utils\DateFormatter::formatDaysFriendly($rec['days_expired']); ?>
                        </span>
                    </span>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Expiry Date</span>
                    <strong style="color: #ef4444;"><?php echo htmlspecialchars($rec['expiry_date']); ?></strong>
                </div>
            </div>

            <div class="notes-cell" style="margin-top: auto; padding-top: 0.75rem; border-top: 1px solid rgba(255,255,255,0.05);">
                <span style="color: var(--text-muted); display: block; font-size: 0.8rem; margin-bottom: 0.25rem;">Notes</span>
                <?php if (!empty($rec['notes'])): ?>
                    <span class="notes-highlight" title="<?php echo htmlspecialchars($rec['notes']); ?>" data-note="<?php echo htmlspecialchars($rec['notes']); ?>" onclick="showSmartNoteInfo(this.getAttribute('data-note'))">
                        <i class="ph ph-note"></i> <span class="note-text"><?php echo htmlspecialchars($rec['notes']); ?></span>
                    </span>
                <?php else: ?>
                    <span style="color: var(--text-muted);">-</span>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
        
        <div id="noExpiredBatchesRow" style="display: <?php echo empty($expiredRecords) ? '' : 'none'; ?>; grid-column: 1 / -1; padding: 2rem; text-align: center; color: var(--text-muted); background: rgba(15,23,42,0.4); border-radius: 12px; border: 1px dashed var(--glass-border);">
            No expired items found.
        </div>
    </div>
    <div id="expiredLoadMoreContainer" style="text-align: center; margin-top: 1.5rem; display: <?php echo $expiredCount > 20 ? 'block' : 'none'; ?>;">
        <button type="button" id="btnExpiredLoadMore" onclick="loadMoreExpired()" class="btn-primary" style="width: auto; padding: 0.6rem 2rem; font-size: 0.95rem; background: rgba(79, 70, 229, 0.2); border: 1px solid rgba(79, 70, 229, 0.4); color: var(--primary-color);">Load More</button>
    </div>
</div>

<!-- Tabular view: Returned Items -->
<div id="returnedTableContainer" class="card" style="display: none; margin-top: 2rem; animation: slideUp 0.3s ease;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; border-bottom: 1px solid var(--glass-border); padding-bottom: 0.5rem; flex-wrap: wrap; gap: 1rem;">
        <h3 style="color: #a855f7; display: flex; align-items: center; gap: 0.5rem; margin: 0; border: none; padding: 0;">
            <i class="ph ph-arrow-u-up-left"></i> Returned Items
        </h3>
        <div style="display: flex; gap: 0.75rem; align-items: center; flex-wrap: wrap; flex: 1; justify-content: flex-end; min-width: 200px;">
            <input type="text" id="searchReturnedTableInput" onkeyup="filterReturnedTableBySearch()" placeholder="Search Name or Batch..." style="padding: 0.5rem 1rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; flex: 1; min-width: 150px; color-scheme: dark;">
            <button type="button" onclick="exportReturnedTableToCSV()" class="btn-primary" style="margin: 0; padding: 0.5rem 1rem; font-size: 0.95rem; width: auto; display: flex; align-items: center; gap: 0.5rem; white-space: nowrap;">
                <i class="ph ph-download-simple"></i> Export Data
            </button>
        </div>
    </div>
    <div id="returnedItemsTable" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1rem;">
        <?php foreach($returnedRecords as $rec): ?>
        <div class="card grid-card expired-batch-row" style="padding: 1.5rem; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.4); border-radius: 12px; position: relative;">
            <div style="margin-bottom: 1rem; border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 0.75rem;">
                <strong style="font-size: 1.1rem; color: white;">
                        <?php echo htmlspecialchars($rec['medicine_name']); ?>
                        <?php if (!empty($rec['item_code'])): ?>
                            <span class="item-code" style="background: rgba(56, 189, 248, 0.15); color: #38bdf8; padding: 0.15rem 0.4rem; border-radius: 4px; font-size: 0.85rem; margin-left: 0.5rem; vertical-align: middle;">
                                <?php echo htmlspecialchars($rec['item_code']); ?>
                            </span>
                        <?php endif; ?>
                    </strong>
                <?php if (!empty($rec['generic_name'])): ?>
                    <br><small style="color: var(--text-muted);"><?php echo htmlspecialchars($rec['generic_name']); ?></small>
                <?php endif; ?>
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; margin-bottom: 1rem; font-size: 0.9rem;">
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Batch Number</span>
                    <strong style="color: #c084fc;"><?php echo htmlspecialchars($rec['batch_number']); ?></strong>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Branch</span>
                    <span><?php echo htmlspecialchars($rec['branch_name']); ?></span>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Quantity Returned</span>
                    <span><?php echo intval($rec['quantity']); ?></span>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Returned Date</span>
                    <strong style="color: #a855f7;"><?php echo date('Y-m-d', strtotime($rec['expiry_date'])); ?></strong>
                </div>
            </div>

            <div class="notes-cell" style="margin-top: auto; padding-top: 0.75rem; border-top: 1px solid rgba(255,255,255,0.05);">
                <span style="color: var(--text-muted); display: block; font-size: 0.8rem; margin-bottom: 0.25rem;">Reason</span>
                <?php if (!empty($rec['notes'])): ?>
                    <span class="notes-highlight" title="<?php echo htmlspecialchars($rec['notes']); ?>" data-note="<?php echo htmlspecialchars($rec['notes']); ?>" onclick="showSmartNoteInfo(this.getAttribute('data-note'))">
                        <i class="ph ph-note"></i> <span class="note-text"><?php echo htmlspecialchars($rec['notes']); ?></span>
                    </span>
                <?php else: ?>
                    <span style="color: var(--text-muted);">-</span>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
        
        <div id="noReturnedBatchesRow" style="display: <?php echo empty($returnedRecords) ? '' : 'none'; ?>; grid-column: 1 / -1; padding: 2rem; text-align: center; color: var(--text-muted); background: rgba(15,23,42,0.4); border-radius: 12px; border: 1px dashed var(--glass-border);">
            No returned items found.
        </div>
    </div>
    <div id="returnedLoadMoreContainer" style="text-align: center; margin-top: 1.5rem; display: <?php echo $returnedCount > 20 ? 'block' : 'none'; ?>;">
        <button type="button" id="btnReturnedLoadMore" onclick="loadMoreReturned()" class="btn-primary" style="width: auto; padding: 0.6rem 2rem; font-size: 0.95rem; background: rgba(79, 70, 229, 0.2); border: 1px solid rgba(79, 70, 229, 0.4); color: var(--primary-color);">Load More</button>
    </div>
</div>
</div>

<!-- Modals -->
<div id="returnModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; justify-content: center; align-items: center; backdrop-filter: blur(5px);">
    <div class="card" style="width: 90%; max-width: 400px; box-sizing: border-box; animation: slideUp 0.3s ease;">
        <h3 style="margin-bottom: 1rem; border-bottom: 1px solid var(--glass-border); padding-bottom: 0.5rem; color: #ef4444;">Return Item</h3>
        <form id="returnForm" method="POST" action="">
            <div class="input-group" style="margin-bottom: 1rem;">
                <label for="return_comment">Comments / Reason</label>
                <textarea id="return_comment" name="return_comment" rows="3" required style="width: 100%; padding: 0.75rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; font-family: 'Inter', sans-serif;" placeholder="e.g. Returned to supplier due to expiration..."></textarea>
            </div>
            <div style="display: flex; gap: 1rem; margin-top: 1.5rem;">
                <button type="button" class="btn-primary" style="flex: 1; background: transparent; border: 1px solid var(--glass-border); margin-top: 0; color: white;" onclick="closeReturnModal()">Cancel</button>
                <button type="submit" class="btn-primary" style="flex: 1; margin-top: 0; background: #ef4444;">Confirm Return</button>
            </div>
        </form>
    </div>
</div>

<script>
let expiringPage = 1;
let expiredPage = 1;

function openReturnModal(batchId) {
    document.getElementById('returnForm').action = '/inventory/returnBatch/' + batchId;
    document.getElementById('returnModal').style.display = 'flex';
}

function closeReturnModal() {
    document.getElementById('returnModal').style.display = 'none';
    document.getElementById('return_comment').value = '';
}

window.addEventListener('click', function(event) {
    if (event.target == document.getElementById('returnModal')) {
        closeReturnModal();
    }
});

async function loadMoreExpiring() {
    expiringPage++;
    const btn = document.getElementById('btnExpiringLoadMore');
    btn.disabled = true;
    btn.textContent = 'Loading...';
    
    const branchEl = document.getElementById('branchFilter');
    const branchId = branchEl ? branchEl.value : '<?php echo htmlspecialchars($selectedBranch); ?>';
    const searchInput = document.getElementById('searchExpiringTableInput').value;
    
    try {
        const response = await fetch(`/dashboard/expiringSoon?branch_id=${branchId}&search=${encodeURIComponent(searchInput)}&page=${expiringPage}`);
        const data = await response.json();
        
        if (data.html) {
            document.querySelector('#expiringSoonTable').insertAdjacentHTML('beforeend', data.html);
        }
        
        if (!data.hasMore) {
            document.getElementById('expiringLoadMoreContainer').style.display = 'none';
        }
    } catch (e) {
        console.error(e);
    } finally {
        btn.disabled = false;
        btn.textContent = 'Load More';
    }
}

async function loadMoreExpired() {
    expiredPage++;
    const btn = document.getElementById('btnExpiredLoadMore');
    btn.disabled = true;
    btn.textContent = 'Loading...';
    
    const branchEl = document.getElementById('branchFilter');
    const branchId = branchEl ? branchEl.value : '<?php echo htmlspecialchars($selectedBranch); ?>';
    const searchInput = document.getElementById('searchExpiredTableInput').value;
    
    try {
        const response = await fetch(`/dashboard/expiredItems?branch_id=${branchId}&search=${encodeURIComponent(searchInput)}&page=${expiredPage}`);
        const data = await response.json();
        
        if (data.html) {
            document.querySelector('#expiredItemsTable').insertAdjacentHTML('beforeend', data.html);
        }
        
        if (!data.hasMore) {
            document.getElementById('expiredLoadMoreContainer').style.display = 'none';
        }
    } catch (e) {
        console.error(e);
    } finally {
        btn.disabled = false;
        btn.textContent = 'Load More';
    }
}

let searchExpiredTimeout = null;
function filterExpiredTableBySearch() {
    clearTimeout(searchExpiredTimeout);
    searchExpiredTimeout = setTimeout(async () => {
        expiredPage = 1;
        const searchInput = document.getElementById('searchExpiredTableInput').value;
        const branchEl = document.getElementById('branchFilter');
        const branchId = branchEl ? branchEl.value : '<?php echo htmlspecialchars($selectedBranch); ?>';
        
        try {
            const response = await fetch(`/dashboard/expiredItems?branch_id=${branchId}&search=${encodeURIComponent(searchInput)}&page=1`);
            const data = await response.json();
            
            const tbody = document.querySelector('#expiredItemsTable');
            if (data.html) {
                tbody.innerHTML = data.html;
            } else {
                tbody.innerHTML = '<div id="noExpiredBatchesRow" style="grid-column: 1 / -1; padding: 2rem; text-align: center; color: var(--text-muted); background: rgba(15,23,42,0.4); border-radius: 12px; border: 1px dashed var(--glass-border);">No expired items found.</div>';
            }
            
            document.getElementById('expiredLoadMoreContainer').style.display = data.hasMore ? 'block' : 'none';
        } catch (e) {
            console.error(e);
        }
    }, 300);
}

function exportExpiredTableToCSV() {
    const searchInput = document.getElementById('searchExpiredTableInput').value;
    const branchEl = document.getElementById('branchFilter');
    const branchId = branchEl ? branchEl.value : 'all';
    
    window.location.href = `/dashboard/exportExpiredItems?branch_id=${branchId}&search=${encodeURIComponent(searchInput)}`;
}

let searchExpiringTimeout = null;
function filterExpiringTableBySearch() {
    clearTimeout(searchExpiringTimeout);
    searchExpiringTimeout = setTimeout(async () => {
        expiringPage = 1;
        const searchInput = document.getElementById('searchExpiringTableInput').value;
        const branchEl = document.getElementById('branchFilter');
        const branchId = branchEl ? branchEl.value : '<?php echo htmlspecialchars($selectedBranch); ?>';
        
        try {
            const response = await fetch(`/dashboard/expiringSoon?branch_id=${branchId}&search=${encodeURIComponent(searchInput)}&page=1`);
            const data = await response.json();
            
            const tbody = document.querySelector('#expiringSoonTable');
            if (data.html) {
                tbody.innerHTML = data.html;
            } else {
                tbody.innerHTML = '<div id="noExpiringBatchesRow" style="grid-column: 1 / -1; padding: 2rem; text-align: center; color: var(--text-muted); background: rgba(15,23,42,0.4); border-radius: 12px; border: 1px dashed var(--glass-border);">No expiring soon items found.</div>';
            }
            
            document.getElementById('expiringLoadMoreContainer').style.display = data.hasMore ? 'block' : 'none';
        } catch (e) {
            console.error(e);
        }
    }, 300);
}

function exportExpiringTableToCSV() {
    const searchInput = document.getElementById('searchExpiringTableInput').value;
    const branchEl = document.getElementById('branchFilter');
    const branchId = branchEl ? branchEl.value : 'all';
    
    window.location.href = `/dashboard/exportExpiringSoonItems?branch_id=${branchId}&search=${encodeURIComponent(searchInput)}`;
}

let returnedPage = 1;
async function loadMoreReturned() {
    returnedPage++;
    const btn = document.getElementById('btnReturnedLoadMore');
    btn.disabled = true;
    btn.textContent = 'Loading...';
    
    const branchEl = document.getElementById('branchFilter');
    const branchId = branchEl ? branchEl.value : '<?php echo htmlspecialchars($selectedBranch); ?>';
    const searchInput = document.getElementById('searchReturnedTableInput').value;
    
    try {
        const response = await fetch(`/dashboard/returnedItems?branch_id=${branchId}&search=${encodeURIComponent(searchInput)}&page=${returnedPage}`);
        const data = await response.json();
        
        if (data.html) {
            document.querySelector('#returnedItemsTable').insertAdjacentHTML('beforeend', data.html);
        }
        
        if (!data.hasMore) {
            document.getElementById('returnedLoadMoreContainer').style.display = 'none';
        }
    } catch (e) {
        console.error(e);
    } finally {
        btn.disabled = false;
        btn.textContent = 'Load More';
    }
}

let searchReturnedTimeout = null;
function filterReturnedTableBySearch() {
    clearTimeout(searchReturnedTimeout);
    searchReturnedTimeout = setTimeout(async () => {
        returnedPage = 1;
        const searchInput = document.getElementById('searchReturnedTableInput').value;
        const branchEl = document.getElementById('branchFilter');
        const branchId = branchEl ? branchEl.value : '<?php echo htmlspecialchars($selectedBranch); ?>';
        
        try {
            const response = await fetch(`/dashboard/returnedItems?branch_id=${branchId}&search=${encodeURIComponent(searchInput)}&page=1`);
            const data = await response.json();
            
            const tbody = document.querySelector('#returnedItemsTable');
            if (data.html) {
                tbody.innerHTML = data.html;
            } else {
                tbody.innerHTML = '<div id="noReturnedBatchesRow" style="grid-column: 1 / -1; padding: 2rem; text-align: center; color: var(--text-muted); background: rgba(15,23,42,0.4); border-radius: 12px; border: 1px dashed var(--glass-border);">No returned items found.</div>';
            }
            
            document.getElementById('returnedLoadMoreContainer').style.display = data.hasMore ? 'block' : 'none';
        } catch (e) {
            console.error(e);
        }
    }, 300);
}

function exportReturnedTableToCSV() {
    const searchInput = document.getElementById('searchReturnedTableInput').value;
    const branchEl = document.getElementById('branchFilter');
    const branchId = branchEl ? branchEl.value : 'all';
    
    window.location.href = `/dashboard/exportReturnedItems?branch_id=${branchId}&search=${encodeURIComponent(searchInput)}`;
}

function toggleKpiTab(type) {
    const expiringCard = document.getElementById('kpi-expiring-card');
    const expiredCard = document.getElementById('kpi-expired-card');
    const returnedCard = document.getElementById('kpi-returned-card');
    
    const expiringContainer = document.getElementById('expiringTableContainer');
    const expiredContainer = document.getElementById('expiredTableContainer');
    const returnedContainer = document.getElementById('returnedTableContainer');
    
    let isCurrentlyActive = false;
    if (type === 'expiring') isCurrentlyActive = expiringCard.classList.contains('active');
    else if (type === 'expired') isCurrentlyActive = expiredCard.classList.contains('active');
    else if (type === 'returned') isCurrentlyActive = returnedCard.classList.contains('active');
    
    // Reset all highlights
    expiringCard.classList.remove('active');
    expiredCard.classList.remove('active');
    if (returnedCard) returnedCard.classList.remove('active');
    
    // Hide all containers
    expiringContainer.style.display = 'none';
    expiredContainer.style.display = 'none';
    if (returnedContainer) returnedContainer.style.display = 'none';
    
    if (!isCurrentlyActive) {
        if (type === 'expiring') {
            expiringCard.classList.add('active');
            expiringContainer.style.display = 'block';
            setTimeout(() => expiringContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' }), 100);
        } else if (type === 'expired') {
            expiredCard.classList.add('active');
            expiredContainer.style.display = 'block';
            setTimeout(() => expiredContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' }), 100);
        } else if (type === 'returned') {
            if (returnedCard) returnedCard.classList.add('active');
            if (returnedContainer) {
                returnedContainer.style.display = 'block';
                setTimeout(() => returnedContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' }), 100);
            }
        }
    }
}

function filterDashboard() {
    const branchEl = document.getElementById('branchFilter');
    const branchId = branchEl ? branchEl.value : '<?php echo htmlspecialchars($selectedBranch); ?>';
    
    const expiryAfterEl = document.getElementById('expiryAfterFilter');
    const expiryAfter = expiryAfterEl ? expiryAfterEl.value : '';
    
    // Determine active KPI tab to preserve it on reload
    const expiringCard = document.getElementById('kpi-expiring-card');
    const expiredCard = document.getElementById('kpi-expired-card');
    const returnedCard = document.getElementById('kpi-returned-card');
    let activeTab = '';
    if (expiringCard.classList.contains('active')) activeTab = 'expiring';
    else if (expiredCard.classList.contains('active')) activeTab = 'expired';
    else if (returnedCard && returnedCard.classList.contains('active')) activeTab = 'returned';
    
    window.location.href = '?branch_id=' + branchId + 
                           '&expiry_after=' + expiryAfter + 
                           (activeTab ? '&active_tab=' + activeTab : '');
}

function clearExpiryFilter() {
    const branchEl = document.getElementById('branchFilter');
    const branchId = branchEl ? branchEl.value : '<?php echo htmlspecialchars($selectedBranch); ?>';
    
    // Determine active KPI tab to preserve it on reload
    const expiringCard = document.getElementById('kpi-expiring-card');
    const expiredCard = document.getElementById('kpi-expired-card');
    const returnedCard = document.getElementById('kpi-returned-card');
    let activeTab = '';
    if (expiringCard.classList.contains('active')) activeTab = 'expiring';
    else if (expiredCard.classList.contains('active')) activeTab = 'expired';
    else if (returnedCard && returnedCard.classList.contains('active')) activeTab = 'returned';
    
    window.location.href = '?branch_id=' + branchId + 
                           (activeTab ? '&active_tab=' + activeTab : '');
}

// Auto-expand active KPI tab based on URL parameter or fallback to active filters
window.addEventListener('DOMContentLoaded', (event) => {
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('active_tab')) {
        toggleKpiTab(urlParams.get('active_tab'));
    } else {
        if (urlParams.has('expiry_after') && urlParams.get('expiry_after') !== '') {
            toggleKpiTab('expiring');
        } else {
            // Default load pre-selects the 1st KPI card
            toggleKpiTab('expiring');
        }
    }
});
</script>

<?php require_once __DIR__ . '/../layouts/footer.php'; ?>
