/**
 * put your comment there...
 *
 *
 * @param mixed $config
 */
function createMappingForm($config)
{
    global $sourcedbname, $db_prefix, $dbPrefix, $is_h2, $useOriginalID;
    $sourcedb = $db_prefix . $sourcedbname;
    print "<br>\n";
    //print "Source database: <b>$sourcedb</b> <br>\n";
    if ($is_h2) {
        $res = mysql_query("select * from `{$sourcedb}`.Users");
    } else {
        $res = mysql_query("select * from {$sourcedb}.sysIdentification");
    }
    if (!$res) {
        die("<p>Unable to open source database <b>{$sourcedb}</b>. Make sure you have included prefix");
    }
    print "<form name='mappings' action='compareStructure.php' method='post'>";
    print "<input id='mode' name='mode' value='5' type='hidden'>";
    // calls the transfer function
    print "<input name='db' value='" . HEURIST_DBNAME . "' type='hidden'>";
    print "<input name='h2' value='" . ($is_h2 ? 1 : 0) . "' type='hidden'>";
    //print "<input name='sourcedbname' value='$sourcedbname' type='hidden'>";
    //print "<input name='reportlevel' value='1' type='checkbox' checked='checked'>Report level: show errors only<br>";
    //print "Check the code mappings below, then click  <input type='button' value='Import data' onclick='{document.getElementById(\"mode\").value=5; document.forms[\"mappings\"].submit();}'>\n";
    // alert(document.getElementById(\"mode\").value);
    /*
    print "<input type='button' value='Save settings' onclick='{document.getElementById(\"mode\").value=3; document.forms[\"mappings\"].submit();}'>";
    
    $filename = HEURIST_FILESTORE_DIR."settings/importfrom_".$sourcedbname.".cfg";
    
    if(file_exists($filename)){
    print "<input type='submit' value='Load settings' onclick='{document.getElementById(\"mode\").value=4; document.forms[\"mappings\"].submit();}'>\n";
    }
    */
    print "<p><hr>\n";
    // --------------------------------------------------------------------------------------------------------------------
    // Get the record type mapping, by default assume that the code is unchanged so select the equivalent record type if available
    $d_rectypes = getAllRectypeStructures();
    //in current database
    $d_dettypes = getAllDetailTypeStructures();
    $d_rtnames = $d_rectypes['names'];
    mysql_connection_overwrite($sourcedb);
    $s_rectypes = getAllRectypeStructures(false);
    $s_dettypes = getAllDetailTypeStructures(false);
    $s_rtnames = $s_rectypes['names'];
    print "<table border='1' width='900'><tr><td width='300'>" . $sourcedbname . "</td><td colspan='2'>" . HEURIST_DBNAME . "</td></tr>";
    $fi_type = $s_dettypes['typedefs']['fieldNamesToIndex']['dty_Type'];
    $fi_name = $s_dettypes['typedefs']['fieldNamesToIndex']['dty_Name'];
    $fi_rt_concept = $s_rectypes['typedefs']['commonNamesToIndex']['rty_ConceptID'];
    $fi_dt_concept = $s_dettypes['typedefs']['fieldNamesToIndex']['dty_ConceptID'];
    foreach ($s_rtnames as $s_id => $s_name) {
        $s_conceptid = $s_rectypes['typedefs'][$s_id]['commonFields'][$fi_rt_concept];
        $dest_id = null;
        $dest_name = null;
        //find record type in destination
        foreach ($d_rtnames as $d_id => $d_name) {
            if ($useOriginalID && $d_rectypes['typedefs'][$d_id]['commonFields'][$fi_rt_concept] == $s_conceptid || !$useOriginalID && $d_name == $s_name) {
                //print "[".$d_id."]  ".$d_name."<br/>";
                //print structure in the same order as source rectype
                $dest_id = $d_id;
                $dest_name = $d_name;
                break;
            }
        }
        //Header  <tr><td colspan='2'><table border='1' width='100%'>
        print "<tr style='background-color:#AAAAAA;'><td width='250'><b>[" . $s_id . "]  " . $s_name . "</b>(" . $s_conceptid . ")</td><td width='250'>";
        if ($dest_id == null) {
            print "...not found";
        } else {
            print "<b>[" . $dest_id . "]  " . $dest_name . "</b>";
        }
        print "</td><td width='400'>&nbsp;</td></tr>";
        //list of field types
        $s_flds = $s_rectypes['typedefs'][$s_id]['dtFields'];
        foreach ($s_flds as $sft_id => $sft_desc) {
            $fld_in_dest_rectype = "&nbsp;";
            $fld_in_dest_all = "&nbsp;";
            $s_conceptid = $s_dettypes['typedefs'][$sft_id]['commonFields'][$fi_dt_concept];
            $s_fitype = $s_dettypes['typedefs'][$sft_id]['commonFields'][$fi_type];
            //find in destination record type
            if ($dest_id != null) {
                $d_flds = $d_rectypes['typedefs'][$dest_id]['dtFields'];
                foreach ($d_flds as $dft_id => $dft_desc) {
                    //compare by original field name and by type
                    if ($useOriginalID && $d_dettypes['typedefs'][$dft_id]['commonFields'][$fi_dt_concept] == $s_conceptid || !$useOriginalID && $s_dettypes['names'][$sft_id] == $d_dettypes['names'][$dft_id] && $s_fitype == $d_dettypes['typedefs'][$dft_id]['commonFields'][$fi_type]) {
                        $fld_in_dest_rectype = "[" . $dft_id . "] " . $dft_desc[0];
                        break;
                    }
                }
            }
            //if not found try to find in entire list of field types
            if ($fld_in_dest_rectype == "&nbsp;") {
                $d_flds = $d_dettypes['typedefs'];
                foreach ($d_flds as $dft_id => $dft_def) {
                    //compare by original field name and by type
                    if ($useOriginalID && $dft_def['commonFields'][$fi_dt_concept] == $s_conceptid || !$useOriginalID && $s_dettypes['names'][$sft_id] == $dft_def['commonFields'][$fi_name] && $s_fitype == $dft_def['commonFields'][$fi_type]) {
                        $fld_in_dest_all = "[" . $dft_id . "] " . $dft_def['commonFields'][$fi_name] . "  (" . $s_fitype . ")";
                        break;
                    }
                }
            }
            print "<tr><td>[" . $sft_id . "] " . $sft_desc[0] . "&nbsp;(" . $s_conceptid . ")</td><td>" . $fld_in_dest_rectype . "</td><td>" . $fld_in_dest_all . "</td></tr>";
        }
        ///print "</table></td><tr>";
    }
    print "</table>";
    return;
    $entnames = $entnames['names'];
    $seloptions = createOptions("or", $entnames);
    if ($is_h2) {
        $query1 = "SELECT DISTINCT `rec_type`,`rt_name` FROM `{$sourcedb}`.`records`,`{$sourcedb}`.`rec_types` where `rec_type`=`rt_id`";
    } else {
        $query1 = "SELECT rty_ID, rty_Name, count(rec_ID) as cnt " . "from `{$sourcedb}`.`Records` " . "left join `{$sourcedb}`.`defRecTypes` on rec_RecTypeID=rty_ID " . "group by rty_ID";
    }
    $res1 = mysql_query($query1);
    if (mysql_num_rows($res1) == 0) {
        die("<p><b>Sorry, there are no data records in this database, or database is bad format</b>");
    }
    print "<h3>Record type mappings</h3> &nbsp;[RT code] <b>{$sourcedb}</b> &nbsp;(use count) ==> <b>{$dbPrefix}" . HEURIST_DBNAME . "</b><p>";
    // . "<p>";
    print "<table>";
    while ($row1 = mysql_fetch_array($res1)) {
        $rt = $row1[0];
        //0=rec_RecTypeID
        $cnt = $row1[2];
        $selopts = $seloptions;
        $selectedId = getPresetId($config, "cbr" . $rt);
        if (!$selectedId) {
            //find the closest name
            $selectedId = findClosestName($row1[1], $entnames);
            //1=rty_Name
        }
        if ($selectedId) {
            $repl = "value='" . $selectedId . "'";
            $selopts = str_replace($repl, $repl . " selected='selected' ", $selopts);
        }
        print "<tr><td>" . $row1[1] . " [ {$rt} ] n=({$cnt}) </td>" . "<td>==> <select id='cbr{$rt}' name='cbr{$rt}' class='rectypes'><option id='or0' value='0'></option>" . $selopts . "</select></td></tr>\n";
    }
    // loop through record types
    print "</table>";
    // --------------------------------------------------------------------------------------------------------------------
    // Get the field type mapping, by default assume that the code is unchanged so select the equivalent detail type if available
    //create the string for combobox
    $entnames = getAllDetailTypeStructures();
    //in current database
    $entnames = $entnames['names'];
    $seloptions = createOptions("od", $entnames);
    print "<h3>Field type mappings</h3>[FT code] <b>{$sourcedb}</b> ==> <b>{$dbPrefix}" . HEURIST_DBNAME . "</b><p>";
    // . "<p>";
    if ($is_h2) {
        $query1 = "SELECT DISTINCT `rd_type`,`rdt_name`,`rdt_type` FROM `{$sourcedb}`.`rec_details`,`{$sourcedb}`.`rec_detail_types` " . "where `rd_type`=`rdt_id`";
    } else {
        $query1 = "SELECT DISTINCT `dtl_DetailTypeID`,`dty_Name`,`dty_Type` FROM `{$sourcedb}`.`recDetails`,`{$sourcedb}`.`defDetailTypes` " . "where `dtl_DetailTypeID`=`dty_ID`";
    }
    $res1 = mysql_query($query1);
    print "<table>";
    while ($row1 = mysql_fetch_array($res1)) {
        $ft = $row1[0];
        //0=dtl_DetailTypeID
        $selopts = $seloptions;
        //find the closest name
        $selectedId = getPresetId($config, "cbd" . $ft);
        if (!$selectedId) {
            //find the closest name
            $selectedId = findClosestName($row1[1], $entnames);
            //dty_Name
        }
        if ($selectedId) {
            $repl = "value='" . $selectedId . "'";
            $selopts = str_replace($repl, $repl . " selected='selected' ", $selopts);
        }
        print "<tr><td>[ {$ft} ] - " . $row1[2] . " " . $row1[1] . " </td>" . "<td>==> <select id='cbd{$ft}' name='cbd{$ft}' class='detailTypes'><option id='od0' value='0'></option>" . $selopts . "</select></td></tr>\n";
    }
    // loop through field types
    print "</table>";
    // --------------------------------------------------------------------------------------------------------------------
    createTermsOptions($config, 'enum');
    createTermsOptions($config, 'relation');
    print "</form>";
}
function createMappingForm($config)
{
    global $sourcedbname, $db_prefix, $dbPrefix, $is_h2, $password, $username;
    $sourcedb = $db_prefix . $sourcedbname;
    print "<br>\n";
    print "Source database: <b>{$sourcedb}</b> <br>\n";
    if ($is_h2) {
        $res = mysql_query("select * from `{$sourcedb}`.Users");
    } else {
        $res = mysql_query("select * from {$sourcedb}.sysIdentification");
    }
    if (!$res) {
        die("<p>Unable to open source database <b>{$sourcedb}</b>. Make sure you have included prefix");
    }
    print "<form id='mapping' name='mappings' action='getRecordsFromDB.php' method='post'>";
    print "<input id='mode' name='mode' value='5' type='hidden'>";
    // calls the transfer function
    print "<input name='db' value='" . HEURIST_DBNAME . "' type='hidden'>";
    print "<input name='h2' value='" . ($is_h2 ? 1 : 0) . "' type='hidden'>";
    print "<input name='sourcedbname' value='{$sourcedbname}' type='hidden'>";
    if (!$is_h2) {
        print "<input name='username' value='{$username}' type='hidden'>";
        print "<input name='password' value='{$password}' type='hidden'>";
    }
    print "<input name='reportlevel' value='1' type='checkbox' checked='checked'>&nbsp;Report level: show errors only<br>";
    print "Check the code mappings below, then click  <input type='button' value='Import data' onclick='{document.getElementById(\"mode\").value=5; document.forms[\"mappings\"].submit();}'>\n";
    // alert(document.getElementById(\"mode\").value);
    print "<input type='button' value='Print mapping' onclick='{printMapping();}'>&nbsp;";
    print "<input type='button' value='Save settings' onclick='{document.getElementById(\"mode\").value=3; document.forms[\"mappings\"].submit();}'>";
    $filename = HEURIST_UPLOAD_DIR . "settings/importfrom_" . $sourcedbname . ".cfg";
    if (file_exists($filename)) {
        print "&nbsp;<input type='submit' value='Load settings' onclick='{document.getElementById(\"mode\").value=4; document.forms[\"mappings\"].submit();}'>\n";
    }
    print "<p><hr>\n";
    // --------------------------------------------------------------------------------------------------------------------
    // Get the record type mapping, by default assume that the code is unchanged so select the equivalent record type if available
    $allrectypes = getAllRectypeStructures();
    //in current database
    $entnames = $allrectypes['names'];
    $seloptions = createOptions("or", $entnames);
    if ($is_h2) {
        $query1 = "SELECT DISTINCT `rec_type`,`rt_name`, '0' as cnt FROM `{$sourcedb}`.`records`,`{$sourcedb}`.`rec_types` where `rec_type`=`rt_id`";
    } else {
        $query1 = "SELECT rty_ID, rty_Name, count(rec_ID) as cnt, rty_OriginatingDBID, rty_IDInOriginatingDB  " . "from `{$sourcedb}`.`Records` " . "left join `{$sourcedb}`.`defRecTypes` on rec_RecTypeID=rty_ID " . "group by rty_ID";
    }
    $res1 = mysql_query($query1);
    if (mysql_num_rows($res1) == 0) {
        die("<p><b>Sorry, there are no data records in this database, or database is bad format</b>");
    }
    print "<h3>Record type mappings</h3>[RT code] <b>{$sourcedb}</b> (use count) ==> <b>{$dbPrefix}" . HEURIST_DBNAME . "</b><p>";
    // . "<p>";
    print "<table>";
    while ($row1 = mysql_fetch_array($res1)) {
        $rt = $row1[0];
        //0=rec_RecTypeID
        $cnt = $row1[2];
        $selopts = $seloptions;
        $selectedId = null;
        $bgcolor = "";
        if ($config) {
            $selectedId = getPresetId($config, "cbr" . $rt);
        } else {
            if (!$is_h2) {
                //find by concept code
                $selectedId = findByRtConceptCode($row1[3], $row1[4], $allrectypes);
                if ($selectedId) {
                    $bgcolor = "style='background-color:#ccffcc;'";
                }
            }
            if (!$selectedId) {
                //find the closest name
                $selectedId = findClosestName($row1[1], $entnames);
                //1=rty_Name
                if ($selectedId < 0) {
                    //exact match
                    $bgcolor = "style='background-color:#ccc;'";
                    $selectedId = -$selectedId;
                }
            }
        }
        if ($selectedId) {
            $repl = "value='" . $selectedId . "'";
            $selopts = str_replace($repl, $repl . " selected='selected' ", $selopts);
        }
        print "<tr {$bgcolor}><td><label id='lblr{$rt}'>[ {$rt} ] " . $row1[1] . ($is_h2 ? "" : "({$cnt}) ") . "</label></td>" . "<td>==> <select id='cbr{$rt}' name='cbr{$rt}' class='rectypes'><option id='or0' value='0'></option>" . $selopts . "</select></td></tr>\n";
    }
    // loop through record types
    print "</table>";
    // --------------------------------------------------------------------------------------------------------------------
    // Get the field type mapping, by default assume that the code is unchanged so select the equivalent detail type if available
    //create the string for combobox
    $alldettypes = getAllDetailTypeStructures();
    //in current database
    $entnames = $alldettypes['names'];
    $seloptions = createOptionsDt($alldettypes);
    print "<h3>Field type mappings</h3>[FT code] <b>{$sourcedb}</b> ==> <b>{$dbPrefix}" . HEURIST_DBNAME . "</b><p>";
    // . "<p>";
    if ($is_h2) {
        $query1 = "SELECT DISTINCT `rd_type`,`rdt_name`,`rdt_type` FROM `{$sourcedb}`.`rec_details`,`{$sourcedb}`.`rec_detail_types` " . "where `rd_type`=`rdt_id`";
    } else {
        $query1 = "SELECT DISTINCT `dtl_DetailTypeID`,`dty_Name`,`dty_Type`,`dty_OriginatingDBID`,`dty_IDInOriginatingDB` FROM `{$sourcedb}`.`recDetails`,`{$sourcedb}`.`defDetailTypes` " . "where `dtl_DetailTypeID`=`dty_ID`";
    }
    $res1 = mysql_query($query1);
    print "<table>";
    while ($row1 = mysql_fetch_array($res1)) {
        $ft = $row1[0];
        //0=dtl_DetailTypeID
        $selopts = $seloptions;
        $bgcolor = "";
        $selectedId = null;
        //find the closest name
        if ($config) {
            $selectedId = getPresetId($config, "cbd" . $ft);
        } else {
            if (!$is_h2) {
                //find by concept code
                $selectedId = findByDtConceptCode($row1[3], $row1[4], $alldettypes);
                if ($selectedId) {
                    $bgcolor = "style='background-color:#ccffcc;'";
                }
            }
            if (!$selectedId) {
                //find the closest name
                $selectedId = findClosestName($row1[1], $entnames);
                //dty_Name
                if ($selectedId < 0) {
                    //exact match
                    $bgcolor = "style='background-color:#ccc;'";
                    $selectedId = -$selectedId;
                }
            }
        }
        if ($selectedId) {
            $repl = "value='" . $selectedId . "'";
            $selopts = str_replace($repl, $repl . " selected='selected' ", $selopts);
        }
        print "<tr {$bgcolor}><td><label id='lbld{$ft}'>[ {$ft} - " . $row1[2] . " ] " . $row1[1] . "</label></td>" . "<td>==> <select id='cbd{$ft}' name='cbd{$ft}' class='detailTypes'><option id='od0' value='0'></option>" . $selopts . "</select></td></tr>\n";
    }
    // loop through field types
    print "</table>";
    // --------------------------------------------------------------------------------------------------------------------
    createTermsOptions($config, 'enum');
    createTermsOptions($config, 'relation');
    print "</form>";
}