<?php
/**
 * Enterprise HRM ERP System - Manpower Transfer
 * Excel-like table interface for bulk employee transfers
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

$pageTitle = 'Manpower Transfer';
$currentModule = 'transfer';

include __DIR__ . '/../../includes/header.php';
?>

<style>
/* Transfer Table Styles */
.transfer-container {
    background-color: var(--white);
    border-radius: 8px;
    box-shadow: var(--shadow);
    overflow: hidden;
    margin-bottom: 20px;
}

.transfer-header {
    padding: 20px 24px;
    border-bottom: 2px solid var(--border-color);
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.transfer-header h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
}

.transfer-actions {
    display: flex;
    gap: 10px;
}

.transfer-table-wrapper {
    overflow-x: auto;
    max-width: 100%;
}

.transfer-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
    background-color: var(--white);
    min-width: 1800px;
}

.transfer-table thead {
    background-color: #f1f5f9;
    position: sticky;
    top: 0;
    z-index: 10;
}

.transfer-table th {
    padding: 12px 8px;
    text-align: center;
    font-weight: 600;
    color: var(--text-primary);
    border: 1px solid #cbd5e1;
    white-space: nowrap;
    font-size: 12px;
    vertical-align: middle;
}

.transfer-table th.header-main {
    background-color: #1e293b;
    color: white;
    font-weight: 700;
    font-size: 13px;
    padding: 14px 8px;
}

.transfer-table th.header-sub {
    background-color: #3b82f6;
    color: white;
    font-weight: 600;
    font-size: 12px;
}

.transfer-table tbody tr {
    border-bottom: 1px dotted #cbd5e1;
}

.transfer-table tbody tr:hover {
    background-color: #f8fafc;
}

.transfer-table td {
    padding: 8px 6px;
    border-right: 1px dotted #cbd5e1;
    border-bottom: 1px dotted #cbd5e1;
    vertical-align: middle;
    text-align: center;
}

.transfer-table td:last-child {
    border-right: none;
}

.transfer-table input[type="text"],
.transfer-table input[type="date"] {
    width: 100%;
    padding: 6px 8px;
    border: 1px solid #cbd5e1;
    border-radius: 4px;
    font-size: 12px;
    text-align: center;
    background: white;
}

.transfer-table input[type="text"]:focus,
.transfer-table input[type="date"]:focus {
    outline: none;
    border-color: #1e293b;
    box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.1);
}

.transfer-table select {
    width: 100%;
    padding: 6px 8px;
    border: 1px solid #cbd5e1;
    border-radius: 4px;
    font-size: 12px;
    text-align: center;
    background: white;
    cursor: pointer;
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 12 12'%3E%3Cpath fill='%23374151' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 6px center;
    padding-right: 24px;
}

.transfer-table select:focus {
    outline: none;
    border-color: #1e293b;
    box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.1);
}

.transfer-table .col-slno {
    width: 50px;
    min-width: 50px;
    font-weight: 600;
    color: var(--text-primary);
}

.transfer-table .col-emp-id {
    width: 120px;
    min-width: 120px;
}

.transfer-table .col-name {
    width: 180px;
    min-width: 180px;
    text-align: left;
    padding-left: 10px;
}

.transfer-table .col-designation {
    width: 150px;
    min-width: 150px;
    text-align: left;
    padding-left: 10px;
}

.transfer-table .col-category {
    width: 100px;
    min-width: 100px;
}

.transfer-table .col-site {
    width: 150px;
    min-width: 150px;
}

.transfer-table .col-location {
    width: 120px;
    min-width: 120px;
}

.transfer-table .col-wef {
    width: 120px;
    min-width: 120px;
}

.transfer-table .col-effective {
    width: 120px;
    min-width: 120px;
}

.transfer-table .col-esi {
    width: 120px;
    min-width: 120px;
}

.transfer-table .col-yes-no {
    width: 140px;
    min-width: 140px;
}

.transfer-table .col-remarks {
    width: 200px;
    min-width: 200px;
    text-align: left;
    padding-left: 10px;
}

