<?php require_once __DIR__ . '/../../layouts/header.php'; ?>
<?php 
$currentStep = 2;
?>
<div class="stepper" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2.5rem; background: rgba(15, 23, 42, 0.4); padding: 1rem 2rem; border-radius: 12px; border: 1px solid var(--glass-border);">
    <div class="step" style="display: flex; align-items: center; gap: 0.75rem; color: #10b981; font-weight: 400;">
        <span style="display: flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 50%; background: #10b981; color: white; border: 2px solid #10b981; font-size: 0.9rem;">1</span>
        <span>Upload CSV File</span>
    </div>
    <div style="flex: 1; height: 2px; background: var(--glass-border); margin: 0 1.5rem;"></div>
    <div class="step" style="display: flex; align-items: center; gap: 0.75rem; color: var(--primary-color); font-weight: 600;">
        <span style="display: flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 50%; background: var(--primary-color); color: white; border: 2px solid var(--primary-color); font-size: 0.9rem;">2</span>
        <span>Preview & Validation</span>
    </div>
    <div style="flex: 1; height: 2px; background: var(--glass-border); margin: 0 1.5rem;"></div>
    <div class="step" style="display: flex; align-items: center; gap: 0.75rem; color: var(--text-muted); font-weight: 400;">
        <span style="display: flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 50%; background: transparent; color: var(--text-muted); border: 2px solid var(--glass-border); font-size: 0.9rem;">3</span>
        <span>Import Results</span>
    </div>
</div>

