<?php

define('MIGRATION_ACCESS', true);

session_start();



// Check authentication

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {

    header('Location: ../index.php');

    exit;

}



// Include database connection

require_once '../config.php';

require_once 'config.php';

require_once 'validation/validator.php';

require_once 'cleansing/phone_formatter.php';

require_once 'cleansing/name_formatter.php';



// Get database connection

$conn = getDBConnection();



// Helper function to get table counts

function getTableCount($conn, $table) {

    if (!$conn) return 0;

    $result = $conn->query("SELECT COUNT(*) as count FROM $table");

    if ($result) {

        $row = $result->fetch_assoc();

        return $row['count'];

    }

    return 0;

}



// Get statistics for dashboard

$studentCount = getTableCount($conn, 'students');

$staffCount = getTableCount($conn, 'staff');

$feesCount = getTableCount($conn, 'fee_structures');

$paymentsCount = getTableCount($conn, 'payments');

$subjectsCount = getTableCount($conn, 'subjects');

$scoresCount = getTableCount($conn, 'scores');

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Data Migration Wizard - School Management System</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <link rel="stylesheet" href="assets/css/migration.css">

    <style>

        .migration-step {

            background: white;

            border-radius: 10px;

            padding: 20px;

            margin-bottom: 20px;

            box-shadow: 0 2px 10px rgba(0,0,0,0.1);

        }

        .step-indicator {

            display: flex;

            justify-content: space-between;

            margin-bottom: 30px;

            position: relative;

        }

        .step {

            flex: 1;

            text-align: center;

            padding: 15px;

            background: #f8f9fa;

            border-radius: 8px;

            margin: 0 5px;

            position: relative;

            z-index: 1;

        }

        .step.active {

            background: #667eea;

            color: white;

        }

        .step.completed {

            background: #28a745;

            color: white;

        }

        .step .step-number {

            width: 30px;

            height: 30px;

            background: white;

            color: #333;

            border-radius: 50%;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            margin-bottom: 10px;

            font-weight: bold;

        }

        .step.active .step-number {

            background: #667eea;

            color: white;

        }

        .upload-area {

            border: 2px dashed #dee2e6;

            border-radius: 10px;

            padding: 40px;

            text-align: center;

            cursor: pointer;

            transition: all 0.3s;

        }

        .upload-area:hover {

            border-color: #667eea;

            background: #f8f9fa;

        }

        .upload-area i {

            font-size: 48px;

            color: #667eea;

            margin-bottom: 15px;

        }

        .template-card {

            border: 1px solid #dee2e6;

            border-radius: 8px;

            padding: 15px;

            margin-bottom: 15px;

            transition: all 0.3s;

            cursor: pointer;

        }

        .template-card:hover {

            box-shadow: 0 5px 15px rgba(0,0,0,0.1);

            border-color: #667eea;

        }

        .template-card.selected {

            border: 2px solid #667eea;

            background: #f0f3ff;

        }

        .validation-issue {

            padding: 10px;

            margin: 5px 0;

            border-radius: 5px;

        }

        .issue-error {

            background: #fee;

            border-left: 4px solid #e74c3c;

        }

        .issue-warning {

            background: #fff3e0;

            border-left: 4px solid #f39c12;

        }

        .issue-success {

            background: #e8f5e9;

            border-left: 4px solid #27ae60;

        }

        .preview-table {

            font-size: 14px;

            max-height: 400px;

            overflow-y: auto;

        }

        .preview-table table {

            width: 100%;

            border-collapse: collapse;

        }

        .preview-table th {

            background: #f8f9fa;

            position: sticky;

            top: 0;

        }

        .stat-card {

            background: white;

            border-radius: 10px;

            padding: 20px;

            box-shadow: 0 2px 10px rgba(0,0,0,0.1);

            text-align: center;

        }

        .stat-card h2 {

            margin: 10px 0;

            color: #667eea;

        }

        .stat-card i {

            font-size: 2.5rem;

            color: #667eea;

        }

    </style>

</head>