.transfer-table input[type="text"].remarks-input {
    text-align: left;
    padding-left: 10px;
}

.transfer-footer {
    padding: 20px 24px;
    border-top: 2px solid var(--border-color);
    background-color: #f8fafc;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

.btn-save {
    background-color: var(--success-color);
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-save:hover {
    background-color: #059669;
    transform: translateY(-1px);
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.btn-save:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
}

.save-status {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-secondary);
}

.save-status.success {
    color: var(--success-color);
}

.save-status.error {
    color: var(--error-color);
}

/* Responsive */
@media (max-width: 1200px) {
    .transfer-table-wrapper {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }
}

@media (max-width: 768px) {
    .transfer-table-wrapper {
        overflow-x: scroll;
        -webkit-overflow-scrolling: touch;
        position: relative;
    }
    
    .transfer-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
        padding: 15px 20px;
    }
    
    .transfer-header h2 {
        font-size: 18px;
    }
    
    .transfer-actions {
        width: 100%;
        flex-direction: column;
    }
    
    .transfer-actions .btn {
        width: 100%;
    }
    
    .transfer-footer {
        flex-direction: column;
        align-items: stretch;
        padding: 15px 20px;
    }
    
    .btn-save {
        width: 100%;
    }
    
    .transfer-table {
        font-size: 11px;
    }
    
    .transfer-table th,
    .transfer-table td {
        padding: 6px 4px;
        font-size: 11px;
    }
    
    .transfer-table input[type="text"],
    .transfer-table input[type="date"],
    .transfer-table select {
        font-size: 11px;
        padding: 4px 6px;
    }
}

/* Loading overlay */
.loading-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 9999;
    justify-content: center;
    align-items: center;
}

.loading-overlay.active {
    display: flex;
}

.loading-spinner {
    background: white;
    padding: 30px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 15px;
}

.spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f4f6;
    border-top-color: #1e293b;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}
</style>

<div class="transfer-container">
    <div class="transfer-header">
        <h2>Manpower Transfer</h2>
        <div class="transfer-actions">
            <?php if (isHRAdmin() || isSuperAdmin()): ?>
            <a href="<?php echo BASE_URL; ?>/modules/transfer/approve.php" class="btn btn-secondary btn-sm">📋 Approval</a>
            <?php endif; ?>
            <a href="<?php echo BASE_URL; ?>/modules/transfer/report.php" class="btn btn-secondary btn-sm">📊 View Transfer Report</a>
            <button type="button" class="btn btn-primary btn-sm" onclick="addNewRow()">➕ Add Row</button>
            <button type="button" class="btn btn-warning btn-sm" onclick="clearAll()">🗑️ Clear All</button>
        </div>
    </div>
    
    <div id="errorMessage" class="alert alert-danger" style="display: none; margin: 15px; padding: 12px; border-radius: 6px;"></div>
    <div id="successMessage" class="alert alert-success" style="display: none; margin: 15px; padding: 12px; border-radius: 6px;"></div>
    
    <div class="transfer-table-wrapper">
        <table class="transfer-table" id="transferTable">
            <thead>
                <tr>
                    <th rowspan="2" class="col-slno header-main">Sl No</th>
                    <th rowspan="2" class="col-emp-id header-main">Emp Id</th>
                    <th rowspan="2" class="col-name header-main">Name</th>
                    <th rowspan="2" class="col-designation header-main">Designation</th>
                    <th rowspan="2" class="col-category header-main">Category</th>
                    <th colspan="2" class="header-main" style="background-color: #1e293b; color: white;">Transfer From</th>
                    <th colspan="2" class="header-main" style="background-color: #1e293b; color: white;">Transfer to</th>
                    <th rowspan="2" class="col-wef header-main">W.E.F</th>
                    <th rowspan="2" class="col-effective header-main">EFFECTIVE BRANCH</th>
                    <th rowspan="2" class="col-effective header-main">EFFECTIVE ATTENDANCE</th>
                    <th rowspan="2" class="col-esi header-main">ESI APPLICABILITY</th>
                    <th rowspan="2" class="col-yes-no header-main">Transfer Request form filled up (Yes)</th>
                    <th rowspan="2" class="col-yes-no header-main">Approved by District Head</th>
                    <th rowspan="2" class="col-remarks header-main">Remarks</th>
                    <th rowspan="2" class="header-main" style="width: 60px; min-width: 60px;">Action</th>
                </tr>
                <tr>
                    <th class="header-sub" style="background-color: #3b82f6; color: white;">Site Name</th>
                    <th class="header-sub" style="background-color: #3b82f6; color: white;">Location</th>
                    <th class="header-sub" style="background-color: #3b82f6; color: white;">Site Name</th>
                    <th class="header-sub" style="background-color: #3b82f6; color: white;">Location</th>
                </tr>
            </thead>
            <tbody id="transferTableBody">
                <!-- Rows will be dynamically generated -->
            </tbody>
        </table>
    </div>
    
    <div class="transfer-footer">
        <div class="save-status" id="saveStatus"></div>
        <button type="button" class="btn-save" id="saveBtn" onclick="saveTransfers()">
            Save Transfers
        </button>
    </div>
