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

<div class="page-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; flex-wrap: wrap; gap: 1rem;">
    <h2>Expiry Check</h2>
    <form method="GET" action="/expiryCheck" style="display: flex; align-items: center; gap: 1rem; flex-wrap: wrap;" class="form-row">
        <?php if ($_SESSION['role'] === 'admin'): ?>
        <div style="display: flex; align-items: center; gap: 0.5rem;">
            <label for="branchFilter" style="color: var(--text-muted); font-weight: 500; white-space: nowrap; font-size: 0.95rem;">Branch:</label>
            <select id="branchFilter" name="branch_id" onchange="this.form.submit()" 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: 150px; color-scheme: dark;">
                <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="display: flex; align-items: center; gap: 0.5rem;">
            <label for="expiryDateFilter" style="color: var(--text-muted); font-weight: 500; white-space: nowrap; font-size: 0.95rem;">Expiring On/Before:</label>
            <input type="date" id="expiryDateFilter" name="date" value="<?php echo htmlspecialchars($selectedDate); ?>" onchange="this.form.submit()" 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; font-size: 0.95rem; color-scheme: dark; height: 38px;">
        </div>
    </form>
</div>

<style>
#expiryDetailsTable th, #expiryDetailsTable td {
    white-space: nowrap;
}
#expiryDetailsTable 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>

<!-- Chart Card -->
<div class="card" style="margin-bottom: 2rem;">
    <h3 style="margin-top: 0; margin-bottom: 1.5rem; border-bottom: 1px solid var(--glass-border); padding-bottom: 0.75rem; color: var(--text-light); font-weight: 600;">
        Expiry Timeline Statistics
    </h3>
    <div style="position: relative; height: 300px; width: 100%;">
        <?php if (empty($chartData)): ?>
            <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; color: var(--text-muted);">
                No expiring batches found on or before the selected date.
            </div>
        <?php else: ?>
            <canvas id="expiryChart"></canvas>
        <?php endif; ?>
    </div>
    <?php if (!empty($chartData)): ?>
        <p style="color: var(--text-muted); font-size: 0.85rem; margin-top: 1rem; text-align: center;">
            <i class="ph ph-info" style="vertical-align: middle;"></i> Tip: Click on any bar in the chart to filter the details table below for that specific expiration date.
        </p>
    <?php endif; ?>
</div>

