<?php include 'layouts/session.php'; ?>
<?php include 'layouts/main.php'; ?>
<?php include 'layouts/dbconn.php'; ?>

<?php
// Initialize variables
$successMsg = '';
$errorMsg = '';
$step = isset($_GET['step']) ? (int)$_GET['step'] : 1;
$sourceType = isset($_GET['source_type']) ? $_GET['source_type'] : '';
$sourceId = isset($_GET['source_id']) ? (int)$_GET['source_id'] : 0;

// Check if user is admin (role_id = 1), if not redirect to dashboard
if ($_SESSION['role_id'] != 1) {
    header("Location: dashboard.php");
    exit;
}

// Step 1: Select data source type
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['select_source_type'])) {
    $selectedSourceType = $_POST['source_type'];
    
    // Redirect to next step with source type
    header("Location: data_migration.php?step=2&source_type=" . urlencode($selectedSourceType));
    exit;
}

// Step 2: Select specific data source or upload file
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['select_source'])) {
    if ($sourceType === 'database') {
        $sourceId = (int)$_POST['source_id'];
        
        // Validate source ID
        if ($sourceId <= 0) {
            $errorMsg = "Please select a valid data source";
        } else {
            // Redirect to next step with source ID
            header("Location: data_migration.php?step=3&source_type=database&source_id=$sourceId");
            exit;
        }
    } elseif ($sourceType === 'csv' || $sourceType === 'excel') {
        // Handle file upload
        if (!isset($_FILES['source_file']) || $_FILES['source_file']['error'] !== UPLOAD_ERR_OK) {
            $errorMsg = "Please upload a valid file";
        } else {
            $uploadDir = 'uploads/import/';
            
            // Create directory if it doesn't exist
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            $fileName = uniqid() . '_' . basename($_FILES['source_file']['name']);
            $uploadFile = $uploadDir . $fileName;
            
            // Move uploaded file
            if (move_uploaded_file($_FILES['source_file']['tmp_name'], $uploadFile)) {
                // Store file info in session
                $_SESSION['import_file'] = $uploadFile;
                $_SESSION['import_file_name'] = $_FILES['source_file']['name'];
                
                // Redirect to next step
                header("Location: data_migration.php?step=3&source_type=$sourceType");
                exit;
            } else {
                $errorMsg = "Failed to upload file";
            }
        }
    }
}

// Step 3: Map fields
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['map_fields'])) {
    // Get field mappings
    $fieldMappings = [];
    foreach ($_POST as $key => $value) {
        if (strpos($key, 'field_mapping_') === 0) {
            $sourceField = substr($key, strlen('field_mapping_'));
            $targetField = $value;
            if (!empty($targetField)) {
                $fieldMappings[$sourceField] = $targetField;
            }
        }
    }
    
    // Store field mappings in session
    $_SESSION['field_mappings'] = $fieldMappings;
    
    // Redirect to confirmation step
    header("Location: data_migration.php?step=4&source_type=$sourceType" . ($sourceType === 'database' ? "&source_id=$sourceId" : ""));
    exit;
}

