// The only thing we need from db_matches is the definition of the web service
require_once 'db_matches.php';
/**
 * Process
 */
$migration = new Migration();
$migration->set_web_service_connection_info($matches);
require $migration->web_service_connection_info['filename'];
$mig = new $migration->web_service_connection_info['class']();
error_log('Building in-memory data_list for speed-up ' . time());
$data_list = array('boost_users' => true, 'boost_courses' => true, 'boost_sessions' => true);
/**
 * Build an array of in-memory database data to reduce time spent querying
 */
if (count($data_list['users']) < 1) {
    MigrationCustom::fill_data_list($data_list);
}
error_log('Built in-memory data_list for speed-up ' . time());
// Counter for transactions found and dealt with
$count_transactions = 0;
/**
 * Check each branch for transactions to execute (and execute them)
 */
$branches = $migration->get_branches();
foreach ($branches as $id => $branch) {
    $response = '';
    $branch_id = $branch['branch_id'];
    if ($mode == 'process') {
        //Load transactions saved before
        $params = array('branch_id' => $branch_id, 'number_of_transactions' => $num_trans);
        $migration->get_transactions_from_webservice($params);
 /**
  * Executes a fields match
  * @param array List of fields that must be matched ('fields_match' => array(0=>array('orig'=>'...','dest'=>'...',...)))
  * @param array Row of data
  * @param array Extra fields table definition
  */
 function execute_field_match($table, $row, $extra_fields = array())
 {
     //error_log('execute_field_match');
     $dest_row = array();
     $first_field = '';
     // If a dest table has been defined, fill $my_extra_fields with the
     //  extra_fields defined for that table
     $my_extra_fields = isset($table['dest_table']) && isset($extra_fields[$table['dest_table']]) ? $extra_fields[$table['dest_table']] : null;
     $extra_field_obj = null;
     $extra_field_value_obj = null;
     if (!empty($table['dest_table'])) {
         $extra_field_obj = new ExtraField($table['dest_table']);
         $extra_field_value_obj = new ExtraFieldValue($table['dest_table']);
     }
     $extra_fields_to_insert = array();
     global $data_list;
     // Fill the data list, if possible
     if (count($data_list['users']) < 1) {
         MigrationCustom::fill_data_list($data_list);
     }
     foreach ($table['fields_match'] as $id_field => $details) {
         //if ($table['dest_table'] == 'session') {error_log('Processing field '.$details['orig']);}
         $params = array();
         // Remove the table name prefix if any (in the orig field)
         if (isset($details['orig'])) {
             $field_exploded = explode('.', $details['orig']);
             if (isset($field_exploded[1])) {
                 $details['orig'] = $field_exploded[1];
             }
         }
         // process the fields one by one
         if ($details['func'] == 'none' || empty($details['func'])) {
             // if no function is defined to alter the field, take it as is
             $dest_data = $row[$details['orig']];
         } else {
             // if an alteration function is defined, run it on the field
             //error_log(__FILE__.' '.__LINE__.' Preparing to treat field with '.$details['func']);
             $dest_data = MigrationCustom::$details['func']($row[$details['orig']], $data_list, $row);
         }
         if (isset($dest_row[$details['dest']])) {
             $dest_row[$details['dest']] .= ' ' . $dest_data;
         } else {
             $dest_row[$details['dest']] = $dest_data;
         }
         //Extra field values
         $extra_field = isset($my_extra_fields) && isset($my_extra_fields[$details['dest']]) ? $my_extra_fields[$details['dest']] : null;
         // Check the array is there
         //if($table['dest_table'] == 'session') error_log('Extra field: '.print_r($extra_field,1));
         if (!empty($extra_field) && $extra_field_obj) {
             //if($table['dest_table'] == 'session') error_log('Extra_field no es vacío');
             // Check the "options" array is defined for this field (checking is_array is crucial here, see BT#5215)
             if (is_array($extra_field['options']) && count($extra_field['options']) > 0) {
                 //if($table['dest_table'] == 'session') error_log('...y sus opciones son: '.print_r($extra_field['options'],1));
                 //if($details['orig']=='uidIdPrograma') { error_log('Eso era lo inicial, del cual se tomó '.$details['dest'].': '.print_r($my_extra_fields,1));}
                 $options = $extra_field['options'];
                 $field_type = $extra_field['field_type'];
                 //if ($table['dest_table'] == 'session') {error_log('Field orig: '.$details['orig']);}
                 if (!empty($options)) {
                     //if ($table['dest_table'] == 'session') {error_log('Options not empty');}
                     if (!is_array($options)) {
                         $options = array($options);
                     }
                     foreach ($options as $option) {
                         if (is_array($option)) {
                             foreach ($option as $key => $value) {
                                 //error_log("$key $value --> {$dest_row[$details['dest']]} ");
                                 if ($key == 'option_value' && $value == $dest_row[$details['dest']]) {
                                     $value = $option['option_display_text'];
                                     if ($field_type == Extrafield::FIELD_TYPE_SELECT) {
                                         $value = $option['option_value'];
                                     }
                                     $params = array('field_id' => $option['field_id'], 'field_value' => $value);
                                     break 2;
                                 }
                             }
                         }
                     }
                 }
             } else {
                 $params = array('field_id' => $extra_field, 'field_value' => $dest_row[$details['dest']]);
             }
             if (!empty($params)) {
                 $extra_fields_to_insert[] = $params;
             }
             unset($dest_row[$details['dest']]);
         }
         unset($extra_field);
     }
     //if ($table['dest_table']=='session') { error_log('Params: '.print_r($params,1)); }
     // If a dest_func entry has been defind, use this entry as the main
     // operation to execute when inserting the item
     if (!empty($table['dest_func'])) {
         //error_log('Calling '.$table['dest_func'].' on data recovered: '.print_r($dest_row, 1));
         $dest_row['return_item_if_already_exists'] = true;
         $item_result = false;
         // Using call_user_func_array() has a serious impact on performance
         switch ($table['dest_func']) {
             case USER_FUNC_EXCEPTION_GRADEBOOK:
                 MigrationCustom::add_gradebook_result_with_evaluation($dest_row);
                 break;
             case USER_FUNC_EXCEPTION_ATTENDANCE:
                 MigrationCustom::create_attendance($dest_row);
                 break;
             default:
                 $item_result = call_user_func_array($table['dest_func'], array($dest_row, $data_list));
         }
         //After the function was executed fill the $data_list array
         switch ($table['dest_table']) {
             case 'course':
                 //Saving courses in array
                 if ($item_result) {
                     //$data_list['courses'][$dest_row['uidIdCurso']] = $item_result;
                 } else {
                     error_log('Course Not FOUND');
                     error_log(print_r($item_result, 1));
                     return false;
                 }
                 $handler_id = $item_result['code'];
                 break;
             case 'user':
                 if (!empty($item_result)) {
                     $handler_id = $item_result['user_id'];
                     //error_log($dest_row['email'].' '.$dest_row['uidIdPersona']);
                     if (isset($dest_row['uidIdAlumno'])) {
                         //$data_list['users_alumno'][$dest_row['uidIdAlumno']]['extra'] = $item_result;
                     }
                     if (isset($dest_row['uidIdEmpleado'])) {
                         //print_r($dest_row['uidIdEmpleado']);exit;
                         //$data_list['users_empleado'][$dest_row['uidIdEmpleado']]['extra'] = $item_result;
                     }
                 } else {
                     global $api_failureList;
                     error_log('Empty user details');
                     error_log(print_r($api_failureList, 1));
                 }
                 break;
             case 'session':
                 //$data_list['sessions'][$dest_row['uidIdPrograma']] = $item_result;
                 $handler_id = $item_result;
                 //session_id
                 break;
         }
         //Saving extra fields of the element
         //error_log('Checking extra fields for '.$extra_field_value_obj->handler_id.' '.$handler_id);
         if (!empty($extra_fields_to_insert)) {
             foreach ($extra_fields_to_insert as $params) {
                 //error_log('Trying to save '.print_r($params,1));
                 $params[$extra_field_value_obj->handler_id] = $handler_id;
                 $extra_field_value_obj->save($params);
             }
         }
     } else {
         // $this->errors_stack[] = "No destination data dest_func found. Abandoning data with first field $first_field = " . $dest_row[$first_field];
     }
     unset($extra_fields_to_insert);
     //remove to free up memory
     return $dest_row;
 }