<!-- Details Table -->
<div class="card" style="padding: 0;">
    <div style="padding: 1.5rem; border-bottom: 1px solid var(--glass-border); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem;">
        <h3 style="margin: 0; border: none; padding: 0; color: var(--text-light); font-weight: 600;">Expiring Batches Details</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="searchTableInput" onkeyup="filterTableBySearch()" 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="exportTableToCSV()" 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 style="padding: 1.5rem 1.5rem 0 1.5rem;">
        <!-- Dynamic JS Filter Banner -->
        <div id="filterBanner" style="display: none; justify-content: space-between; align-items: center; background: rgba(129, 140, 248, 0.1); border: 1px solid rgba(129, 140, 248, 0.3); padding: 0.75rem 1.5rem; border-radius: 8px; margin-bottom: 0.5rem; color: #818cf8;">
            <span>Showing detailed batches expiring on: <strong id="filterDateText"></strong></span>
            <button type="button" onclick="resetTableFilter()" class="btn-primary" style="margin: 0; padding: 0.35rem 1rem; font-size: 0.85rem; width: auto; background: var(--primary-color);">Show All Dates</button>
        </div>
    </div>

    <div id="expiryDetailsTable" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1rem;">
        <?php foreach($batches as $b): ?>
        <?php 
            $expiryDate = new DateTime($b['expiry_date']);
            $today = new DateTime();
            $today->setTime(0, 0, 0);
            $expiryDate->setTime(0, 0, 0);
            $diff = (int) $today->diff($expiryDate)->format("%r%a");
            
            $expiryColor = '#34d399'; // Green
            if ($diff < 0) {
                $expiryColor = '#ef4444'; // Red (Expired)
            } elseif ($diff <= 30) {
                $expiryColor = '#f59e0b'; // Orange (Expiring soon)
            }
        ?>
        <div class="card grid-card batch-row" data-date="<?php echo htmlspecialchars($b['expiry_date']); ?>" style="padding: 1.5rem; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.4); border-radius: 12px; position: relative; display: flex; flex-direction: column;">
            <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 style="min-width: 0;">
                    <strong style="font-size: 1.1rem; color: white; display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" class="med-name"><?php echo htmlspecialchars($b['medicine_name']); ?></strong>
                    <?php if (!empty($b['generic_name'])): ?>
                        <small style="color: var(--text-muted); display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" class="med-generic"><?php echo htmlspecialchars($b['generic_name']); ?></small>
                    <?php endif; ?>
                </div>
                <div class="actions-cell" style="margin-left: 0.5rem; flex-shrink: 0;">
                    <?php if ($diff < 0): ?>
                        <button class="btn-danger" style="padding: 0.2rem 0.6rem; font-size: 0.8rem; width: auto; margin: 0; background: rgba(239, 68, 68, 0.1); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.3); border-radius: 4px; cursor: pointer; display: flex; align-items: center; gap: 0.25rem; white-space: nowrap; transition: all 0.3s ease;" onclick="confirmRemoveBatch(<?php echo $b['id']; ?>)">
                            <i class="ph ph-trash"></i> Remove
                        </button>
                    <?php endif; ?>
                </div>
            </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;" class="batch-num"><?php echo htmlspecialchars($b['batch_number']); ?></strong>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Branch</span>
                    <span class="branch-name"><?php echo htmlspecialchars($b['branch_name']); ?></span>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Quantity</span>
                    <span class="qty" style="padding: 0.15rem 0.4rem; border-radius: 4px; font-weight: bold; background: rgba(255, 255, 255, 0.05); color: var(--text-light);"><?php echo $b['quantity']; ?></span>
                </div>
                <div>
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Expiry Date</span>
                    <strong style="color: <?php echo $expiryColor; ?>;" class="exp-date"><?php echo htmlspecialchars($b['expiry_date']); ?></strong>
                </div>
                <div style="grid-column: 1 / -1;">
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem;">Days Remaining</span>
                    <span class="days-left-badge" style="background: <?php echo $diff < 0 ? 'rgba(239, 68, 68, 0.15)' : 'rgba(245, 158, 11, 0.15)'; ?>; color: <?php echo $diff < 0 ? '#ef4444' : '#f59e0b'; ?>; padding: 0.15rem 0.4rem; border-radius: 4px; font-weight: 500; font-size: 0.8rem;">
                        <?php echo $diff < 0 ? 'Expired (' . \App\Utils\DateFormatter::formatDaysFriendly($diff) . ' overdue)' : \App\Utils\DateFormatter::formatDaysFriendly($diff) . ' left'; ?>
                    </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);">
                <div style="min-width: 0; max-width: 100%;">
                    <span style="color: var(--text-muted); display: block; font-size: 0.8rem; margin-bottom: 0.25rem;">Notes</span>
                    <?php if (!empty($b['notes'])): ?>
                        <span class="notes-highlight note-text-container" style="display: flex; align-items: flex-start; max-width: 100%; box-sizing: border-box;" title="<?php echo htmlspecialchars($b['notes']); ?>" data-note="<?php echo htmlspecialchars($b['notes']); ?>" onclick="showSmartNoteInfo(this.getAttribute('data-note'))">
                            <i class="ph ph-note" style="margin-top: 0.15rem; flex-shrink: 0;"></i> 
                            <span class="note-text" style="white-space: normal; overflow-wrap: break-word; word-break: break-word; overflow: visible; display: block;"><?php echo htmlspecialchars($b['notes']); ?></span>
                        </span>
                    <?php else: ?>
                        <span style="color: var(--text-muted);" class="note-text-container">-</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        
        <div id="noBatchesRow" style="display: <?php echo empty($batches) ? '' : '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 batches details found.
        </div>
    </div>
</div>