<div>
<div class="page-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
        <h2>Preview Bulk Upload</h2>
        <div class="header-actions">
            <a href="/inventory/bulk" class="btn-primary" style="background: transparent; border: 1px solid var(--glass-border); color: var(--text-light); text-decoration: none; width: auto; margin: 0;">Cancel & Go Back</a>
        </div>
    </div>

    <div class="card" style="margin-bottom: 2rem;">
        <h3 style="margin-bottom: 1rem;">Validation Report</h3>
        <div style="display: flex; gap: 2rem; margin-bottom: 1.5rem;" class="form-row">
            <div style="flex: 1; padding: 1.5rem; background: rgba(15,23,42,0.6); border-radius: 8px; border-left: 4px solid var(--primary-color);">
                <p style="color: var(--text-muted); font-size: 0.9rem; margin-bottom: 0.5rem;">Total Rows Found</p>
                <p style="font-size: 2rem; font-weight: 600;"><?php echo $totalRows; ?></p>
            </div>
            <div style="flex: 1; padding: 1.5rem; background: rgba(15,23,42,0.6); border-radius: 8px; border-left: 4px solid #10b981;">
                <p style="color: var(--text-muted); font-size: 0.9rem; margin-bottom: 0.5rem;">Valid Rows (Ready)</p>
                <p id="valid-rows-count" style="font-size: 2rem; font-weight: 600; color: #10b981;"><?php echo $validRowsCount; ?></p>
            </div>
            <div style="flex: 1; padding: 1.5rem; background: rgba(15,23,42,0.6); border-radius: 8px; border-left: 4px solid #ef4444;">
                <p style="color: var(--text-muted); font-size: 0.9rem; margin-bottom: 0.5rem;">Invalid Rows (Will Skip)</p>
                <p id="invalid-rows-count" style="font-size: 2rem; font-weight: 600; color: #ef4444;"><?php echo $allErrorsCount; ?></p>
            </div>
        </div>

        <?php if (!empty($errors)): ?>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;" class="form-row">
                <h4 style="color: #ef4444; margin: 0;">Formatting Errors Found (<span id="all-errors-count"><?php echo $allErrorsCount; ?></span>):</h4>
                <button onclick="saveAllRows()" class="btn-primary" style="margin: 0; padding: 0.5rem 1rem; width: auto; font-size: 0.9rem; background: var(--primary-color);">Save All</button>
            </div>
            <p style="color: var(--text-muted); margin-bottom: 1rem;">The following rows have errors. You can edit and save them right here, or proceed to only import the valid rows.</p>
            
            <div style="overflow-x: auto; margin-bottom: 1rem;" class="responsive-table-container">
                <table style="width: 100%; border-collapse: collapse; background: rgba(0,0,0,0.2); border-radius: 8px; overflow: hidden;">
                    <thead>
                        <tr style="background: rgba(15,23,42,0.8); text-align: left;">
                            <th style="padding: 1rem; border-bottom: 1px solid rgba(239, 68, 68, 0.2); color: #ef4444; font-weight: 600; width: 60px;">Row</th>
                            <th style="padding: 1rem; border-bottom: 1px solid rgba(239, 68, 68, 0.2); color: #ef4444; font-weight: 600; width: 200px;">Error Message</th>
                            <th style="padding: 1rem; border-bottom: 1px solid rgba(239, 68, 68, 0.2); color: var(--text-muted); font-weight: 500;">Medicine Name</th>
                            <th style="padding: 1rem; border-bottom: 1px solid rgba(239, 68, 68, 0.2); color: var(--text-muted); font-weight: 500; width: 140px;">Unit of Measure</th>
                            <th style="padding: 1rem; border-bottom: 1px solid rgba(239, 68, 68, 0.2); color: var(--text-muted); font-weight: 500; width: 130px;">Expiry Alert Days</th>
                            <th style="padding: 1rem; border-bottom: 1px solid rgba(239, 68, 68, 0.2); color: var(--text-muted); font-weight: 500; width: 90px;">Quantity</th>
                            <th style="padding: 1rem; border-bottom: 1px solid rgba(239, 68, 68, 0.2); color: var(--text-muted); font-weight: 500; width: 130px;">Expiry Date</th>
                            <th style="padding: 1rem; border-bottom: 1px solid rgba(239, 68, 68, 0.2); width: 80px;"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($errors as $err): ?>
                            <tr class="error-row" style="border-bottom: 1px solid rgba(255,255,255,0.05); transition: opacity 0.4s ease, transform 0.4s ease, background 0.4s ease;" id="row-<?php echo $err['row']; ?>" data-row="<?php echo $err['row']; ?>">
                                <td style="padding: 1rem; color: #ef4444; font-weight: bold;"><?php echo $err['row']; ?></td>
                                <td class="error-msg-cell" style="padding: 1rem; color: #ef4444; font-size: 0.9rem;"><?php echo htmlspecialchars($err['message']); ?></td>
                                <td style="padding: 0.5rem;"><input type="text" class="edit-med" value="<?php echo htmlspecialchars($err['data'][0] ?? ''); ?>" style="width: 100%; padding: 0.5rem; border-radius: 4px; border: 1px solid var(--glass-border); background: var(--bg-dark); color: white;"></td>
                                <td style="padding: 0.5rem;">
                                    <select class="edit-uom" style="width: 100%; padding: 0.5rem; border-radius: 4px; border: 1px solid var(--glass-border); background: var(--bg-dark); color: white; outline: none;">
                                        <option value="" style="background: var(--bg-dark);">-- Select UOM --</option>
                                        <?php foreach($uoms as $uom): ?>
                                            <option value="<?php echo htmlspecialchars($uom['name']); ?>" <?php echo (strtolower($err['data'][2] ?? '') === strtolower($uom['name'])) ? 'selected' : ''; ?> style="background: var(--bg-dark);"><?php echo htmlspecialchars($uom['name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td style="padding: 0.5rem;"><input type="number" class="edit-alert" value="<?php echo htmlspecialchars($err['data'][5] ?? ''); ?>" style="width: 100%; padding: 0.5rem; border-radius: 4px; border: 1px solid var(--glass-border); background: var(--bg-dark); color: white;"></td>
                                <td style="padding: 0.5rem;"><input type="number" class="edit-qty" value="<?php echo htmlspecialchars($err['data'][6] ?? ''); ?>" style="width: 100%; padding: 0.5rem; border-radius: 4px; border: 1px solid var(--glass-border); background: var(--bg-dark); color: white;"></td>
                                <td style="padding: 0.5rem;"><input type="text" class="edit-exp" value="<?php echo htmlspecialchars($err['data'][7] ?? ''); ?>" placeholder="Expiry Date" style="width: 100%; padding: 0.5rem; border-radius: 4px; border: 1px solid var(--glass-border); background: var(--bg-dark); color: white;"></td>
                                <td style="padding: 0.5rem; text-align: center;">
                                    <button onclick="saveRow(<?php echo $err['row']; ?>)" class="btn-primary btn-save" style="padding: 0.4rem 0.8rem; margin: 0; font-size: 0.8rem; width: auto;">Save</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($totalPages > 1): ?>
                <div style="display: flex; justify-content: center; gap: 1rem; margin-top: 1rem;">
                    <?php if ($page > 1): ?>
                        <a href="?page=<?php echo $page - 1; ?>" class="btn-primary" style="background: transparent; border: 1px solid var(--glass-border); text-decoration: none; width: auto;">&laquo; Previous</a>
                    <?php endif; ?>
                    <span style="padding: 0.5rem 1rem; color: var(--text-muted);">Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
                    <?php if ($page < $totalPages): ?>
                        <a href="?page=<?php echo $page + 1; ?>" class="btn-primary" style="background: transparent; border: 1px solid var(--glass-border); text-decoration: none; width: auto;">Next &raquo;</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <div id="import-actions" style="margin-top: 1.5rem;">
        <form id="import-form" action="/inventory/bulkCommit" method="POST" style="text-align: right; display: <?php echo $validRowsCount > 0 ? 'block' : 'none'; ?>;">
            <input type="hidden" name="temp_file_path" value="<?php echo htmlspecialchars($tempFilePath); ?>">
            <input type="hidden" name="branch_id" value="<?php echo htmlspecialchars($branchId); ?>">
            <button type="submit" id="import-btn" class="btn-primary" style="background: #10b981; border-color: #059669; font-size: 1.1rem; padding: 1rem 2rem; width: auto; max-width: 100%; margin-left: auto;">Confirm & Import <?php echo $validRowsCount; ?> Valid Rows</button>
        </form>
        <div id="no-valid-box" class="card" style="text-align: center; border-color: #ef4444; display: <?php echo $validRowsCount > 0 ? 'none' : 'block'; ?>;">
            <p style="color: #ef4444; font-weight: 500;">No valid rows found to import. Please fix your CSV file and try again.</p>
        </div>
    </div>

</div>

<!-- Progress Modal Overlay -->
<div id="progressModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(15, 23, 42, 0.9); z-index: 9999; justify-content: center; align-items: center; backdrop-filter: blur(5px);">
    <div class="card" style="width: 100%; max-width: 500px; padding: 2.5rem; text-align: center; border: 1px solid var(--glass-border);">
        <h3 id="progress-title" style="margin-bottom: 1.5rem; background: linear-gradient(to right, #818cf8, #c084fc); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 1.5rem;">Importing Records...</h3>
        
        <!-- Progress Bar Container -->
        <div style="width: 100%; height: 12px; background: rgba(255,255,255,0.05); border-radius: 6px; overflow: hidden; margin-bottom: 1rem; border: 1px solid var(--glass-border);">
            <div id="progress-bar-fill" style="width: 0%; height: 100%; background: linear-gradient(90deg, var(--primary-color), #c084fc); transition: width 0.3s ease; border-radius: 6px;"></div>
        </div>
        
        <!-- Progress Stats -->
        <p id="progress-text" style="color: var(--text-light); font-size: 1.1rem; margin-bottom: 0.5rem; font-weight: 500;">0% Completed</p>
        <p id="progress-details" style="color: var(--text-muted); font-size: 0.95rem;">Processed 0 of <?php echo $totalRows; ?> rows...</p>
    </div>
</div>

<script>
function getRowData(rowNum) {
    const tr = document.getElementById('row-' + rowNum);
    if (!tr) return null;
    return {
        row: rowNum,
        medName: tr.querySelector('.edit-med').value,
        uomName: tr.querySelector('.edit-uom').value,
        expiryAlertDays: tr.querySelector('.edit-alert').value,
        quantity: tr.querySelector('.edit-qty').value,
        expiryDate: tr.querySelector('.edit-exp').value
    };
}

async function saveRow(rowNum) {
    const tr = document.getElementById('row-' + rowNum);
    if (!tr) return;
    
    const saveBtn = tr.querySelector('.btn-save');
    if (saveBtn) {
        saveBtn.disabled = true;
        saveBtn.textContent = 'Saving...';
    }
    
    const rowData = getRowData(rowNum);
    const tempFile = '<?php echo addslashes($tempFilePath); ?>';
    
    try {
        const response = await fetch('/inventory/bulkPatchRow', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                temp_file: tempFile,
                row: rowNum,
                medName: rowData.medName,
                uomName: rowData.uomName,
                expiryAlertDays: rowData.expiryAlertDays,
                quantity: rowData.quantity,
                expiryDate: rowData.expiryDate
            })
        });
        
        const data = await response.json();
        if (data.success) {
            handleSaveResults(data, [rowNum]);
        } else {
            alert('Failed to save row.');
            if (saveBtn) {
                saveBtn.disabled = false;
                saveBtn.textContent = 'Save';
            }
        }
    } catch (e) {
        alert('An error occurred while saving.');
        if (saveBtn) {
            saveBtn.disabled = false;
            saveBtn.textContent = 'Save';
        }
    }
}

