<div class="page-header">
    <div>
        <h1>Stock Taking</h1>
        <div class="page-subtitle">Manage stock counting and inventory adjustments</div>
    </div>
    <div class="flex gap-2">
        <button onclick="printTable()" class="btn btn-outline" title="Print">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 16px; height: 16px;"><polyline points="6 9 6 2 18 2 18 9"></polyline><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v-5a2 2 0 0 1-2 2h-2"></path><rect x="6" y="14" width="12" height="8"></rect></svg>
            Print
        </button>
        <button onclick="exportCSV()" class="btn btn-outline" title="Export CSV">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 16px; height: 16px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
            Export CSV
        </button>
        <a href="<?= APP_URL ?>/stock-takings/create" class="btn btn-primary">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                <line x1="12" y1="5" x2="12" y2="19"></line>
                <line x1="5" y1="12" x2="19" y2="12"></line>
            </svg>
            New Stock Taking
        </a>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h3 class="card-title">Stock Taking Sessions</h3>
    </div>
    <div class="table-wrapper">
        <table class="data-table">
            <thead>
                <tr>
                    <th>Reference</th>
                    <th>Date</th>
                    <th>Location</th>
                    <th>Mode</th>
                    <th>Status</th>
                    <th>Items</th>
                    <th>Created By</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($stockTakings['data'] as $st): ?>
                <tr>
                    <td>
                        <span class="badge badge-secondary"><?= e($st['reference']) ?></span>
                    </td>
                    <td>
                        <span class="text-sm"><?= date('M j, Y g:i A', strtotime($st['created_at'])) ?></span>
                    </td>
                    <td>
                        <span class="text-sm"><?= e($st['location_name']) ?></span>
                    </td>
                    <td>
                        <span class="badge badge-info"><?= ucfirst($st['mode']) ?></span>
                    </td>
                    <td>
                        <?php if ($st['status'] === 'completed'): ?>
                            <span class="badge badge-success">Completed</span>
                        <?php else: ?>
                            <span class="badge badge-warning">Draft</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="text-sm"><?= number_format($st['item_count']) ?></span>
                    </td>
                    <td>
                        <span class="text-sm"><?= e($st['user_name']) ?></span>
                    </td>
                    <td>
                        <div class="flex gap-1">
                            <a href="<?= APP_URL ?>/stock-takings/view/<?= $st['id'] ?>" class="btn btn-ghost btn-sm" title="View">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;">
                                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                    <circle cx="12" cy="12" r="3"></circle>
                                </svg>
                            </a>
                            <?php if ($st['status'] === 'completed'): ?>
                                <a href="<?= APP_URL ?>/stock-takings/report/<?= $st['id'] ?>" class="btn btn-ghost btn-sm" title="Report">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;">
                                        <path d="M14 2H6a2 2 0 0 1-2h3a2 2 0 0 1-2z"></path>
                                        <path d="M16 4v2"></path>
                                        <path d="M16 4v2"></path>
                                        <path d="M16 4v2"></path>
                                    </svg>
                                </a>
                            <?php else: ?>
                                <a href="<?= APP_URL ?>/stock-takings/count/<?= $st['id'] ?>" class="btn btn-ghost btn-sm" title="Count">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;"><path d="M11 4H4a2 2 0 0 1-2h3a2 2 0 0 1-2z"></path><path d="M17 5v-2h3a2 2 0 0 1-2z"></path></svg>
                                </a>
                            <?php endif; ?>
                            
                            <form method="POST" action="<?= APP_URL ?>/stock-takings/delete" style="display:inline;">
                                <?= Security::csrfField() ?>
                                <input type="hidden" name="id" value="<?= $st['id'] ?>">
                                <button type="submit" class="btn btn-ghost btn-sm text-danger" 
                                    onclick="return confirm('<?= $st['stock_updated'] ? 'WARNING: Stock has already been updated for this session. Deleting it will remove the adjustment record but will NOT revert the stock changes. Continue?' : 'Are you sure you want to delete this stock taking session?' ?>')" 
                                    title="Delete">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;">
                                        <polyline points="3 6 5 6 21 6"></polyline>
                                        <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                                        <line x1="10" y1="11" x2="10" y2="17"></line>
                                        <line x1="14" y1="11" x2="14" y2="17"></line>
                                    </svg>
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($stockTakings['data'])): ?>
                <tr>
                    <td colspan="8" class="text-center text-muted py-8">
                        No stock taking sessions found. Start a new stock taking to get started.
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <div class="flex justify-between items-center p-4 border-t border-soft">
        <?= paginationLinks($stockTakings, APP_URL . '/stock-takings', []) ?>
    </div>
</div>

<script>
function printTable() {
    const tableWrapper = document.querySelector('.table-wrapper');
    if (!tableWrapper) return;
    
    // Clone the table
    const clonedWrapper = tableWrapper.cloneNode(true);
    const table = clonedWrapper.querySelector('table');
    
    // Remove Action column (the last one)
    const headerRow = table.querySelector('thead tr');
    if (headerRow) headerRow.deleteCell(-1);
    
    const bodyRows = table.querySelectorAll('tbody tr');
    bodyRows.forEach(row => {
        // Only delete if it has cells (skip empty state rows if length 1)
        if (row.cells.length > 1) {
            row.deleteCell(-1);
        }
    });
    
    // Open print window
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Stock Taking Sessions</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; font-size: 12px; }
                table { border-collapse: collapse; width: 100%; margin-top: 10px; }
                th, td { border: 1px solid #ccc; padding: 8px 10px; text-align: left; }
                th { background: #f5f5f5; font-weight: bold; font-size: 11px; }
                .badge { padding: 3px 8px; border-radius: 3px; font-size: 10px; display: inline-block; background: #e2e3e5; }
                .text-sm { font-size: 11px; }
                @media print {
                    body { margin: 15mm; padding: 0; }
                }
            </style>
        </head>
        <body>
            <div style="margin-bottom: 20px; border-bottom: 2px solid #333; padding-bottom: 10px;">
                <h2 style="margin: 0 0 5px 0;">Stock Taking Sessions</h2>
                <p style="margin: 0; color: #666; font-size: 11px;">Generated on: ${new Date().toLocaleDateString()}</p>
            </div>
            ${clonedWrapper.outerHTML}
        </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.onload = function() {
        printWindow.print();
        printWindow.close();
    };
}

function exportCSV() {
    let csv = 'Reference,Date,Location,Mode,Status,Items,Created By\n';
    <?php foreach ($stockTakings['data'] as $st): ?>
    csv += '<?= e($st['reference']) ?>,<?= date('Y-m-d H:i:s', strtotime($st['created_at'])) ?>,<?= e(str_replace(',', ' ', $st['location_name'])) ?>,<?= ucfirst($st['mode']) ?>,<?= ucfirst($st['status']) ?>,<?= $st['item_count'] ?>,<?= e(str_replace(',', ' ', $st['user_name'])) ?>\n';
    <?php endforeach; ?>
    
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'stock_takings_export.csv';
    a.click();
    window.URL.revokeObjectURL(url);
}
</script>
