<div class="page-title d-flex justify-content-between align-items-center">
    <h2><i class="bi bi-database"></i> Master Data Management</h2>
    <div>
        <button class="btn btn-success me-2" onclick="exportMasterData()" id="exportBtn">
            <i class="bi bi-download"></i> Export All Data
        </button>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#uploadModal">
            <i class="bi bi-upload"></i> Upload CSV/Excel
        </button>
    </div>
</div>

<div class="row mb-4">
    <div class="col-md-4">
        <div class="stat-card primary">
            <h6 class="text-muted">Total Data</h6>
            <h3><?= number_format($stats['total_data']) ?></h3>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card success">
            <h6 class="text-muted">Assigned</h6>
            <h3 class="text-success"><?= number_format($stats['assigned_data']) ?></h3>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card info">
            <h6 class="text-muted">Unassigned</h6>
            <h3><?= number_format($stats['unassigned_data']) ?></h3>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <?php if (isset($use_server_side) && $use_server_side): ?>
        <!-- Server-side DataTables for large datasets (2.1M+ records) -->
        <div class="table-responsive">
            <table id="masterDataTable" class="table table-hover" style="width:100%">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Mobile</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Address</th>
                        <th>Status</th>
                        <th>Uploaded At</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
        <?php else: ?>
        <!-- Client-side table for smaller datasets -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Mobile</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Gender</th>
                        <th>City</th>
                        <th>Address</th>
                        <th>Status</th>
                        <th>Uploaded At</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($data_list)): ?>
                        <?php foreach ($data_list as $data): ?>
                            <tr>
                                <td><?= $data->id ?></td>
                                <td><?= $data->mobile ?></td>
                                <td><?= $data->name ?></td>
                                <td><?= $data->email ?></td>
                                <td>
                                    <?php if (!empty($data->gender)): ?>
                                        <span class="badge <?= $data->gender === 'male' ? 'bg-primary' : ($data->gender === 'female' ? 'bg-danger' : 'bg-secondary') ?>">
                                            <?= ucfirst($data->gender) ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">N/A</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= !empty($data->city) ? $data->city : 'N/A' ?></td>
                                <td><?= substr($data->address ?? '', 0, 30) ?><?= strlen($data->address ?? '') > 30 ? '...' : '' ?></td>
                                <td>
                                    <?php if ($data->is_assigned): ?>
                                        <span class="badge bg-success">Assigned</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">Unassigned</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= date('M d, Y', strtotime($data->uploaded_at)) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" class="text-center">No data found</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($pagination['total_pages'] > 1): ?>
            <nav>
                <ul class="pagination justify-content-center">
                    <?php for ($i = 1; $i <= min($pagination['total_pages'], 10); $i++): ?>
                        <li class="page-item <?= $i == $pagination['current_page'] ? 'active' : '' ?>">
                            <a class="page-link" href="<?= $pagination['base_url'] ?>?page=<?= $i ?>"><?= $i ?></a>
                        </li>
                    <?php endfor; ?>
                    <?php if ($pagination['total_pages'] > 10): ?>
                        <li class="page-item disabled"><span class="page-link">...</span></li>
                        <li class="page-item">
                            <a class="page-link" href="<?= $pagination['base_url'] ?>?page=<?= $pagination['total_pages'] ?>"><?= $pagination['total_pages'] ?></a>
                        </li>
                    <?php endif; ?>
                </ul>
            </nav>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<!-- Export Progress Modal -->