// Step 4: Preview and confirm migration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_migration'])) {
    // Get field mappings from session
    $fieldMappings = $_SESSION['field_mappings'] ?? [];
    
    if (empty($fieldMappings)) {
        $errorMsg = "No field mappings found. Please go back and map fields.";
    } else {
        // Start migration process
        try {
            $conn->begin_transaction();
            
            // Get target table from the first mapping
            $firstMapping = reset($fieldMappings);
            $targetField = key($fieldMappings);
            $targetTable = '';
            
            // Extract table name from target field (format: table.field)
            if (strpos($firstMapping, '.') !== false) {
                list($targetTable, ) = explode('.', $firstMapping);
            }
            
            if (empty($targetTable)) {
                throw new Exception("Could not determine target table");
            }
            
            // Process based on source type
            $importedCount = 0;
            
            if ($sourceType === 'database' && $sourceId > 0) {
                // Get source connection details
                $sourceQuery = "SELECT * FROM data_sources WHERE id = $sourceId";
                $sourceResult = $conn->query($sourceQuery);
                
                if ($sourceResult && $sourceResult->num_rows > 0) {
                    $source = $sourceResult->fetch_assoc();
                    
                    // Connect to source database
                    $sourceConn = new mysqli(
                        $source['db_host'],
                        $source['db_username'],
                        $source['db_password'],
                        $source['db_name']
                    );
                    
                    if ($sourceConn->connect_error) {
                        throw new Exception("Connection to source database failed: " . $sourceConn->connect_error);
                    }
                    
                    // Extract source table name from the first mapping's key
                    $sourceTable = '';
                    $sourceFields = [];
                    
                    foreach ($fieldMappings as $sourceColumn => $targetColumn) {
                        if (strpos($sourceColumn, '.') !== false) {
                            list($srcTable, $srcField) = explode('.', $sourceColumn);
                            if (empty($sourceTable)) {
                                $sourceTable = $srcTable;
                            }
                            $sourceFields[$srcField] = $targetColumn;
                        }
                    }
                    
                    if (empty($sourceTable)) {
                        throw new Exception("Could not determine source table");
                    }
                    
                    // Build source query
                    $sourceFieldsList = implode(', ', array_keys($sourceFields));
                    $sourceDataQuery = "SELECT $sourceFieldsList FROM $sourceTable";
                    $sourceDataResult = $sourceConn->query($sourceDataQuery);
                    
                    if (!$sourceDataResult) {
                        throw new Exception("Error querying source data: " . $sourceConn->error);
                    }
                    
                    // Process each row from source
                    while ($row = $sourceDataResult->fetch_assoc()) {
                        // Prepare data for insertion
                        $insertFields = [];
                        $insertValues = [];
                        $insertParams = [];
                        $paramTypes = '';
                        
                        foreach ($sourceFields as $srcField => $targetColumn) {
                            list(, $targetField) = explode('.', $targetColumn);
                            $insertFields[] = $targetField;
                            $insertValues[] = '?';
                            $insertParams[] = $row[$srcField];
                            $paramTypes .= $this->getParamType($row[$srcField]);
                        }
                        
                        // Build and execute insert query
                        $targetFieldsStr = implode(', ', $insertFields);
                        $targetValuesStr = implode(', ', $insertValues);
                        $insertQuery = "INSERT INTO $targetTable ($targetFieldsStr) VALUES ($targetValuesStr)";
                        
                        $stmt = $conn->prepare($insertQuery);
                        if (!$stmt) {
                            throw new Exception("Error preparing insert statement: " . $conn->error);
                        }
                        
                        $stmt->bind_param($paramTypes, ...$insertParams);
                        $stmt->execute();
                        $stmt->close();
                        
                        $importedCount++;
                    }
                    
                    $sourceConn->close();
                } else {
                    throw new Exception("Source database not found");
                }
            } elseif ($sourceType === 'csv' && isset($_SESSION['import_file'])) {
                $file = $_SESSION['import_file'];
                
                // Parse CSV
                if (($handle = fopen($file, "r")) !== FALSE) {
                    // Read header row
                    $header = fgetcsv($handle, 1000, ",");
                    
                    // Prepare target fields
                    $targetFields = [];
                    $headerMap = [];
                    
                    foreach ($fieldMappings as $sourceColumn => $targetColumn) {
                        if (strpos($targetColumn, '.') !== false) {
                            list(, $targetField) = explode('.', $targetColumn);
                            
                            if (($index = array_search($sourceColumn, $header)) !== false) {
                                $targetFields[] = $targetField;
                                $headerMap[$index] = $targetField;
                            }
                        }
                    }
                    
                    if (empty($targetFields)) {
                        throw new Exception("No valid field mappings found");
                    }
                    
                    // Process data rows
                    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                        $insertFields = [];
                        $insertValues = [];
                        $insertParams = [];
                        $paramTypes = '';
                        
                        foreach ($headerMap as $index => $field) {
                            if (isset($data[$index])) {
                                $insertFields[] = $field;
                                $insertValues[] = '?';
                                $insertParams[] = $data[$index];
                                $paramTypes .= $this->getParamType($data[$index]);
                            }
                        }
                        
                        // Build and execute insert query
                        $targetFieldsStr = implode(', ', $insertFields);
                        $targetValuesStr = implode(', ', $insertValues);
                        $insertQuery = "INSERT INTO $targetTable ($targetFieldsStr) VALUES ($targetValuesStr)";
                        
                        $stmt = $conn->prepare($insertQuery);
                        if (!$stmt) {
                            throw new Exception("Error preparing insert statement: " . $conn->error);
                        }
                        
                        $stmt->bind_param($paramTypes, ...$insertParams);
                        $stmt->execute();
                        $stmt->close();
                        
                        $importedCount++;
                    }
                    
                    fclose($handle);
                } else {
                    throw new Exception("Could not open CSV file");
                }
            } elseif ($sourceType === 'excel' && isset($_SESSION['import_file'])) {
                $file = $_SESSION['import_file'];
                
                // Check if PhpSpreadsheet is available
                if (!class_exists('PhpOffice\PhpSpreadsheet\IOFactory')) {
                    // Use a simple excel parser library
                    require_once 'libs/SimpleXLSX.php';
                    
                    if ($xlsx = SimpleXLSX::parse($file)) {
                        // Get headers from first row
                        $rows = $xlsx->rows();
                        $header = $rows[0];
                        
                        // Prepare target fields
                        $targetFields = [];
                        $headerMap = [];
                        
                        foreach ($fieldMappings as $sourceColumn => $targetColumn) {
                            if (strpos($targetColumn, '.') !== false) {
                                list(, $targetField) = explode('.', $targetColumn);
                                
                                if (($index = array_search($sourceColumn, $header)) !== false) {
                                    $targetFields[] = $targetField;
                                    $headerMap[$index] = $targetField;
                                }
                            }
                        }
                        
                        if (empty($targetFields)) {
                            throw new Exception("No valid field mappings found");
                        }
                        
                        // Skip header row and process data rows
                        for ($i = 1; $i < count($rows); $i++) {
                            $data = $rows[$i];
                            
                            $insertFields = [];
                            $insertValues = [];
                            $insertParams = [];
                            $paramTypes = '';
                            
                            foreach ($headerMap as $index => $field) {
                                if (isset($data[$index])) {
                                    $insertFields[] = $field;
                                    $insertValues[] = '?';
                                    $insertParams[] = $data[$index];
                                    $paramTypes .= $this->getParamType($data[$index]);
                                }
                            }
                            
                            // Build and execute insert query
                            $targetFieldsStr = implode(', ', $insertFields);
                            $targetValuesStr = implode(', ', $insertValues);
                            $insertQuery = "INSERT INTO $targetTable ($targetFieldsStr) VALUES ($targetValuesStr)";
                            
                            $stmt = $conn->prepare($insertQuery);
                            if (!$stmt) {
                                throw new Exception("Error preparing insert statement: " . $conn->error);
                            }
                            
                            $stmt->bind_param($paramTypes, ...$insertParams);
                            $stmt->execute();
                            $stmt->close();
                            
                            $importedCount++;
                        }
                    } else {
                        throw new Exception("Error parsing Excel file: " . SimpleXLSX::parseError());
                    }
                } else {
                    // Use PhpSpreadsheet
                    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
                    $worksheet = $spreadsheet->getActiveSheet();
                    $rows = $worksheet->toArray();
                    
                    // Get headers from first row
                    $header = $rows[0];
                    
                    // Prepare target fields
                    $targetFields = [];
                    $headerMap = [];
                    
                    foreach ($fieldMappings as $sourceColumn => $targetColumn) {
                        if (strpos($targetColumn, '.') !== false) {
                            list(, $targetField) = explode('.', $targetColumn);
                            
                            if (($index = array_search($sourceColumn, $header)) !== false) {
                                $targetFields[] = $targetField;
                                $headerMap[$index] = $targetField;
                            }
                        }
                    }
                    
                    if (empty($targetFields)) {
                        throw new Exception("No valid field mappings found");
                    }
                    
                    // Skip header row and process data rows
                    for ($i = 1; $i < count($rows); $i++) {
                        $data = $rows[$i];
                        
                        $insertFields = [];
                        $insertValues = [];
                        $insertParams = [];
                        $paramTypes = '';
                        
                        foreach ($headerMap as $index => $field) {
                            if (isset($data[$index])) {
                                $insertFields[] = $field;
                                $insertValues[] = '?';
                                $insertParams[] = $data[$index];
                                $paramTypes .= $this->getParamType($data[$index]);
                            }
                        }
                        
                        // Build and execute insert query
                        $targetFieldsStr = implode(', ', $insertFields);
                        $targetValuesStr = implode(', ', $insertValues);
                        $insertQuery = "INSERT INTO $targetTable ($targetFieldsStr) VALUES ($targetValuesStr)";
                        
                        $stmt = $conn->prepare($insertQuery);
                        if (!$stmt) {
                            throw new Exception("Error preparing insert statement: " . $conn->error);
                        }
                        
                        $stmt->bind_param($paramTypes, ...$insertParams);
                        $stmt->execute();
                        $stmt->close();
                        
                        $importedCount++;
                    }
                }
            } else {
                throw new Exception("Invalid source type or missing import file");
            }
            
            // Log the import
            $logQuery = "INSERT INTO activity_logs (user_id, activity_type, description, ip_address, related_to) 
                        VALUES (?, 'import', ?, ?, 'data_migration')";
            $stmt = $conn->prepare($logQuery);
            
            $description = "Imported $importedCount records from " . ucfirst($sourceType) . " source";
            if ($sourceType === 'database') {
                $description .= " (ID: $sourceId)";
            } elseif (isset($_SESSION['import_file_name'])) {
                $description .= " (File: " . $_SESSION['import_file_name'] . ")";
            }
            
            $stmt->bind_param('iss', $_SESSION['user_id'], $description, $_SERVER['REMOTE_ADDR']);
            $stmt->execute();
            
            // Commit transaction
            $conn->commit();
            
            // Clear session data
            unset($_SESSION['field_mappings']);
            unset($_SESSION['import_file']);
            unset($_SESSION['import_file_name']);
            
            $successMsg = "$importedCount records successfully imported to $targetTable table.";
            
            // Redirect to success page
            header("Location: data_migration.php?step=5&success=1&count=$importedCount&table=" . urlencode($targetTable));
            exit;
            
        } catch (Exception $e) {
            // Rollback transaction
            $conn->rollback();
            $errorMsg = "Error during migration: " . $e->getMessage();
        }
    }
}