async function saveAllRows() {
    const trs = document.querySelectorAll('.error-row');
    if (trs.length === 0) return;
    
    const saveAllBtn = document.querySelector('button[onclick="saveAllRows()"]');
    if (saveAllBtn) {
        saveAllBtn.disabled = true;
        saveAllBtn.textContent = 'Saving All...';
    }
    
    const rows = [];
    const rowNums = [];
    trs.forEach(tr => {
        const rowNum = parseInt(tr.getAttribute('data-row'));
        const rowData = getRowData(rowNum);
        if (rowData) {
            rows.push(rowData);
            rowNums.push(rowNum);
        }
        // Disable individual buttons
        const btn = tr.querySelector('.btn-save');
        if (btn) {
            btn.disabled = true;
            btn.textContent = '...';
        }
    });
    
    const tempFile = '<?php echo addslashes($tempFilePath); ?>';
    
    try {
        const response = await fetch('/inventory/bulkPatchRow', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                temp_file: tempFile,
                rows: rows
            })
        });
        
        const data = await response.json();
        if (data.success) {
            handleSaveResults(data, rowNums);
        } else {
            alert('Failed to save rows.');
        }
    } catch (e) {
        alert('An error occurred while saving.');
    } finally {
        if (saveAllBtn) {
            saveAllBtn.disabled = false;
            saveAllBtn.textContent = 'Save All';
        }
        // Re-enable individual buttons for rows that weren't removed
        document.querySelectorAll('.error-row').forEach(tr => {
            const btn = tr.querySelector('.btn-save');
            if (btn && btn.disabled && btn.textContent === '...') {
                btn.disabled = false;
                btn.textContent = 'Save';
            }
        });
    }
}