<div class="modal fade" id="exportModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-download"></i> Exporting Master Data</h5>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <p class="text-muted">Exporting <span id="exportTotalRecords">0</span> records...</p>
                    <div class="progress" style="height: 25px;">
                        <div id="exportProgress" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%;">0%</div>
                    </div>
                </div>
                <div id="exportStatus" class="alert alert-info">
                    <i class="bi bi-hourglass-split"></i> Preparing export...
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Upload Modal -->
<div class="modal fade" id="uploadModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Upload Master Data</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="uploadForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label class="form-label">Select CSV/Excel File *</label>
                        <input type="file" class="form-control" name="data_file" id="data_file" accept=".csv,.xls,.xlsx" required>
                        <small class="text-muted">Maximum file size: 100MB (Supports up to 2.1M+ records)</small>
                    </div>
                    
                    <div id="uploadProgress" class="progress mb-3" style="display:none;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                    </div>
                    <div id="uploadStatus" class="alert alert-info" style="display:none;"></div>
                    
                    <div class="alert alert-info">
                        <strong>CSV Format:</strong><br>
                        Column 1: Mobile (required)<br>
                        Column 2: Name<br>
                        Column 3: Email<br>
                        Column 4: Address<br>
                        Column 5-7: Custom Fields (optional)<br>
                        <hr>
                        <small><i class="bi bi-info-circle"></i> For large files (>100K rows), upload may take several minutes.</small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="uploadBtn" onclick="uploadData()">
                    <i class="bi bi-upload"></i> Upload
                </button>
            </div>
        </div>
    </div>
</div>

<script>
<?php if (isset($use_server_side) && $use_server_side): ?>
// Initialize server-side DataTables for large datasets
$(document).ready(function() {
    $('#masterDataTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '<?= base_url('admin/master-data-ajax') ?>',
            type: 'GET'
        },
        pageLength: 50,
        lengthMenu: [[25, 50, 100, 200], [25, 50, 100, 200]],
        order: [[0, 'desc']],
        columns: [
            { data: 0 },
            { data: 1 },
            { data: 2 },
            { data: 3 },
            { data: 4 },
            { data: 5 },
            { data: 6 }
        ],
        language: {
            processing: '<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div>',
            info: 'Showing _START_ to _END_ of _TOTAL_ records (optimized for 2.1M+ data)',
            infoFiltered: '(filtered from _MAX_ total records)'
        },
        drawCallback: function() {
            // Reinitialize any tooltips or popovers
        }
    });
});
<?php endif; ?>

// Export Master Data with batch processing for 3M+ records
function exportMasterData() {
    const btn = $('#exportBtn');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Exporting...');
    
    // Get total count first
    $.get('<?= base_url('admin/master_data_count') ?>', function(response) {
        if (!response.success) {
            alert('Error: ' + response.message);
            btn.prop('disabled', false).html('<i class="bi bi-download"></i> Export All Data');
            return;
        }
        
        const totalRecords = response.count;
        if (totalRecords === 0) {
            alert('No data to export.');
            btn.prop('disabled', false).html('<i class="bi bi-download"></i> Export All Data');
            return;
        }
        
        // Show modal
        $('#exportTotalRecords').text(totalRecords.toLocaleString());
        $('#exportModal').modal('show');
        
        // Start batch export
        startBatchExport(totalRecords);
    });
}

function startBatchExport(totalRecords) {
    const batchSize = 50000; // 50K records per batch
    const totalBatches = Math.ceil(totalRecords / batchSize);
    let currentBatch = 0;
    let allData = [];
    
    function exportNextBatch() {
        if (currentBatch >= totalBatches) {
            // All batches complete - generate CSV
            generateCSV(allData, totalRecords);
            return;
        }
        
        const offset = currentBatch * batchSize;
        currentBatch++;
        
        const progress = Math.round((currentBatch / totalBatches) * 100);
        $('#exportProgress').css('width', progress + '%').text(progress + '%');
        $('#exportStatus').html(`<i class="bi bi-hourglass-split"></i> Fetching batch ${currentBatch} of ${totalBatches}... (${(offset + batchSize).toLocaleString()} / ${totalRecords.toLocaleString()})`);
        
        $.ajax({
            url: '<?= base_url('admin/master_data_export_batch') ?>',
            method: 'GET',
            data: {
                offset: offset,
                limit: batchSize
            },
            dataType: 'json',
            success: function(response) {
                if (response.success && response.data) {
                    allData = allData.concat(response.data);
                    // Continue to next batch
                    setTimeout(exportNextBatch, 100); // Small delay to prevent overwhelming server
                } else {
                    alert('Error fetching data: ' + (response.message || 'Unknown error'));
                    resetExport();
                }
            },
            error: function(xhr, status, error) {
                console.error('Export error:', error);
                alert('Error during export: ' + error);
                resetExport();
            }
        });
    }
    
    exportNextBatch();
}