<?php if (!empty($chartData)): ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
    const chartLabels = <?php echo json_encode(array_column($chartData, 'expiry_date')); ?>;
    const chartCounts = <?php echo json_encode(array_map('intval', array_column($chartData, 'batch_count'))); ?>;
    const chartQuantities = <?php echo json_encode(array_map('intval', array_column($chartData, 'total_quantity'))); ?>;

    const ctx = document.getElementById('expiryChart').getContext('2d');
    
    // Create premium gradient for bars
    const gradient = ctx.createLinearGradient(0, 0, 0, 300);
    gradient.addColorStop(0, '#a78bfa'); // purple-400
    gradient.addColorStop(1, '#818cf8'); // indigo-400

    const hoverGradient = ctx.createLinearGradient(0, 0, 0, 300);
    hoverGradient.addColorStop(0, '#c084fc'); // purple-300
    hoverGradient.addColorStop(1, '#6366f1'); // indigo-500

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: chartLabels,
            datasets: [{
                label: 'Batch Count',
                data: chartCounts,
                backgroundColor: gradient,
                hoverBackgroundColor: hoverGradient,
                borderRadius: 6,
                borderSkipped: false,
                barPercentage: 0.6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(15, 23, 42, 0.95)',
                    titleColor: '#fff',
                    bodyColor: '#cbd5e1',
                    borderColor: 'rgba(255, 255, 255, 0.08)',
                    borderWidth: 1,
                    padding: 12,
                    callbacks: {
                        afterBody: function(context) {
                            const index = context[0].dataIndex;
                            return `Total Quantity: ${chartQuantities[index]}`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        color: '#94a3b8',
                        font: {
                            family: 'Inter'
                        }
                    }
                },
                y: {
                    grid: {
                        color: 'rgba(255, 255, 255, 0.05)'
                    },
                    ticks: {
                        color: '#94a3b8',
                        stepSize: 1,
                        precision: 0,
                        font: {
                            family: 'Inter'
                        }
                    }
                }
            },
            onClick: (event, activeElements) => {
                if (activeElements.length > 0) {
                    const elementIndex = activeElements[0].index;
                    const clickedDate = chartLabels[elementIndex];
                    filterTableByDate(clickedDate);
                }
            }
        }
    });
});