</div>

<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner">
        <div class="spinner"></div>
        <div>Saving transfers...</div>
    </div>
</div>

<script>
let employees = [];
let sites = [];
let designations = [];
let categories = ['FTC', 'Permanent', 'Contract', 'Temporary'];
let yesNoOptions = ['Yes', 'No'];

// Initialize page
document.addEventListener('DOMContentLoaded', function() {
    loadInitialData();
    initializeTable();
});

// Load employees, sites, and designations
async function loadInitialData() {
    try {
        const response = await fetch('<?php echo BASE_URL; ?>/api/get_transfers.php');
        const data = await response.json();
        
        if (data.success) {
            employees = data.employees || [];
            sites = data.sites || [];
            
            // (Optional) load designations if needed later
            await loadDesignations();
            
            // Always start with exactly ONE empty row for new entry
            const tbody = document.getElementById('transferTableBody');
            tbody.innerHTML = '';
            addRow(1, null);
        }
    } catch (error) {
        console.error('Error loading data:', error);
        showStatus('Error loading data. Please refresh the page.', 'error');
        // Even if there's an error, show at least 1 empty row
        const tbody = document.getElementById('transferTableBody');
        tbody.innerHTML = '';
        addRow(1, null);
    }
}

// Load designations
async function loadDesignations() {
    try {
        // Designations are already included in employee data, so we can skip this
        // If needed, we can fetch from a separate endpoint
        designations = [];
    } catch (error) {
        console.error('Error loading designations:', error);
    }
}

// Initialize table with empty rows
function initializeTable() {
    const tbody = document.getElementById('transferTableBody');
    if (tbody.children.length === 0) {
        // Rows will be added by loadInitialData
    }
}