function generateCSV(data, totalRecords) {
    $('#exportStatus').removeClass('alert-info').addClass('alert-success')
        .html('<i class="bi bi-check-circle"></i> Generating CSV file...');
    
    try {
        // Create CSV content
        let csvContent = 'ID,Mobile,Name,Email,Address,Custom Field 1,Custom Field 2,Custom Field 3,Status,Uploaded At\n';
        
        data.forEach(row => {
            csvContent += [
                row.id || '',
                `"${(row.mobile || '').replace(/"/g, '""')}"`,
                `"${(row.name || '').replace(/"/g, '""')}"`,
                `"${(row.email || '').replace(/"/g, '""')}"`,
                `"${(row.address || '').replace(/"/g, '""')}"`,
                `"${(row.custom_field1 || '').replace(/"/g, '""')}"`,
                `"${(row.custom_field2 || '').replace(/"/g, '""')}"`,
                `"${(row.custom_field3 || '').replace(/"/g, '""')}"`,
                row.is_assigned ? 'Assigned' : 'Unassigned',
                row.uploaded_at || ''
            ].join(',') + '\n';
        });
        
        // Create blob and download
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        const timestamp = new Date().toISOString().split('T')[0];
        
        link.setAttribute('href', url);
        link.setAttribute('download', `master_data_${timestamp}_${totalRecords}_records.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        $('#exportStatus').html('<i class="bi bi-check-circle"></i> Export completed successfully! Downloaded ' + totalRecords.toLocaleString() + ' records.');
        
        setTimeout(function() {
            $('#exportModal').modal('hide');
            resetExport();
        }, 2000);
        
    } catch (error) {
        console.error('CSV generation error:', error);
        alert('Error generating CSV: ' + error.message);
        resetExport();
    }
}

function resetExport() {
    $('#exportBtn').prop('disabled', false).html('<i class="bi bi-download"></i> Export All Data');
    $('#exportProgress').css('width', '0%').text('0%');
    $('#exportStatus').removeClass('alert-success alert-danger').addClass('alert-info')
        .html('<i class="bi bi-hourglass-split"></i> Preparing export...');
}

function uploadData() {
    const formData = new FormData($('#uploadForm')[0]);
    const fileInput = document.getElementById('data_file');
    const file = fileInput.files[0];
    
    if (!file) {
        alert('Please select a file to upload.');
        return;
    }
    
    // Check file size - use large upload endpoint for files > 5MB
    const useLargeUpload = file.size > 5 * 1024 * 1024;
    const uploadUrl = useLargeUpload 
        ? '<?= base_url('admin/master-data-upload-large') ?>'
        : '<?= base_url('admin/master_data_upload') ?>';
    
    // Show progress
    $('#uploadProgress').show();
    $('#uploadStatus').show().html('<i class="bi bi-hourglass-split"></i> Processing... This may take several minutes for large files.');
    $('#uploadBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Uploading...');
    
    $.ajax({
        url: uploadUrl,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        timeout: 600000, // 10 minute timeout for large files
        xhr: function() {
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    var percent = Math.round((e.loaded / e.total) * 100);
                    $('#uploadProgress .progress-bar').css('width', percent + '%').text(percent + '%');
                }
            }, false);
            return xhr;
        },
        success: function(response) {
            if (response.success) {
                $('#uploadStatus').removeClass('alert-info').addClass('alert-success')
                    .html('<i class="bi bi-check-circle"></i> ' + response.message);
                setTimeout(function() {
                    location.reload();
                }, 2000);
            } else {
                $('#uploadStatus').removeClass('alert-info').addClass('alert-danger')
                    .html('<i class="bi bi-x-circle"></i> Error: ' + response.message);
                $('#uploadBtn').prop('disabled', false).html('<i class="bi bi-upload"></i> Upload');
            }
        },
        error: function(xhr, status, error) {
            var errorMsg = 'An error occurred during upload.';
            if (status === 'timeout') {
                errorMsg = 'Upload timed out. Please try with a smaller file or contact support.';
            }
            $('#uploadStatus').removeClass('alert-info').addClass('alert-danger')
                .html('<i class="bi bi-x-circle"></i> ' + errorMsg);
            $('#uploadBtn').prop('disabled', false).html('<i class="bi bi-upload"></i> Upload');
        }
    });
}
</script>