<body>

    <div class="container-fluid py-4">

        <!-- Header -->

        <div class="d-flex justify-content-between align-items-center mb-4">

            <h1><i class="fas fa-database me-3 text-primary"></i>Data Migration Wizard</h1>

            <div>

                <a href="../dashboard.php" class="btn btn-outline-secondary me-2">

                    <i class="fas fa-arrow-left me-2"></i>Back to Dashboard

                </a>

                <button class="btn btn-primary" onclick="window.location.reload()">

                    <i class="fas fa-sync-alt me-2"></i>Refresh

                </button>

            </div>

        </div>



        <!-- Statistics Dashboard -->

        <div class="row mb-4">

            <div class="col-md-2">

                <div class="stat-card">

                    <i class="fas fa-users"></i>

                    <h2><?php echo $studentCount; ?></h2>

                    <p class="text-muted">Students</p>

                </div>

            </div>

            <div class="col-md-2">

                <div class="stat-card">

                    <i class="fas fa-chalkboard-teacher"></i>

                    <h2><?php echo $staffCount; ?></h2>

                    <p class="text-muted">Staff</p>

                </div>

            </div>

            <div class="col-md-2">

                <div class="stat-card">

                    <i class="fas fa-money-bill-wave"></i>

                    <h2><?php echo $feesCount; ?></h2>

                    <p class="text-muted">Fee Structures</p>

                </div>

            </div>

            <div class="col-md-2">

                <div class="stat-card">

                    <i class="fas fa-credit-card"></i>

                    <h2><?php echo $paymentsCount; ?></h2>

                    <p class="text-muted">Payments</p>

                </div>

            </div>

            <div class="col-md-2">

                <div class="stat-card">

                    <i class="fas fa-book"></i>

                    <h2><?php echo $subjectsCount; ?></h2>

                    <p class="text-muted">Subjects</p>

                </div>

            </div>

            <div class="col-md-2">

                <div class="stat-card">

                    <i class="fas fa-chart-line"></i>

                    <h2><?php echo $scoresCount; ?></h2>

                    <p class="text-muted">Scores</p>

                </div>

            </div>

        </div>



        <!-- Migration Steps -->

        <div class="step-indicator">

            <div class="step active" id="step1">

                <div class="step-number">1</div>

                <div>Choose Source</div>

            </div>

            <div class="step" id="step2">

                <div class="step-number">2</div>

                <div>Upload Data</div>

            </div>

            <div class="step" id="step3">

                <div class="step-number">3</div>

                <div>Validate & Cleanse</div>

            </div>

            <div class="step" id="step4">

                <div class="step-number">4</div>

                <div>Preview & Map</div>

            </div>

            <div class="step" id="step5">

                <div class="step-number">5</div>

                <div>Import</div>

            </div>

        </div>



        <!-- Step 1: Source Selection -->

        <div class="migration-step" id="step1-content">

            <h4 class="mb-4"><i class="fas fa-database me-2 text-primary"></i>Select Data Source</h4>

            

            <div class="row">

                <div class="col-md-4">

                    <div class="template-card text-center" onclick="selectSource('csv')">

                        <i class="fas fa-file-csv fa-3x text-primary mb-3"></i>

                        <h5>CSV/Excel Files</h5>

                        <p class="text-muted">Upload from spreadsheets</p>

                        <div class="mt-3">

                            <span class="badge bg-success">Most Common</span>

                        </div>

                    </div>

                </div>

                <div class="col-md-4">

                    <div class="template-card text-center" onclick="selectSource('gesmis')">

                        <i class="fas fa-school fa-3x text-success mb-3"></i>

                        <h5>GESMIS Export</h5>

                        <p class="text-muted">Government school data</p>

                        <div class="mt-3">

                            <span class="badge bg-info">Ghana Education Service</span>

                        </div>

                    </div>

                </div>

                <div class="col-md-4">

                    <div class="template-card text-center" onclick="selectSource('oneroster')">

                        <i class="fas fa-globe fa-3x text-warning mb-3"></i>

                        <h5>OneRoster Format</h5>

                        <p class="text-muted">International schools</p>

                        <div class="mt-3">

                            <span class="badge bg-secondary">IMS Global</span>

                        </div>

                    </div>

                </div>

            </div>

            

            <div class="row mt-4">

                <div class="col-md-4">

                    <div class="template-card text-center" onclick="selectSource('manual')">

                        <i class="fas fa-pencil-alt fa-3x text-info mb-3"></i>

                        <h5>Manual Entry</h5>

                        <p class="text-muted">Enter data directly</p>

                        <div class="mt-3">

                            <span class="badge bg-primary">Small Batches</span>

                        </div>

                    </div>

                </div>

            </div>

            

            <div class="text-center mt-4">

                <button class="btn btn-primary" onclick="nextStep(1)" disabled id="continue-btn">

                    Continue <i class="fas fa-arrow-right ms-2"></i>

                </button>

            </div>

        </div>



        <!-- Step 2: Upload Area -->

        <div class="migration-step" id="step2-content" style="display: none;">

            <h4 class="mb-4"><i class="fas fa-upload me-2 text-primary"></i>Upload Your Data</h4>

            

            <div class="row">

                <div class="col-md-8">

                    <div class="upload-area" id="uploadArea">

                        <i class="fas fa-cloud-upload-alt"></i>

                        <h5>Drag & Drop Files Here</h5>

                        <p class="text-muted">or click to browse</p>

                        <input type="file" id="fileInput" multiple accept=".csv,.xlsx,.xls,.txt,.zip" style="display: none;">

                        <div id="fileList" class="mt-3"></div>

                    </div>

                    <div id="manual-entry-info" class="alert alert-info mt-3" style="display: none;">

                        <i class="fas fa-info-circle me-2"></i>

                        You've selected manual entry. Click "Continue" to proceed to data entry forms.

                    </div>

                </div>

                <div class="col-md-4">

                    <div class="card">

                        <div class="card-header bg-primary text-white">

                            <h6 class="mb-0"><i class="fas fa-download me-2"></i>Download Templates</h6>

                        </div>

                        <div class="card-body">

                            <div class="list-group">

                                <a href="templates/students_template.csv" class="list-group-item list-group-item-action">

                                    <i class="fas fa-users me-2"></i> Students Template

                                </a>

                                <a href="templates/staff_template.csv" class="list-group-item list-group-item-action">

                                    <i class="fas fa-chalkboard-teacher me-2"></i> Staff Template

                                </a>

                                <a href="templates/fees_template.csv" class="list-group-item list-group-item-action">

                                    <i class="fas fa-money-bill-wave me-2"></i> Fee Structure Template

                                </a>

                                <a href="templates/payments_template.csv" class="list-group-item list-group-item-action">

                                    <i class="fas fa-credit-card me-2"></i> Payment History Template

                                </a>

                                <a href="templates/subjects_template.csv" class="list-group-item list-group-item-action">

                                    <i class="fas fa-book me-2"></i> Subjects Template

                                </a>

                                <a href="templates/staff_pay_template.csv" class="list-group-item list-group-item-action">

                                    <i class="fas fa-money-check-dollar me-2"></i> Staff Salaries (Payroll) Template

                                </a>

                                <a href="templates/student_health_template.csv" class="list-group-item list-group-item-action">

                                    <i class="fas fa-heart-pulse me-2"></i> Student Health Template

                                </a>

                                <a href="templates/student_leadership_template.csv" class="list-group-item list-group-item-action">

                                    <i class="fas fa-crown me-2"></i> Leadership Roles Template

                                </a>

                                <a href="templates/student_activities_template.csv" class="list-group-item list-group-item-action">

                                    <i class="fas fa-medal me-2"></i> Student Activities Template

                                </a>

                                <a href="templates/biometric_enroll_template.csv" class="list-group-item list-group-item-action">

                                    <i class="fas fa-fingerprint me-2"></i> Biometric Enrolment Template

                                </a>

                            </div>

                        </div>

                    </div>

                </div>

            </div>

            

            <div class="text-center mt-4">

                <button class="btn btn-secondary me-2" onclick="prevStep(2)">

                    <i class="fas fa-arrow-left me-2"></i>Back

                </button>

                <button class="btn btn-primary" onclick="uploadAndValidate()" id="validateBtn" disabled>

                    Validate Data <i class="fas fa-check ms-2"></i>

                </button>

                <button class="btn btn-success" onclick="goToManualEntry()" id="manualBtn" style="display: none;">

                    Go to Manual Entry <i class="fas fa-arrow-right ms-2"></i>

                </button>

            </div>

        </div>



        <!-- Step 3: Validation & Cleansing -->

        <div class="migration-step" id="step3-content" style="display: none;">

            <h4 class="mb-4"><i class="fas fa-check-circle me-2 text-primary"></i>Validate & Cleanse Data</h4>

            

            <div class="row">

                <div class="col-md-6">

                    <div class="card mb-3">

                        <div class="card-header bg-warning text-white">

                            <h6 class="mb-0"><i class="fas fa-exclamation-triangle me-2"></i>Issues Found</h6>

                        </div>

                        <div class="card-body" id="issues-container">

                            <p class="text-muted">No issues detected yet</p>

                        </div>

                    </div>

                </div>

                <div class="col-md-6">

                    <div class="card mb-3">

                        <div class="card-header bg-success text-white">

                            <h6 class="mb-0"><i class="fas fa-magic me-2"></i>Auto-Fix Suggestions</h6>

                        </div>

                        <div class="card-body" id="suggestions-container">

                            <p class="text-muted">Run validation to see suggestions</p>

                        </div>

                    </div>

                </div>

            </div>

            

            <div class="row mt-3">

                <div class="col-12">

                    <div id="duplicate-warning"></div>

                    <div id="existing-warning"></div>

                </div>

            </div>

            

            <div class="row mt-3">

                <div class="col-12">

                    <div class="card">

                        <div class="card-header bg-info text-white">

                            <h6 class="mb-0"><i class="fas fa-chart-bar me-2"></i>Data Quality Report</h6>

                        </div>

                        <div class="card-body">

                            <div class="row text-center">

                                <div class="col-md-3">

                                    <h3 id="total-records">0</h3>

                                    <p class="text-muted">Total Records</p>

                                </div>

                                <div class="col-md-3">

                                    <h3 id="valid-records">0</h3>

                                    <p class="text-muted">Valid</p>

                                </div>

                                <div class="col-md-3">

                                    <h3 id="warning-records">0</h3>

                                    <p class="text-muted">Warnings</p>

                                </div>

                                <div class="col-md-3">

                                    <h3 id="error-records">0</h3>

                                    <p class="text-muted">Errors</p>

                                </div>

                            </div>

                        </div>

                    </div>

                </div>

            </div>

            

            <div class="text-center mt-4">

                <button class="btn btn-secondary me-2" onclick="prevStep(3)">

                    <i class="fas fa-arrow-left me-2"></i>Back

                </button>

                <button class="btn btn-primary" onclick="nextStep(3)" id="continue-to-preview">

                    Continue to Preview <i class="fas fa-arrow-right ms-2"></i>

                </button>

            </div>

        </div>



        <!-- Step 4: Preview & Field Mapping -->

        <div class="migration-step" id="step4-content" style="display: none;">

            <h4 class="mb-4"><i class="fas fa-eye me-2 text-primary"></i>Preview & Map Fields</h4>

            

            <div class="row">

                <div class="col-md-12">

                    <div class="preview-table" id="preview-container">

                        <!-- Preview table will be loaded here -->

                    </div>

                </div>

            </div>

            

            <div class="text-center mt-4">

                <button class="btn btn-secondary me-2" onclick="prevStep(4)">

                    <i class="fas fa-arrow-left me-2"></i>Back

                </button>

                <button class="btn btn-primary" onclick="startImport()">

                    Start Import <i class="fas fa-play ms-2"></i>

                </button>

            </div>

        </div>



        <!-- Step 5: Import Progress -->

        <div class="migration-step" id="step5-content" style="display: none;">

            <h4 class="mb-4"><i class="fas fa-sync-alt fa-spin me-2 text-primary"></i>Importing Data</h4>

            

            <div class="progress mb-3" style="height: 30px;">

                <div class="progress-bar progress-bar-striped progress-bar-animated" 

                     id="import-progress" 

                     role="progressbar" 

                     style="width: 0%">

                    0%

                </div>

            </div>

            

            <div id="import-log" class="border rounded p-3" style="max-height: 300px; overflow-y: auto;">

                <p class="text-muted">Starting import...</p>

            </div>

            

            <div class="text-center mt-4" id="import-complete" style="display: none;">

                <i class="fas fa-check-circle fa-4x text-success mb-3"></i>

                <h4>Import Complete!</h4>

                <p id="import-summary"></p>

                <button class="btn btn-success mt-3" onclick="finishMigration()">

                    <i class="fas fa-flag-checkered me-2"></i>Finish

                </button>

            </div>

        </div>

    </div>



    <!-- JavaScript -->

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script src="assets/js/migration.js"></script>

    

    <script>

        let currentStep = 1;

        let selectedSource = null;

        let uploadedFiles = [];

        let validationResults = null;

        

        function selectSource(source) {

            selectedSource = source;

            document.querySelectorAll('.template-card').forEach(card => {

                card.classList.remove('selected');

            });

            event.currentTarget.classList.add('selected');

            document.getElementById('continue-btn').disabled = false;

            

            // Show/hide appropriate elements for step 2

            if (source === 'manual') {

                document.getElementById('uploadArea').style.display = 'none';

                document.getElementById('manual-entry-info').style.display = 'block';

                document.getElementById('validateBtn').style.display = 'none';

                document.getElementById('manualBtn').style.display = 'inline-block';

            } else {

                document.getElementById('uploadArea').style.display = 'block';

                document.getElementById('manual-entry-info').style.display = 'none';

                document.getElementById('validateBtn').style.display = 'inline-block';

                document.getElementById('manualBtn').style.display = 'none';

            }

        }

        

        function nextStep(step) {

            document.getElementById(`step${step}-content`).style.display = 'none';

            document.getElementById(`step${step + 1}-content`).style.display = 'block';

            

            document.querySelectorAll('.step').forEach(s => s.classList.remove('active'));

            document.getElementById(`step${step + 1}`).classList.add('active');

            

            if (step === 1) {

                document.getElementById(`step${step}`).classList.add('completed');

            }

            

            currentStep = step + 1;

        }

        

        function prevStep(step) {

            document.getElementById(`step${step}-content`).style.display = 'none';

            document.getElementById(`step${step - 1}-content`).style.display = 'block';

            

            document.querySelectorAll('.step').forEach(s => s.classList.remove('active'));

            document.getElementById(`step${step - 1}`).classList.add('active');

            

            currentStep = step - 1;

        }

        

        // File upload handling

        document.getElementById('uploadArea').addEventListener('click', function() {

            document.getElementById('fileInput').click();

        });

        

        document.getElementById('uploadArea').addEventListener('dragover', function(e) {

            e.preventDefault();

            this.style.borderColor = '#667eea';

            this.style.background = '#f8f9fa';

        });

        

        document.getElementById('uploadArea').addEventListener('dragleave', function(e) {

            e.preventDefault();

            this.style.borderColor = '#dee2e6';

            this.style.background = 'white';

        });

        

        document.getElementById('uploadArea').addEventListener('drop', function(e) {

            e.preventDefault();

            this.style.borderColor = '#dee2e6';

            this.style.background = 'white';

            

            const files = e.dataTransfer.files;

            handleFiles(files);

        });

        

        document.getElementById('fileInput').addEventListener('change', function(e) {

            handleFiles(this.files);

        });

        

        function handleFiles(files) {

            uploadedFiles = Array.from(files);

            const fileList = document.getElementById('fileList');

            fileList.innerHTML = '';

            

            uploadedFiles.forEach(file => {

                const fileItem = document.createElement('div');

                fileItem.className = 'alert alert-info';

                fileItem.innerHTML = `

                    <i class="fas fa-file me-2"></i>${file.name} (${(file.size / 1024).toFixed(2)} KB)

                `;

                fileList.appendChild(fileItem);

            });

            

            document.getElementById('validateBtn').disabled = false;

        }

        

        function goToManualEntry() {

            window.location.href = 'imports/manual_entry.php';

        }

        

        function uploadAndValidate() {

            if (uploadedFiles.length === 0) {

                alert('Please upload files first');

                return;

            }

            

            const formData = new FormData();

            formData.append('source', selectedSource);

            uploadedFiles.forEach((file, index) => {

                formData.append(`files[${index}]`, file);

            });

            

            // Show loading

            document.getElementById('validateBtn').innerHTML = 'Validating... <i class="fas fa-spinner fa-spin ms-2"></i>';

            document.getElementById('validateBtn').disabled = true;

            

            $.ajax({

                url: 'imports/csv_import.php?action=validate',

                type: 'POST',

                data: formData,

                processData: false,

                contentType: false,

                success: function(response) {

                    validationResults = response;

                    displayValidationResults(response);

                    nextStep(2);

                },

                error: function(xhr, status, error) {

                    alert('Validation failed: ' + error);

                    console.error(xhr.responseText);

                },

                complete: function() {

                    document.getElementById('validateBtn').innerHTML = 'Validate Data <i class="fas fa-check ms-2"></i>';

                    document.getElementById('validateBtn').disabled = false;

                }

            });

        }

        

        function displayValidationResults(results) {

            // Update counts

            document.getElementById('total-records').textContent = results.total || 0;

            document.getElementById('valid-records').textContent = results.valid || 0;

            document.getElementById('warning-records').textContent = results.warnings || 0;

            document.getElementById('error-records').textContent = results.errors || 0;

            

            // Display issues

            const issuesContainer = document.getElementById('issues-container');

            issuesContainer.innerHTML = '';

            

            if (results.issues && results.issues.length > 0) {

                results.issues.forEach(issue => {

                    const issueDiv = document.createElement('div');

                    issueDiv.className = `validation-issue issue-${issue.type}`;

                    issueDiv.innerHTML = `

                        <strong>Row ${issue.row}:</strong> ${issue.message}

                        <small class="d-block text-muted">${issue.field}</small>

                    `;

                    issuesContainer.appendChild(issueDiv);

                });

            } else {

                issuesContainer.innerHTML = '<p class="text-success"><i class="fas fa-check-circle me-2"></i>No issues found!</p>';

            }

            

            // Display suggestions

            const suggestionsContainer = document.getElementById('suggestions-container');

            suggestionsContainer.innerHTML = '';

            

            if (results.suggestions && results.suggestions.length > 0) {

                results.suggestions.forEach(suggestion => {

                    const suggestionDiv = document.createElement('div');

                    suggestionDiv.className = 'alert alert-info';

                    suggestionDiv.innerHTML = `

                        <strong>${suggestion.field}:</strong> ${suggestion.message}

                        <button class="btn btn-sm btn-success float-end" onclick="applySuggestion(${suggestion.row}, '${suggestion.field}', '${suggestion.value}')">

                            Apply

                        </button>

                    `;

                    suggestionsContainer.appendChild(suggestionDiv);

                });

            } else {

                suggestionsContainer.innerHTML = '<p class="text-muted">No suggestions available</p>';

            }

            

            // Display duplicate warnings

            if (results.duplicate_count > 0) {

                const duplicateHtml = `

                    <div class="alert alert-warning mt-3">

                        <h6><i class="fas fa-copy me-2"></i>Duplicates Found: ${results.duplicate_count}</h6>

                        <p class="mb-0">Please review and merge duplicate records before importing.</p>

                    </div>

                `;

                document.getElementById('duplicate-warning').innerHTML = duplicateHtml;

            }

            

            // Display existing records warnings

            if (results.existing_count > 0) {

                const existingHtml = `

                    <div class="alert alert-info mt-3">

                        <h6><i class="fas fa-database me-2"></i>Records Already in Database: ${results.existing_count}</h6>

                        <p class="mb-0">These records will be skipped during import.</p>

                    </div>

                `;

                document.getElementById('existing-warning').innerHTML = existingHtml;

            }

        }

        

        function applySuggestion(row, field, value) {

            // Apply suggestion to the data

            console.log('Applying suggestion:', row, field, value);

        }

        

        function startImport() {

            document.getElementById('step4-content').style.display = 'none';

            document.getElementById('step5-content').style.display = 'block';

            

            const formData = new FormData();

            formData.append('source', selectedSource);

            uploadedFiles.forEach((file, index) => {

                formData.append(`files[${index}]`, file);

            });

            

            // Start import process

            $.ajax({

                url: 'imports/csv_import.php?action=import',

                type: 'POST',

                data: formData,

                processData: false,

                contentType: false,

                xhr: function() {

                    const xhr = new XMLHttpRequest();

                    xhr.upload.addEventListener('progress', function(e) {

                        if (e.lengthComputable) {

                            const percentComplete = (e.loaded / e.total) * 100;

                            document.getElementById('import-progress').style.width = percentComplete + '%';

                            document.getElementById('import-progress').textContent = Math.round(percentComplete) + '%';

                        }

                    });

                    return xhr;

                },

                success: function(response) {

                    document.getElementById('import-progress').style.width = '100%';

                    document.getElementById('import-progress').textContent = '100%';

                    

                    const log = document.getElementById('import-log');

                    log.innerHTML += `<p class="text-success">✓ Import completed successfully</p>`;

                    

                    if (response.details) {

                        response.details.forEach(detail => {

                            log.innerHTML += `<p>${detail}</p>`;

                        });

                    }

                    

                    document.getElementById('import-complete').style.display = 'block';

                    document.getElementById('import-summary').textContent = 

                        `Successfully imported ${response.imported || 0} records.`;

                },

                error: function(xhr, status, error) {

                    document.getElementById('import-log').innerHTML += `

                        <p class="text-danger">✗ Import failed: ${error}</p>

                    `;

                }

            });

        }

        

        function finishMigration() {

            window.location.href = '../dashboard.php?migration=complete';

        }

    </script>

</body>

</html>