// Add a new row
function addRow(rowNum, transferData = null) {
    const tbody = document.getElementById('transferTableBody');
    const row = document.createElement('tr');
    row.dataset.rowNum = rowNum;
    
    row.innerHTML = `
        <td class="col-slno">${rowNum}</td>
        <td class="col-emp-id">
            <select class="emp-id-select" data-row="${rowNum}" onchange="loadEmployeeDetails(${rowNum})">
                <option value="">Select</option>
                ${employees.map(emp => `
                    <option value="${emp.employee_id}" 
                            data-code="${emp.employee_code || ''}"
                            data-name="${(emp.first_name || '') + ' ' + (emp.middle_name || '') + ' ' + (emp.last_name || '')}"
                            data-designation="${emp.designation_id || ''}"
                            data-category="${emp.employee_category || 'FTC'}"
                            data-site="${emp.site_id || ''}">
                        ${emp.employee_code || ''}
                    </option>
                `).join('')}
            </select>
        </td>
        <td class="col-name">
            <input type="text" class="name-input" data-row="${rowNum}" readonly value="${transferData ? `${transferData.first_name || ''} ${transferData.middle_name || ''} ${transferData.last_name || ''}`.trim() : ''}">
        </td>
        <td class="col-designation">
            <input type="text" class="designation-input" data-row="${rowNum}" readonly value="${transferData && transferData.designation_name ? transferData.designation_name : ''}">
        </td>
        <td class="col-category">
            <select class="category-select" data-row="${rowNum}">
                <option value="">Select</option>
                ${categories.map(cat => `<option value="${cat}" ${(transferData && transferData.employee_category === cat) || (!transferData && cat === 'FTC') ? 'selected' : ''}>${cat}</option>`).join('')}
            </select>
        </td>
        <td class="col-site">
            <select class="from-site-select" data-row="${rowNum}">
                <option value="">Select</option>
                ${sites.map(site => `<option value="${site.site_id}" ${transferData && transferData.from_site_id == site.site_id ? 'selected' : ''}>${site.site_name || ''}</option>`).join('')}
            </select>
        </td>
        <td class="col-location">
            <input type="text" class="from-location-input" data-row="${rowNum}" placeholder="Location" value="${transferData && transferData.from_location ? transferData.from_location : ''}">
        </td>
        <td class="col-site">
            <select class="to-site-select" data-row="${rowNum}">
                <option value="">Select</option>
                ${sites.map(site => `<option value="${site.site_id}" ${transferData && transferData.to_site_id == site.site_id ? 'selected' : ''}>${site.site_name || ''}</option>`).join('')}
            </select>
        </td>
        <td class="col-location">
            <input type="text" class="to-location-input" data-row="${rowNum}" placeholder="Location" value="${transferData && transferData.to_location ? transferData.to_location : ''}">
        </td>
        <td class="col-wef">
            <input type="date" class="wef-input" data-row="${rowNum}" value="${transferData && transferData.transfer_date ? transferData.transfer_date : ''}">
        </td>
        <td class="col-effective">
            <select class="effective-branch-select" data-row="${rowNum}">
                <option value="">Select</option>
                ${yesNoOptions.map(opt => `<option value="${opt}" ${transferData && transferData.effective_branch === opt ? 'selected' : ''}>${opt}</option>`).join('')}
            </select>
        </td>
        <td class="col-effective">
            <select class="effective-attendance-select" data-row="${rowNum}">
                <option value="">Select</option>
                ${yesNoOptions.map(opt => `<option value="${opt}" ${transferData && transferData.effective_attendance === opt ? 'selected' : ''}>${opt}</option>`).join('')}
            </select>
        </td>
        <td class="col-esi">
            <select class="esi-select" data-row="${rowNum}">
                <option value="">Select</option>
                ${yesNoOptions.map(opt => `<option value="${opt}" ${transferData && transferData.esi_applicability === opt ? 'selected' : ''}>${opt}</option>`).join('')}
            </select>
        </td>
        <td class="col-yes-no">
            <select class="transfer-form-select" data-row="${rowNum}">
                <option value="No" ${transferData && transferData.transfer_form_filled === 'No' ? 'selected' : (!transferData ? 'selected' : '')}>No</option>
                <option value="Yes" ${transferData && transferData.transfer_form_filled === 'Yes' ? 'selected' : ''}>Yes</option>
            </select>
        </td>
        <td class="col-yes-no">
            <select class="approved-select" data-row="${rowNum}">
                <option value="">Select</option>
                <option value="Yes" ${transferData && transferData.approved_by_district_head === 'Yes' ? 'selected' : ''}>Yes</option>
                <option value="No" ${transferData && transferData.approved_by_district_head === 'No' ? 'selected' : (!transferData && rowNum === 1 ? 'selected' : '')}>No</option>
            </select>
        </td>
        <td class="col-remarks">
            <input type="text" class="remarks-input" data-row="${rowNum}" placeholder="Remarks" value="${transferData && transferData.transfer_reason ? transferData.transfer_reason : ''}">
        </td>
        <td style="text-align: center;">
            <button type="button" onclick="deleteRow(${rowNum})" class="btn-delete" title="Delete Row" style="background: #dc3545; color: white; border: none; padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 11px;">✕</button>
        </td>
    `;
    
    tbody.appendChild(row);
}