function handleSaveResults(data, rowNums) {
    // 1. Update stats
    const validCountEl = document.getElementById('valid-rows-count');
    const invalidCountEl = document.getElementById('invalid-rows-count');
    const allErrorsCountEl = document.getElementById('all-errors-count');
    
    if (validCountEl) validCountEl.textContent = data.validRowsCount;
    if (invalidCountEl) invalidCountEl.textContent = data.invalidRowsCount;
    if (allErrorsCountEl) allErrorsCountEl.textContent = data.invalidRowsCount;
    
    // 2. Update Import action form/button at bottom
    const importForm = document.getElementById('import-form');
    const noValidBox = document.getElementById('no-valid-box');
    const importBtn = document.getElementById('import-btn');
    
    if (data.validRowsCount > 0) {
        if (importForm) importForm.style.display = 'block';
        if (noValidBox) noValidBox.style.display = 'none';
        if (importBtn) importBtn.textContent = 'Confirm & Import ' + data.validRowsCount + ' Valid Rows';
    } else {
        if (importForm) importForm.style.display = 'none';
        if (noValidBox) noValidBox.style.display = 'block';
    }
    
    // 3. Process individual row results
    rowNums.forEach(rowNum => {
        const tr = document.getElementById('row-' + rowNum);
        if (!tr) return;
        
        const result = data.rowResults[rowNum];
        if (result) {
            if (result.isValid) {
                // Highlight and slide/fade out
                tr.style.background = 'rgba(16, 185, 129, 0.1)';
                tr.style.opacity = '0';
                tr.style.transform = 'translateY(-15px)';
                setTimeout(() => {
                    tr.remove();
                    // If no more rows are in the table, reload the page to refresh pagination and list
                    const tbody = document.querySelector('tbody');
                    if (tbody && tbody.children.length === 0) {
                        window.location.reload();
                    }
                }, 400);
            } else {
                // Still invalid, show updated error message
                const msgCell = tr.querySelector('.error-msg-cell');
                if (msgCell) {
                    msgCell.textContent = result.errorMessage;
                }
                const btn = tr.querySelector('.btn-save');
                if (btn) {
                    btn.disabled = false;
                    btn.textContent = 'Save';
                }
            }
        }
    });
}