// Helper function to get parameter type for prepared statements
function getParamType($value) {
    if (is_numeric($value)) {
        if (is_float($value)) {
            return 'd'; // double
        } else {
            return 'i'; // integer
        }
    } else {
        return 's'; // string
    }
}

// Get available database sources
$dataSources = [];

// Check if data_sources table exists, create if not
$checkTableQuery = "SHOW TABLES LIKE 'data_sources'";
$tableExists = $conn->query($checkTableQuery)->num_rows > 0;

if (!$tableExists) {
    // Create data_sources table
    $createTableQuery = "CREATE TABLE `data_sources` (
                        `id` int NOT NULL AUTO_INCREMENT,
                        `name` varchar(100) NOT NULL,
                        `description` text,
                        `db_type` varchar(20) NOT NULL DEFAULT 'mysql',
                        `db_host` varchar(255) NOT NULL,
                        `db_port` int DEFAULT NULL,
                        `db_name` varchar(100) NOT NULL,
                        `db_username` varchar(100) NOT NULL,
                        `db_password` varchar(255) NOT NULL,
                        `last_used` datetime DEFAULT NULL,
                        `created_by` int NOT NULL,
                        `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
                        `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                        PRIMARY KEY (`id`),
                        KEY `created_by` (`created_by`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
    
    $conn->query($createTableQuery);
}

$dataSourcesQuery = "SELECT * FROM data_sources ORDER BY name";
$dataSourcesResult = $conn->query($dataSourcesQuery);

if ($dataSourcesResult && $dataSourcesResult->num_rows > 0) {
    while ($row = $dataSourcesResult->fetch_assoc()) {
        $dataSources[] = $row;
    }
}


// Function to get target database tables and their structure
function getTargetTables($conn) {
    $tables = [];
    $excludeTables = ['settings', 'activity_logs', 'login_history', 'system_logs', 'data_sources'];
    
    $tablesQuery = "SHOW TABLES";
    $tablesResult = $conn->query($tablesQuery);
    
    if ($tablesResult) {
        while ($row = $tablesResult->fetch_row()) {
            $tableName = $row[0];
            
            // Skip excluded tables
            if (in_array($tableName, $excludeTables)) {
                continue;
            }
            
            // Get table columns
            $columnsQuery = "SHOW COLUMNS FROM $tableName";
            $columnsResult = $conn->query($columnsQuery);
            
            $columns = [];
            if ($columnsResult) {
                while ($column = $columnsResult->fetch_assoc()) {
                    $columns[] = [
                        'field' => $column['Field'],
                        'type' => $column['Type'],
                        'null' => $column['Null'],
                        'key' => $column['Key'],
                        'default' => $column['Default'],
                        'extra' => $column['Extra']
                    ];
                }
            }
            
            $tables[$tableName] = $columns;
        }
    }
    
    return $tables;
}

// Get source fields to map
function getSourceFields($conn, $sourceType, $sourceId) {
    $fields = [];
    
    if ($sourceType === 'database' && $sourceId > 0) {
        // Get source connection details
        $sourceQuery = "SELECT * FROM data_sources WHERE id = $sourceId";
        $sourceResult = $conn->query($sourceQuery);
        
        if ($sourceResult && $sourceResult->num_rows > 0) {
            $source = $sourceResult->fetch_assoc();
            
            try {
                // Connect to source database
                $sourceConn = new mysqli(
                    $source['db_host'],
                    $source['db_username'],
                    $source['db_password'],
                    $source['db_name']
                );
                
                if ($sourceConn->connect_error) {
                    throw new Exception("Connection to source database failed: " . $sourceConn->connect_error);
                }
                
                // Get tables
                $tablesQuery = "SHOW TABLES";
                $tablesResult = $sourceConn->query($tablesQuery);
                
                if ($tablesResult) {
                    while ($row = $tablesResult->fetch_row()) {
                        $tableName = $row[0];
                        
                        // Get table columns
                        $columnsQuery = "SHOW COLUMNS FROM $tableName";
                        $columnsResult = $sourceConn->query($columnsQuery);
                        
                        $tableFields = [];
                        if ($columnsResult) {
                            while ($column = $columnsResult->fetch_assoc()) {
                                $tableFields[] = [
                                    'field' => $column['Field'],
                                    'type' => $column['Type'],
                                    'null' => $column['Null'],
                                    'key' => $column['Key'],
                                    'default' => $column['Default'],
                                    'extra' => $column['Extra']
                                ];
                            }
                        }
                        
                        $fields[$tableName] = $tableFields;
                    }
                }
                
                $sourceConn->close();
            } catch (Exception $e) {
                // Handle connection error
                $errorMsg = $e->getMessage();
            }
        }
    } elseif ($sourceType === 'csv' && isset($_SESSION['import_file'])) {
        $file = $_SESSION['import_file'];
        
        // Parse CSV header
        if (($handle = fopen($file, "r")) !== FALSE) {
            // Read header row
            $header = fgetcsv($handle, 1000, ",");
            
            // Read a sample row to determine types
            $sampleRow = fgetcsv($handle, 1000, ",");
            
            $fields['csv_file'] = [];
            
            for ($i = 0; $i < count($header); $i++) {
                $type = 'string';
                if (isset($sampleRow[$i])) {
                    if (is_numeric($sampleRow[$i])) {
                        if (strpos($sampleRow[$i], '.') !== false) {
                            $type = 'float';
                        } else {
                            $type = 'int';
                        }
                    } elseif (strtotime($sampleRow[$i]) !== false) {
                        $type = 'date';
                    }
                }
                
                $fields['csv_file'][] = [
                    'field' => $header[$i],
                    'type' => $type,
                    'sample' => $sampleRow[$i] ?? null
                ];
            }
            
            fclose($handle);
        }
    } elseif ($sourceType === 'excel' && isset($_SESSION['import_file'])) {
        $file = $_SESSION['import_file'];
        
        // Check if PhpSpreadsheet is available
        if (!class_exists('PhpOffice\PhpSpreadsheet\IOFactory')) {
            // Use a simple excel parser library
            require_once 'libs/SimpleXLSX.php';
            
            if ($xlsx = SimpleXLSX::parse($file)) {
                // Get headers from first row
                $rows = $xlsx->rows();
                $header = $rows[0];
                $sampleRow = isset($rows[1]) ? $rows[1] : [];
                
                $fields['excel_file'] = [];
                
                for ($i = 0; $i < count($header); $i++) {
                    $type = 'string';
                    if (isset($sampleRow[$i])) {
                        if (is_numeric($sampleRow[$i])) {
                            if (strpos($sampleRow[$i], '.') !== false) {
                                $type = 'float';
                            } else {
                                $type = 'int';
                            }
                        } elseif (strtotime($sampleRow[$i]) !== false) {
                            $type = 'date';
                        }
                    }
                    
                    $fields['excel_file'][] = [
                        'field' => $header[$i],
                        'type' => $type,
                        'sample' => $sampleRow[$i] ?? null
                    ];
                }
            }
        } else {
            // Use PhpSpreadsheet
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
            $worksheet = $spreadsheet->getActiveSheet();
            $rows = $worksheet->toArray();
            
            // Get headers from first row
            $header = $rows[0];
            $sampleRow = isset($rows[1]) ? $rows[1] : [];
            
            $fields['excel_file'] = [];
            
            for ($i = 0; $i < count($header); $i++) {
                $type = 'string';
                if (isset($sampleRow[$i])) {
                    if (is_numeric($sampleRow[$i])) {
                        if (strpos($sampleRow[$i], '.') !== false) {
                            $type = 'float';
                        } else {
                            $type = 'int';
                        }
                    } elseif (strtotime($sampleRow[$i]) !== false) {
                        $type = 'date';
                    }
                }
                
                $fields['excel_file'][] = [
                    'field' => $header[$i],
                    'type' => $type,
                    'sample' => $sampleRow[$i] ?? null
                ];
            }
        }
    }
    
    return $fields;
}

// Get target tables structure
$targetTables = getTargetTables($conn);

// Get source fields based on current step
$sourceFields = [];
if ($step === 3) {
    $sourceFields = getSourceFields($conn, $sourceType, $sourceId);
}

// Function to get sample data for preview
function getSampleData($conn, $sourceType, $sourceId, $fieldMappings, $limit = 5) {
    $sampleData = [];
    
    if ($sourceType === 'database' && $sourceId > 0) {
        // Get source connection details
        $sourceQuery = "SELECT * FROM data_sources WHERE id = $sourceId";
        $sourceResult = $conn->query($sourceQuery);
        
        if ($sourceResult && $sourceResult->num_rows > 0) {
            $source = $sourceResult->fetch_assoc();
            
            try {
                // Connect to source database
                $sourceConn = new mysqli(
                    $source['db_host'],
                    $source['db_username'],
                    $source['db_password'],
                    $source['db_name']
                );
                
                if ($sourceConn->connect_error) {
                    throw new Exception("Connection to source database failed: " . $sourceConn->connect_error);
                }
                
                // Extract source table name from the first mapping's key
                $sourceTable = '';
                $sourceFields = [];
                
                foreach ($fieldMappings as $sourceColumn => $targetColumn) {
                    if (strpos($sourceColumn, '.') !== false) {
                        list($srcTable, $srcField) = explode('.', $sourceColumn);
                        if (empty($sourceTable)) {
                            $sourceTable = $srcTable;
                        }
                        $sourceFields[$srcField] = $targetColumn;
                    }
                }
                
                if (empty($sourceTable)) {
                    throw new Exception("Could not determine source table");
                }
                
                // Build source query
                $sourceFieldsList = implode(', ', array_keys($sourceFields));
                $sourceDataQuery = "SELECT $sourceFieldsList FROM $sourceTable LIMIT $limit";
                $sourceDataResult = $sourceConn->query($sourceDataQuery);
                
                if (!$sourceDataResult) {
                    throw new Exception("Error querying source data: " . $sourceConn->error);
                }
                
                // Fetch sample data
                while ($row = $sourceDataResult->fetch_assoc()) {
                    $mappedRow = [];
                    
                    foreach ($sourceFields as $srcField => $targetColumn) {
                        $mappedRow[$targetColumn] = $row[$srcField];
                    }
                    
                    $sampleData[] = $mappedRow;
                }
                
                $sourceConn->close();
            } catch (Exception $e) {
                // Handle connection error
                $errorMsg = $e->getMessage();
            }
        }
    } elseif ($sourceType === 'csv' && isset($_SESSION['import_file'])) {
        $file = $_SESSION['import_file'];
        
        // Parse CSV
        if (($handle = fopen($file, "r")) !== FALSE) {
            // Read header row
            $header = fgetcsv($handle, 1000, ",");
            
            // Prepare field mapping indices
            $fieldIndices = [];
            foreach ($fieldMappings as $sourceColumn => $targetColumn) {
                $index = array_search($sourceColumn, $header);
                if ($index !== false) {
                    $fieldIndices[$index] = $targetColumn;
                }
            }
            
            // Read data rows (up to limit)
            $count = 0;
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE && $count < $limit) {
                $mappedRow = [];
                
                foreach ($fieldIndices as $index => $targetField) {
                    if (isset($data[$index])) {
                        $mappedRow[$targetField] = $data[$index];
                    }
                }
                
                $sampleData[] = $mappedRow;
                $count++;
            }
            
            fclose($handle);
        }
    } elseif ($sourceType === 'excel' && isset($_SESSION['import_file'])) {
        $file = $_SESSION['import_file'];
        
        // Check if PhpSpreadsheet is available
        if (!class_exists('PhpOffice\PhpSpreadsheet\IOFactory')) {
            // Use a simple excel parser library
            require_once 'libs/SimpleXLSX.php';
            
            if ($xlsx = SimpleXLSX::parse($file)) {
                // Get headers from first row
                $rows = $xlsx->rows();
                $header = $rows[0];
                
                // Prepare field mapping indices
                $fieldIndices = [];
                foreach ($fieldMappings as $sourceColumn => $targetColumn) {
                    $index = array_search($sourceColumn, $header);
                    if ($index !== false) {
                        $fieldIndices[$index] = $targetColumn;
                    }
                }
                
                // Read up to limit rows for preview
                $count = 0;
                for ($i = 1; $i < count($rows) && $count < $limit; $i++) {
                    $data = $rows[$i];
                    $mappedRow = [];
                    
                    foreach ($fieldIndices as $index => $targetField) {
                        if (isset($data[$index])) {
                            $mappedRow[$targetField] = $data[$index];
                        }
                    }
                    
                    $sampleData[] = $mappedRow;
                    $count++;
                }
            }
        } else {
            // Use PhpSpreadsheet
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
            $worksheet = $spreadsheet->getActiveSheet();
            $rows = $worksheet->toArray();
            
            // Get headers from first row
            $header = $rows[0];
            
            // Prepare field mapping indices
            $fieldIndices = [];
            foreach ($fieldMappings as $sourceColumn => $targetColumn) {
                $index = array_search($sourceColumn, $header);
                if ($index !== false) {
                    $fieldIndices[$index] = $targetColumn;
                }
            }
            
            // Read up to limit rows for preview
            $count = 0;
            for ($i = 1; $i < count($rows) && $count < $limit; $i++) {
                $data = $rows[$i];
                $mappedRow = [];
                
                foreach ($fieldIndices as $index => $targetField) {
                    if (isset($data[$index])) {
                        $mappedRow[$targetField] = $data[$index];
                    }
                }
                
                $sampleData[] = $mappedRow;
                $count++;
            }
        }
    }
    
    return $sampleData;
}