// Add a new row at the end
function addNewRow() {
    const tbody = document.getElementById('transferTableBody');
    const rowNum = tbody.children.length + 1;
    addRow(rowNum);
    updateRowNumbers();
}

// Update row numbers
function updateRowNumbers() {
    const rows = document.querySelectorAll('#transferTableBody tr');
    rows.forEach((row, index) => {
        row.dataset.rowNum = index + 1;
        const slNoCell = row.querySelector('.col-slno');
        if (slNoCell) {
            slNoCell.textContent = index + 1;
        }
    });
}

// Load employee details when employee is selected
function loadEmployeeDetails(rowNum) {
    const row = document.querySelector(`tr[data-row-num="${rowNum}"]`);
    if (!row) return;
    
    const empSelect = row.querySelector('.emp-id-select');
    const selectedOption = empSelect.options[empSelect.selectedIndex];
    
    if (!selectedOption.value) {
        // Clear fields
        row.querySelector('.name-input').value = '';
        row.querySelector('.designation-input').value = '';
        row.querySelector('.from-site-select').value = '';
        return;
    }
    
    // Load full employee details via API for accurate data
    loadEmployeeDetailsAPI(rowNum, selectedOption.value);
}

// Load employee details via API
async function loadEmployeeDetailsAPI(rowNum, employeeId) {
    try {
        const response = await fetch(`<?php echo BASE_URL; ?>/api/get_employee_for_transfer.php?employee_id=${employeeId}`);
        const data = await response.json();
        
        if (data.success && data.employee) {
            const emp = data.employee;
            const row = document.querySelector(`tr[data-row-num="${rowNum}"]`);
            if (!row) return;
            
            // Update name
            const fullName = `${emp.first_name || ''} ${emp.middle_name || ''} ${emp.last_name || ''}`.trim();
            row.querySelector('.name-input').value = fullName;
            
            // Update designation
            if (emp.designation_name) {
                row.querySelector('.designation-input').value = emp.designation_name;
            }
            
            // Update category
            if (emp.employee_category) {
                row.querySelector('.category-select').value = emp.employee_category;
            } else {
                row.querySelector('.category-select').value = 'FTC';
            }
            
            // Update from site
            if (emp.site_id) {
                row.querySelector('.from-site-select').value = emp.site_id;
            }
        }
    } catch (error) {
        console.error('Error loading employee details:', error);
    }
}

// Clear all rows
function clearAll() {
    if (!confirm('Are you sure you want to clear all data?')) {
        return;
    }
    
    const rows = document.querySelectorAll('#transferTableBody tr');
    rows.forEach((row, index) => {
        const inputs = row.querySelectorAll('input, select');
        inputs.forEach(input => {
            if (input.type === 'date') {
                input.value = '';
            } else if (input.tagName === 'SELECT') {
                if (input.classList.contains('category-select')) {
                    input.value = 'FTC';
                } else if (input.classList.contains('transfer-form-select')) {
                    input.value = 'No';
                } else if (input.classList.contains('approved-select')) {
                    input.value = index === 0 ? 'Yes' : 'No';
                } else {
                    input.value = '';
                }
            } else {
                input.value = '';
            }
        });
    });
    
    showStatus('All data cleared.', 'success');
    setTimeout(() => showStatus('', ''), 2000);
}