document.getElementById('import-form').addEventListener('submit', function(e) {
    e.preventDefault();
    startImport();
});

async function startImport() {
    document.getElementById('progressModal').style.display = 'flex';
    
    const tempFilePath = '<?php echo addslashes($tempFilePath); ?>';
    const branchId = '<?php echo addslashes($branchId); ?>';
    const totalRows = <?php echo intval($totalRows); ?>;
    
    let startRow = 1;
    const chunkSize = 500;
    
    while (true) {
        try {
            const response = await fetch('/inventory/bulkCommitChunk', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    temp_file_path: tempFilePath,
                    branch_id: branchId,
                    start_row: startRow,
                    chunk_size: chunkSize
                })
            });
            
            const data = await response.json();
            if (data.success) {
                if (data.done) {
                    document.getElementById('progress-bar-fill').style.width = '100%';
                    document.getElementById('progress-text').textContent = '100% Completed';
                    document.getElementById('progress-details').textContent = 'Import finished successfully! Redirecting...';
                    
                    setTimeout(() => {
                        window.location.href = '/inventory/bulk';
                    }, 1000);
                    break;
                } else {
                    startRow = data.next_row;
                    const percent = Math.min(99, Math.round(((startRow - 1) / totalRows) * 100));
                    document.getElementById('progress-bar-fill').style.width = percent + '%';
                    document.getElementById('progress-text').textContent = percent + '% Completed';
                    document.getElementById('progress-details').textContent = 'Processed ' + (startRow - 1) + ' of ' + totalRows + ' rows...';
                }
            } else {
                alert('Import failed: ' + (data.error || 'Unknown error'));
                document.getElementById('progressModal').style.display = 'none';
                break;
            }
        } catch (error) {
            alert('An error occurred during import.');
            document.getElementById('progressModal').style.display = 'none';
            break;
        }
    }
}
</script>

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