function filterTableByDate(date) {
    document.getElementById('filterDateText').textContent = date;
    document.getElementById('filterBanner').style.display = 'flex';
    
    const rows = document.querySelectorAll('#expiryDetailsTable tbody tr.batch-row');
    let visibleCount = 0;
    rows.forEach(row => {
        const rowDate = row.getAttribute('data-date');
        if (rowDate === date) {
            row.style.display = '';
            visibleCount++;
        } else {
            row.style.display = 'none';
        }
    });
    
    const noRows = document.getElementById('noBatchesRow');
    if (noRows) {
        noRows.style.display = visibleCount === 0 ? '' : 'none';
    }
    
    // Smooth scroll down to table header
    document.getElementById('expiryDetailsTable').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

function resetTableFilter() {
    document.getElementById('filterBanner').style.display = 'none';
    const rows = document.querySelectorAll('#expiryDetailsTable tbody tr.batch-row');
    rows.forEach(row => {
        row.style.display = '';
    });
    
    // Clear search input if present
    const searchInput = document.getElementById('searchTableInput');
    if(searchInput) searchInput.value = '';
    
    const noRows = document.getElementById('noBatchesRow');
    if (noRows) {
        noRows.style.display = rows.length === 0 ? '' : 'none';
    }
}

function filterTableBySearch() {
    const input = document.getElementById('searchTableInput').value.toLowerCase();
    const rows = document.querySelectorAll('#expiryDetailsTable .batch-row');
    let visibleCount = 0;
    const dateFilterText = document.getElementById('filterDateText').textContent;
    const isDateFiltered = document.getElementById('filterBanner').style.display !== 'none';

    rows.forEach(row => {
        const medName = row.querySelector('.med-name').textContent.toLowerCase();
        const batchNum = row.querySelector('.batch-num').textContent.toLowerCase();
        
        let showRow = true;
        
        if (input && !medName.includes(input) && !batchNum.includes(input)) {
            showRow = false;
        }
        
        if (isDateFiltered && row.getAttribute('data-date') !== dateFilterText) {
            showRow = false;
        }
        
        row.style.display = showRow ? '' : 'none';
        if (showRow) visibleCount++;
    });
    
    const noRows = document.getElementById('noBatchesRow');
    if (noRows) {
        noRows.style.display = visibleCount === 0 ? '' : 'none';
    }
}

let batchToRemove = null;

function confirmRemoveBatch(batchId) {
    batchToRemove = batchId;
    document.getElementById('removeConfirmModal').style.display = 'flex';
}

function closeRemoveModal() {
    batchToRemove = null;
    document.getElementById('removeConfirmModal').style.display = 'none';
}

function exportTableToCSV() {
    const cards = document.querySelectorAll('#expiryDetailsTable .batch-row');
    let csvContent = "data:text/csv;charset=utf-8,\uFEFF"; // Include BOM for Excel compatibility
    
    // CSV Header
    csvContent += '"Medicine Details","Batch Number","Branch","Quantity","Expiry Date","Days Remaining","Notes"\r\n';
    
    cards.forEach(card => {
        if (card.style.display === 'none' || card.id === 'noBatchesRow') return;

        let rowData = [];
        
        const medName = card.querySelector('.med-name')?.innerText.trim() || '';
        const medGeneric = card.querySelector('.med-generic')?.innerText.trim() || '';
        const medFull = medGeneric ? medName + " " + medGeneric : medName;
        rowData.push('"' + medFull.replace(/"/g, '""') + '"');
        
        const batchNum = card.querySelector('.batch-num')?.innerText.trim() || '';
        rowData.push('"' + batchNum.replace(/"/g, '""') + '"');
        
        const branchName = card.querySelector('.branch-name')?.innerText.trim() || '';
        rowData.push('"' + branchName.replace(/"/g, '""') + '"');
        
        const qty = card.querySelector('.qty')?.innerText.trim() || '';
        rowData.push('"' + qty.replace(/"/g, '""') + '"');
        
        const expDate = card.querySelector('.exp-date')?.innerText.trim() || '';
        rowData.push('"' + expDate.replace(/"/g, '""') + '"');
        
        const daysLeft = card.querySelector('.days-left-badge')?.innerText.trim() || '';
        rowData.push('"' + daysLeft.replace(/"/g, '""') + '"');
        
        const notes = card.querySelector('.note-text-container')?.innerText.trim() || '';
        rowData.push('"' + notes.replace(/"/g, '""') + '"');
        
        csvContent += rowData.join(",") + "\r\n";
    });

    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    const dateStr = new Date().toISOString().split('T')[0];
    link.setAttribute("download", `expiring_batches_${dateStr}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

document.addEventListener('DOMContentLoaded', () => {
    const confirmBtn = document.getElementById('confirmRemoveBtn');
    if(confirmBtn) {
        confirmBtn.addEventListener('click', () => {
            if (batchToRemove) {
                window.location.href = `/expiryCheck/remove?batch_id=${batchToRemove}`;
            }
        });
    }
});
</script>
<?php endif; ?>

<!-- Custom Confirmation Modal -->
<div id="removeConfirmModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; align-items: center; justify-content: center; backdrop-filter: blur(4px);">
    <div class="card" style="max-width: 400px; width: 90%; background: var(--bg-dark); border: 1px solid var(--glass-border); box-shadow: 0 10px 25px rgba(0,0,0,0.5); padding: 1.5rem;">
        <h3 style="margin-top: 0; color: #ef4444; display: flex; align-items: center; gap: 0.5rem; font-size: 1.25rem;">
            <i class="ph ph-warning-circle" style="font-size: 1.5rem;"></i> Confirm Removal
        </h3>
        <p style="color: var(--text-light); margin-bottom: 1.5rem; line-height: 1.5;">
            Are you sure you want to remove this expired batch from the inventory? This action cannot be undone.
        </p>
        <div style="display: flex; justify-content: flex-end; gap: 1rem;">
            <button type="button" onclick="closeRemoveModal()" style="margin: 0; background: rgba(255,255,255,0.1); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; font-weight: 500;">Cancel</button>
            <button type="button" id="confirmRemoveBtn" style="margin: 0; background: #ef4444; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; font-weight: 500;">Yes, Remove</button>
        </div>
    </div>
</div>

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