// Save all transfers
async function saveTransfers() {
    const rows = document.querySelectorAll('#transferTableBody tr');
    const transfers = [];
    
    rows.forEach(row => {
        const empSelect = row.querySelector('.emp-id-select');
        const employeeId = empSelect ? empSelect.value : '';
        
        if (!employeeId) return; // Skip empty rows
        
        const transferData = {
            employee_id: employeeId,
            category: row.querySelector('.category-select')?.value || '',
            from_site_id: row.querySelector('.from-site-select')?.value || '',
            from_location: row.querySelector('.from-location-input')?.value || '',
            to_site_id: row.querySelector('.to-site-select')?.value || '',
            to_location: row.querySelector('.to-location-input')?.value || '',
            wef_date: row.querySelector('.wef-input')?.value || '',
            effective_branch: row.querySelector('.effective-branch-select')?.value || '',
            effective_attendance: row.querySelector('.effective-attendance-select')?.value || '',
            esi_applicability: row.querySelector('.esi-select')?.value || '',
            transfer_form_filled: row.querySelector('.transfer-form-select')?.value || 'No',
            approved_by_district_head: row.querySelector('.approved-select')?.value || '',
            remarks: row.querySelector('.remarks-input')?.value || ''
        };
        
        // Only add if "Transfer to" site is selected
        if (transferData.to_site_id) {
            transfers.push(transferData);
        }
    });
    
    if (transfers.length === 0) {
        showStatus('Please fill at least one complete transfer record.', 'error');
        return;
    }
    
    // Show loading
    document.getElementById('loadingOverlay').classList.add('active');
    document.getElementById('saveBtn').disabled = true;
    
    try {
        const response = await fetch('<?php echo BASE_URL; ?>/api/save_transfers_simple.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ transfers: transfers })
        });
        
        const responseText = await response.text();
        console.log('Server response:', responseText);
        
        let data;
        try {
            data = JSON.parse(responseText);
        } catch (parseError) {
            console.error('JSON parse error:', parseError);
            showStatus('Server error: Invalid response. Check console for details.', 'error');
            return;
        }
        
        if (data.success) {
            showStatus(data.message || `Successfully saved ${data.saved_count || transfers.length} transfer(s)!`, 'success');
            // Reload the data without full page reload
            setTimeout(() => {
                loadInitialData();
            }, 1000);
        } else {
            console.error('Save error:', data);
            showStatus(data.message || 'Error saving transfers. Please try again.', 'error');
        }
    } catch (error) {
        console.error('Error saving transfers:', error);
        showStatus('Network error: ' + error.message, 'error');
    } finally {
        document.getElementById('loadingOverlay').classList.remove('active');
        document.getElementById('saveBtn').disabled = false;
    }
}

// Show status message
function showStatus(message, type) {
    // Safely get elements with null checks
    const statusEl = document.getElementById('saveStatus');
    const errorBox = document.getElementById('errorMessage');
    const successBox = document.getElementById('successMessage');
    
    // Update status element if it exists
    if (statusEl) {
        statusEl.textContent = message || '';
        statusEl.className = 'save-status' + (type ? ' ' + type : '');
    }
    
    // Handle alert boxes with null checks
    if (type === 'error') {
        if (errorBox) {
            errorBox.textContent = message || '';
            errorBox.style.display = 'block';
            setTimeout(() => { if (errorBox) errorBox.style.display = 'none'; }, 5000);
        }
        if (successBox) {
            successBox.style.display = 'none';
        }
    } else if (type === 'success') {
        if (successBox) {
            successBox.textContent = message || '';
            successBox.style.display = 'block';
            setTimeout(() => { if (successBox) successBox.style.display = 'none'; }, 5000);
        }
        if (errorBox) {
            errorBox.style.display = 'none';
        }
    } else {
        if (errorBox) errorBox.style.display = 'none';
        if (successBox) successBox.style.display = 'none';
    }
    
    // Also log to console for debugging
    if (message) {
        console.log(`[${type || 'info'}] ${message}`);
    }
}

// Delete a specific row
function deleteRow(rowNum) {
    const tbody = document.getElementById('transferTableBody');
    if (tbody.children.length <= 1) {
        showStatus('Cannot delete the last row. At least one row is required.', 'error');
        return;
    }
    
    const row = document.querySelector(`tr[data-row-num="${rowNum}"]`);
    if (row) {
        row.remove();
        updateRowNumbers();
        showStatus('Row deleted.', 'success');
    }
}
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>