// Get sample data for preview if on step 4
$sampleData = [];
if ($step === 4 && isset($_SESSION['field_mappings'])) {
    $sampleData = getSampleData($conn, $sourceType, $sourceId, $_SESSION['field_mappings']);
}
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Data Migration')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    
    <!-- Sweet Alert css -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.5/dist/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System', 'title' => 'Data Migration')); ?>
                    
                    <!-- Alert Messages -->
                    <?php if (!empty($successMsg)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>Success!</strong> <?php echo $successMsg; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($errorMsg)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>Error!</strong> <?php echo $errorMsg; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Progress Steps -->
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="step-arrow-nav mb-4">
                                        <ul class="nav nav-pills custom-nav nav-justified" role="tablist">
                                            <li class="nav-item" role="presentation">
                                                <button class="nav-link <?php echo $step === 1 ? 'active' : ($step > 1 ? 'done' : ''); ?>" data-position="0">
                                                    <span class="step-title">Step 1</span>
                                                    <span class="step-title-desc">Select Source Type</span>
                                                </button>
                                            </li>
                                            <li class="nav-item" role="presentation">
                                                <button class="nav-link <?php echo $step === 2 ? 'active' : ($step > 2 ? 'done' : ''); ?>" data-position="1">
                                                    <span class="step-title">Step 2</span>
                                                    <span class="step-title-desc">Select Source</span>
                                                </button>
                                            </li>
                                            <li class="nav-item" role="presentation">
                                                <button class="nav-link <?php echo $step === 3 ? 'active' : ($step > 3 ? 'done' : ''); ?>" data-position="2">
                                                    <span class="step-title">Step 3</span>
                                                    <span class="step-title-desc">Map Fields</span>
                                                </button>
                                            </li>
                                            <li class="nav-item" role="presentation">
                                                <button class="nav-link <?php echo $step === 4 ? 'active' : ($step > 4 ? 'done' : ''); ?>" data-position="3">
                                                    <span class="step-title">Step 4</span>
                                                    <span class="step-title-desc">Preview & Confirm</span>
                                                </button>
                                            </li>
                                            <li class="nav-item" role="presentation">
                                                <button class="nav-link <?php echo $step === 5 ? 'active' : ''; ?>" data-position="4">
                                                    <span class="step-title">Step 5</span>
                                                    <span class="step-title-desc">Complete</span>
                                                </button>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <?php if ($step === 1): ?>
                    <!-- Step 1: Select Source Type -->
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Select Data Source Type</h4>
                                </div>
                                <div class="card-body">
                                    <p class="card-text text-muted">Choose the type of data source you want to import from.</p>
                                    
                                    <form action="" method="POST" class="mt-4">
                                        <div class="row">
                                            <div class="col-lg-4 mb-3">
                                                <div class="card">
                                                    <div class="card-body">
                                                        <div class="form-check card-radio">
                                                            <input id="source_type_database" name="source_type" type="radio" value="database" class="form-check-input" checked>
                                                            <label class="form-check-label" for="source_type_database">
                                                                <div class="d-flex align-items-center">
                                                                    <div class="flex-shrink-0">
                                                                        <div class="avatar-sm">
                                                                            <div class="avatar-title bg-soft-primary text-primary rounded-circle fs-4">
                                                                                <i class="ri-database-2-line"></i>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="flex-grow-1 ms-3">
                                                                        <h5 class="mb-1">External Database</h5>
                                                                        <p class="mb-0 text-muted">Import from another database source</p>
                                                                    </div>
                                                                </div>
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-lg-4 mb-3">
                                                <div class="card">
                                                    <div class="card-body">
                                                        <div class="form-check card-radio">
                                                            <input id="source_type_csv" name="source_type" type="radio" value="csv" class="form-check-input">
                                                            <label class="form-check-label" for="source_type_csv">
                                                                <div class="d-flex align-items-center">
                                                                    <div class="flex-shrink-0">
                                                                        <div class="avatar-sm">
                                                                            <div class="avatar-title bg-soft-success text-success rounded-circle fs-4">
                                                                                <i class="ri-file-text-line"></i>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="flex-grow-1 ms-3">
                                                                        <h5 class="mb-1">CSV File</h5>
                                                                        <p class="mb-0 text-muted">Import from a CSV file</p>
                                                                    </div>
                                                                </div>
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-lg-4 mb-3">
                                                <div class="card">
                                                    <div class="card-body">
                                                        <div class="form-check card-radio">
                                                            <input id="source_type_excel" name="source_type" type="radio" value="excel" class="form-check-input">
                                                            <label class="form-check-label" for="source_type_excel">
                                                                <div class="d-flex align-items-center">
                                                                    <div class="flex-shrink-0">
                                                                        <div class="avatar-sm">
                                                                            <div class="avatar-title bg-soft-info text-info rounded-circle fs-4">
                                                                                <i class="ri-file-excel-line"></i>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="flex-grow-1 ms-3">
                                                                        <h5 class="mb-1">Excel File</h5>
                                                                        <p class="mb-0 text-muted">Import from an Excel file</p>
                                                                    </div>
                                                                </div>
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="d-flex align-items-start gap-3 mt-4">
                                            <button type="submit" name="select_source_type" class="btn btn-primary">Continue <i class="ri-arrow-right-line align-bottom ms-1"></i></button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <?php elseif ($step === 2): ?>
                    <!-- Step 2: Select Source -->
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0"><?php echo ucfirst($sourceType); ?> Source Selection</h4>
                                </div>
                                <div class="card-body">
                                    <?php if ($sourceType === 'database'): ?>
                                    
                                    <?php if (empty($dataSources)): ?>
                                    <div class="alert alert-info">
                                        <p class="mb-0">No database sources found. Please add a database connection first.</p>
                                    </div>
                                    <div class="text-center">
                                        <a href="data_source_add.php" class="btn btn-primary">Add Database Source</a>
                                        <a href="data_migration.php" class="btn btn-light ms-2">Go Back</a>
                                    </div>
                                    <?php else: ?>
                                    <p class="card-text text-muted mb-4">Select the database source you want to import data from.</p>
                                    
                                    <form action="" method="POST">
                                        <div class="table-responsive">
                                            <table class="table table-hover align-middle mb-0">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th style="width: 50px;"></th>
                                                        <th>Name</th>
                                                        <th>Host</th>
                                                        <th>Database</th>
                                                        <th>Last Used</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($dataSources as $source): ?>
                                                    <tr>
                                                        <td>
                                                            <div class="form-check">
                                                                <input class="form-check-input" type="radio" name="source_id" id="source_<?php echo $source['id']; ?>" value="<?php echo $source['id']; ?>" required>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <label for="source_<?php echo $source['id']; ?>" class="form-check-label fw-medium">
                                                                <?php echo htmlspecialchars($source['name']); ?>
                                                            </label>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($source['db_host']); ?></td>
                                                        <td><?php echo htmlspecialchars($source['db_name']); ?></td>
                                                        <td><?php echo $source['last_used'] ? date('M d, Y', strtotime($source['last_used'])) : 'Never'; ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                        
                                        <div class="d-flex align-items-start gap-3 mt-4">
                                            <a href="data_migration.php" class="btn btn-light"><i class="ri-arrow-left-line align-bottom me-1"></i> Back</a>
                                            <button type="submit" name="select_source" class="btn btn-primary">Continue <i class="ri-arrow-right-line align-bottom ms-1"></i></button>
                                            <a href="data_source_add.php" class="btn btn-success ms-auto"><i class="ri-add-line align-bottom me-1"></i> Add Database Source</a>
                                        </div>
                                    </form>
                                    <?php endif; ?>
                                    
                                    <?php elseif ($sourceType === 'csv' || $sourceType === 'excel'): ?>
                                    <p class="card-text text-muted mb-4">Upload a <?php echo strtoupper($sourceType); ?> file to import data from.</p>
                                    
                                    <form action="" method="POST" enctype="multipart/form-data">
                                        <div class="mb-4">
                                            <label for="source_file" class="form-label">Select <?php echo strtoupper($sourceType); ?> File</label>
                                            <input type="file" class="form-control" id="source_file" name="source_file" required 
                                                accept="<?php echo $sourceType === 'csv' ? '.csv' : '.xlsx,.xls'; ?>">
                                            <div class="form-text">
                                                <?php if ($sourceType === 'csv'): ?>
                                                Please upload a valid CSV file. The first row should contain column headers.
                                                <?php else: ?>
                                                Please upload a valid Excel file (XLSX or XLS). The first sheet will be used, and the first row should contain column headers.
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        
                                        <div class="d-flex align-items-start gap-3 mt-4">
                                            <a href="data_migration.php" class="btn btn-light"><i class="ri-arrow-left-line align-bottom me-1"></i> Back</a>
                                            <button type="submit" name="select_source" class="btn btn-primary">Continue <i class="ri-arrow-right-line align-bottom ms-1"></i></button>
                                        </div>
                                    </form>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <?php elseif ($step === 3): ?>
                    <!-- Step 3: Map Fields -->
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Map Fields</h4>
                                </div>
                                <div class="card-body">
                                    <p class="card-text text-muted mb-4">Map the fields from your source data to your target database tables.</p>
                                    
                                    <?php if (empty($sourceFields)): ?>
                                    <div class="alert alert-warning">
                                        <p class="mb-0">Could not retrieve source fields. Please go back and try again.</p>
                                    </div>
                                    <div class="d-flex align-items-start gap-3 mt-4">
                                        <a href="data_migration.php?step=2&source_type=<?php echo $sourceType; ?>" class="btn btn-light"><i class="ri-arrow-left-line align-bottom me-1"></i> Back</a>
                                    </div>
                                    <?php else: ?>
                                    <form action="" method="POST" id="fieldMappingForm">
                                        <div class="table-responsive">
                                            <table class="table table-bordered align-middle mb-0">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th>Source Field</th>
                                                        <th>Sample Data</th>
                                                        <th>Target Field</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($sourceFields as $table => $fields): ?>
                                                    <?php foreach ($fields as $field): ?>
                                                    <tr>
                                                        <td>
                                                            <strong><?php echo htmlspecialchars($table . '.' . $field['field']); ?></strong>
                                                            <div class="small text-muted"><?php echo htmlspecialchars($field['type']); ?></div>
                                                        </td>
                                                        <td>
                                                            <?php 
                                                            if (isset($field['sample'])) {
                                                                if (is_array($field['sample']) || is_object($field['sample'])) {
                                                                    echo htmlspecialchars(json_encode($field['sample']));
                                                                } else {
                                                                    echo htmlspecialchars($field['sample']);
                                                                }
                                                            } else {
                                                                echo '<span class="text-muted">N/A</span>';
                                                            }
                                                            ?>
                                                        </td>
                                                        <td>
                                                            <select class="form-select" name="field_mapping_<?php echo htmlspecialchars($table . '.' . $field['field']); ?>">
                                                                <option value="">-- Do not import --</option>
                                                                <?php foreach ($targetTables as $targetTable => $targetFields): ?>
                                                                <optgroup label="<?php echo htmlspecialchars($targetTable); ?>">
                                                                    <?php foreach ($targetFields as $targetField): ?>
                                                                    <option value="<?php echo htmlspecialchars($targetTable . '.' . $targetField['field']); ?>"
                                                                        <?php 
                                                                        // Auto-select if field names match
                                                                        if (strtolower($field['field']) === strtolower($targetField['field'])) {
                                                                            echo ' selected';
                                                                        }
                                                                        ?>>
                                                                        <?php echo htmlspecialchars($targetField['field']); ?>
                                                                        <small>(<?php echo htmlspecialchars($targetField['type']); ?>)</small>
                                                                    </option>
                                                                    <?php endforeach; ?>
                                                                </optgroup>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                        
                                        <div class="d-flex align-items-start gap-3 mt-4">
                                            <a href="data_migration.php?step=2&source_type=<?php echo $sourceType; ?>" class="btn btn-light"><i class="ri-arrow-left-line align-bottom me-1"></i> Back</a>
                                            <button type="submit" name="map_fields" class="btn btn-primary">Continue <i class="ri-arrow-right-line align-bottom ms-1"></i></button>
                                        </div>
                                    </form>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <?php elseif ($step === 4): ?>
                    <!-- Step 4: Preview and Confirm -->
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Preview and Confirm</h4>
                                </div>
                                <div class="card-body">
                                    <p class="card-text text-muted mb-4">Review the data mapping and preview the data that will be imported.</p>
                                    
                                    <?php if (empty($_SESSION['field_mappings'])): ?>
                                    <div class="alert alert-warning">
                                        <p class="mb-0">No field mappings found. Please go back and map fields.</p>
                                    </div>
                                    <div class="d-flex align-items-start gap-3 mt-4">
                                        <a href="data_migration.php?step=3&source_type=<?php echo $sourceType; ?><?php echo $sourceType === 'database' ? '&source_id=' . $sourceId : ''; ?>" class="btn btn-light"><i class="ri-arrow-left-line align-bottom me-1"></i> Back</a>
                                    </div>
                                    <?php else: ?>
                                    
                                    <!-- Display field mappings -->
                                    <h5 class="mb-3">Field Mappings</h5>
                                    <div class="table-responsive mb-4">
                                        <table class="table table-bordered align-middle mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Source Field</th>
                                                    <th>Target Field</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($_SESSION['field_mappings'] as $sourceField => $targetField): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($sourceField); ?></td>
                                                    <td><?php echo htmlspecialchars($targetField); ?></td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Preview data sample -->
                                    <h5 class="mb-3">Data Preview (sample of 5 records)</h5>
                                    <div class="table-responsive mb-4">
                                        <table class="table table-bordered align-middle mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>#</th>
                                                    <?php foreach ($_SESSION['field_mappings'] as $targetField): ?>
                                                    <th><?php echo htmlspecialchars($targetField); ?></th>
                                                    <?php endforeach; ?>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($sampleData)): ?>
                                                <tr>
                                                    <td colspan="<?php echo count($_SESSION['field_mappings']) + 1; ?>" class="text-center">No preview data available</td>
                                                </tr>
                                                <?php else: ?>
                                                <?php foreach ($sampleData as $index => $row): ?>
                                                <tr>
                                                    <td><?php echo $index + 1; ?></td>
                                                    <?php foreach ($_SESSION['field_mappings'] as $targetField): ?>
                                                    <td>
                                                    <?php 
                                                    if (isset($row[$targetField])) {
                                                        if (is_array($row[$targetField]) || is_object($row[$targetField])) {
                                                            echo htmlspecialchars(json_encode($row[$targetField]));
                                                        } else {
                                                            echo htmlspecialchars($row[$targetField]);
                                                        }
                                                    } else {
                                                        echo '<span class="text-muted">N/A</span>';
                                                    }
                                                    ?>
                                                    </td>
                                                    <?php endforeach; ?>
                                                </tr>
                                                <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Confirm migration -->
                                    <div class="alert alert-warning">
                                        <p><strong>Warning:</strong> This operation will import data into your database. Make sure you have a backup before proceeding.</p>
                                    </div>
                                    
                                    <form action="" method="POST" id="confirmMigrationForm">
                                        <div class="d-flex align-items-start gap-3 mt-4">
                                            <a href="data_migration.php?step=3&source_type=<?php echo $sourceType; ?><?php echo $sourceType === 'database' ? '&source_id=' . $sourceId : ''; ?>" class="btn btn-light"><i class="ri-arrow-left-line align-bottom me-1"></i> Back</a>
                                            <button type="submit" name="confirm_migration" class="btn btn-success">Start Migration <i class="ri-arrow-right-line align-bottom ms-1"></i></button>
                                        </div>
                                    </form>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <?php elseif ($step === 5): ?>
                    <!-- Step 5: Complete -->
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-body text-center">
                                    <?php if (isset($_GET['success']) && $_GET['success'] == 1): ?>
                                    <div class="avatar-lg mx-auto mt-2">
                                        <div class="avatar-title bg-light text-success display-3 rounded-circle">
                                            <i class="ri-checkbox-circle-fill"></i>
                                        </div>
                                    </div>
                                    <div class="mt-4 pt-2">
                                        <h4>Migration Completed Successfully!</h4>
                                        <p class="text-muted mx-4">
                                            <?php echo isset($_GET['count']) ? (int)$_GET['count'] : 0; ?> records have been successfully imported to
                                            <?php echo isset($_GET['table']) ? htmlspecialchars($_GET['table']) : 'the database'; ?>.
                                        </p>
                                        <div class="mt-4">
                                            <a href="data_migration.php" class="btn btn-primary">Start New Migration</a>
                                            <a href="dashboard.php" class="btn btn-light ms-2">Go to Dashboard</a>
                                        </div>
                                    </div>
                                    <?php else: ?>
                                    <div class="avatar-lg mx-auto mt-2">
                                        <div class="avatar-title bg-light text-danger display-3 rounded-circle">
                                            <i class="ri-close-circle-fill"></i>
                                        </div>
                                    </div>
                                    <div class="mt-4 pt-2">
                                        <h4>Migration Failed!</h4>
                                        <p class="text-muted mx-4">Something went wrong during the migration process. Please try again.</p>
                                        <div class="mt-4">
                                            <a href="data_migration.php" class="btn btn-primary">Try Again</a>
                                            <a href="dashboard.php" class="btn btn-light ms-2">Go to Dashboard</a>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                </div>
                <!-- End container-fluid -->
            </div>
            <!-- End page-content -->
            
            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- End main content -->
    </div>
    <!-- End layout wrapper -->
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function() {
            // Field mapping validation
            $("#fieldMappingForm").on("submit", function(e) {
                // Check if at least one field is mapped
                var mappedFields = 0;
                $("select[name^='field_mapping_']").each(function() {
                    if ($(this).val() !== "") {
                        mappedFields++;
                    }
                });
                
                if (mappedFields === 0) {
                    e.preventDefault();
                    Swal.fire({
                        title: 'Validation Error',
                        text: 'You must map at least one field to continue.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    return false;
                }
            });
            
            // Migration confirmation
            $("#confirmMigrationForm").on("submit", function(e) {
                e.preventDefault();
                
                Swal.fire({
                    title: 'Confirm Migration',
                    text: 'Are you sure you want to proceed with the data migration? This action cannot be undone.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, proceed',
                    cancelButtonText: 'No, cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        this.submit();
                    }
                });
            });
            
            // Initialize DataTables
            $('.table-responsive table').DataTable({
                paging: false,
                ordering: false,
                info: false,
                searching: false
            });
        });
    </script>
</body>
</html>