function _ops_update()
{
    $OID = max(0, intval($_POST['OID']));
    $CID = max(0, intval($_POST['CID']));
    $msg = "";
    loginRequireMgmt();
    if (!loginCheckPermission(USER::MGMT_HMB_DATA)) {
        redirect("errors/401");
    }
    $itemName = "HMB Data";
    $urlPrefix = "mgmt_hmb_data";
    $object = new HMBData();
    if ($OID) {
        $object->retrieve($OID, $CID);
        if (!$object->exists()) {
            $msg = "{$itemName} not found!";
        } else {
            transactionBegin();
            $object->merge($_POST);
            $object->set("encode", $encode);
            if ($object->update()) {
                transactionCommit();
                $msg = "{$itemName} updated!";
            } else {
                transactionRollback();
                $msg = "{$itemName} update failed";
            }
        }
    } else {
        $object->merge($_POST);
        transactionBegin();
        if ($object->create()) {
            transactionCommit();
            $msg = "{$itemName} created!";
        } else {
            transactionRollback();
            $msg = "{$itemName} Create failed";
        }
    }
    redirect("{$urlPrefix}/manage", $msg);
}
function _ops_loaddb()
{
    $urlPrefix = "mgmt_hmb_data";
    $item = "HMBData";
    if (isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
        // open the csv file for reading
        $file_path = $_FILES['csv_file']['tmp_name'];
        $handle = fopen($file_path, 'r');
        try {
            transactionBegin();
            $o = new HMBData();
            if ($o->truncateTable() === false) {
                throw new Exception("truncate {$item}");
            }
            while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                if (count($data) != 7) {
                    throw new Exception("wrong number of value of {$item}");
                }
                $o = new HMBData();
                $o->set('_1st_on', $data[0]);
                $o->set('_1st_off', $data[1]);
                $o->set('_2nd_on', $data[2]);
                $o->set('_2nd_off', $data[3]);
                $o->set('_3rd_on', $data[4]);
                $o->set('_3rd_off', $data[5]);
                $o->set('cycle', $data[6]);
                if ($o->create() === false) {
                    throw new Execption("Can't create {$item} object");
                }
            }
            transactionCommit();
            $msg = "Load {$item} completed";
        } catch (Exception $e) {
            transactionRollback();
            $msg = "caught exception " . $e->getMessage();
        }
        // delete csv file
        unlink($file_path);
    } else {
        $msg = "error no file uploaded";
    }
    redirect("{$urlPrefix}/manage", $msg);
}
function _resetdb()
{
    if (!isset($_POST['dataOption'])) {
        echo "error";
        exit;
    }
    $dataOption = $_POST['dataOption'];
    try {
        $dbh = getdbh();
        $list = explode(",", "v_leaderboard_main,v_ext_ranks,v_leaderboard_ext");
        foreach ($list as $view) {
            dropView($dbh, $view);
        }
        //
        //  rPI challenge data
        //
        $list = explode(",", "t_cts_data,t_fsl_data,t_hmb_data,t_cpa_data,t_ext_data");
        foreach ($list as $table) {
            dropTable($dbh, $table);
        }
        $list = explode(",", "t_event,t_user,t_rpi,t_station,t_stationtype,t_team,t_school");
        foreach ($list as $table) {
            dropTable($dbh, $table);
        }
        create_t_user($dbh);
        create_t_stationtype($dbh);
        create_t_station($dbh);
        create_t_school($dbh);
        create_t_team($dbh);
        create_t_event($dbh);
        create_t_rpi($dbh);
        create_v_leaderboard_main($dbh);
        create_v_ext_ranks($dbh);
        create_v_leaderboard_ext($dbh);
        //
        //  rPI challenge data
        //
        create_t_cts_data($dbh);
        create_t_fsl_data($dbh);
        create_t_hmb_data($dbh);
        create_t_cpa_data($dbh);
        create_t_ext_data($dbh);
        $admin = new User();
        $admin->set('username', "admin");
        $admin->setPassword('pass');
        $admin->set('email', "*****@*****.**");
        $admin->set('fullname', "administrator");
        $admin->setRoll(USER::ROLL_ADMIN);
        $admin->create();
        $stationType = StationType::makeStationType(StationType::STATION_TYPE_REG, "Register", false, 60, "Hello! You have been successfully registered and may start the competition. Good luck!", "If you see this message there was an internal error 1", "If you see this message there was an internal error 2", "If you see this message there was an internal error 3");
        if ($stationType === false) {
            echo "Create StationType REG failed";
        } else {
            createStations(1, "reg", $stationType->get('OID'));
        }
        $stationType = StationType::makeStationType(StationType::STATION_TYPE_CTS, "Crack The Safe", true, 60, "Welcome, Team! Your first assignment is to break into Professor Aardvark's safe where you will find the first clue to his Secret Laboratory. Measure the interior angles and pick the three correct angles for the safe combination. Good luck! [clue=[clue]]", "Success! Go quickly to the next team queue.", "You have failed the challenge. Go quickly to the next team queue.", "No luck, better try again!");
        $numStations = $dataOption == 1 ? 1 : 6;
        if ($stationType === false) {
            echo "Create StationType CTS failed";
        } else {
            createStations($numStations, "cts", $stationType->get('OID'));
        }
        $stationType = StationType::makeStationType(StationType::STATION_TYPE_FSL, "Find Secret Lab", false, 60, "Find and scan the [ordinal] at [waypoint-lat=[lat]] [waypoint-lon=[lng]].", "Success! Find and scan the [ordinal] marker at [waypoint-lat=[lat]] [waypoint-lon=[lng]].", "Too bad, you failed. Find and scan the [ordinal] marker at [waypoint-lat=[lat]] [waypoint-lon=[lng]].", "Wrong marker, try again!");
        if ($stationType === false) {
            echo "Create StationType FSL failed";
        } else {
            createStations(1, "fsl", $stationType->get('OID'));
        }
        $stationType = StationType::makeStationType(StationType::STATION_TYPE_HMB, "Defuse Hypermutation Bomb", true, 60, "The HMB has been triggered! Send the Energy Pulsator cycle time quickly!", "Success! Go quickly to the next team queue.", "Oops. Enough said. Go quickly to the next team queue.", "Nope, better try again!");
        $numStations = $dataOption == 1 ? 1 : 6;
        if ($stationType === false) {
            echo "Create StationType HMB failed";
        } else {
            createStations($numStations, "hmb", $stationType->get('OID'));
        }
        $stationType = StationType::makeStationType(StationType::STATION_TYPE_CPA, "Catch Provessor Aardvark", true, 2000, "PA is trying to escape. Quickly measure the [fence=label] [building=[label]] and scan Start QR Code.", "Watch now as the professor attempts to escape. Get him!", "Success! Go quickly to the team finish area.", "Professor Aardvark has escaped. Oh well. Go quickly to the team finish area.", "Miss! Try again!");
        $numStations = $dataOption == 1 ? 1 : 6;
        if ($stationType === false) {
            echo "Create StationType CPA failed";
        } else {
            createStations($numStations, "cpa", $stationType->get('OID'));
        }
        $stationType = StationType::makeStationType(StationType::STATION_TYPE_EXT, "Extra", false, 60, "You have 20 (TBR) minutes to provide the tower location and height. Good luck." . " [waypoint1-lat=[a_lat]] [waypoint1-lon=[a_lng]]" . " [waypoint2-lat=[b_lat]] [waypoint2-lon=[b_lng]]" . " [waypoint3-lat=[c_lat]] [waypoint3-lon=[c_lng]]", "Message received, return to base", "M didn't understand your message", "If you see this message there was an internal error 5");
        if ($stationType === false) {
            echo "Create StationType EXT failed";
        } else {
            createStations(1, "ext", $stationType->get('OID'));
        }
        if ($dataOption == 0) {
            redirect('mgmt_main', 'Database Initialized without test data!');
            return;
        }
        // generate test data
        // for ($i=1;$i < 21; $i++) {
        //  $user = new User();
        //  $user->set('username','user'.$i);
        //  $user->setPassword('pass'.$i);
        //  $user->set('email','email'.$i."@harris.com");
        //  $user->set('fullname','User #'.$i);
        //  if ($user->create()===false) echo "Create user $i failed";
        // }
        // keep an equal number of each of these items.
        $mascots = explode(",", "Unencoded,Encoded,Unencoded,Encoded,Unencoded,Encoded,Unencoded,Encoded,Unencoded,Encoded,Unencoded,Encoded,Unencoded,Encoded");
        $schools = explode(",", "Titusville HS,Edgewood Jr/Sr HS,Holy Trinity,West Shore Jr/Sr HS,Melbourne HS,Palm Bay Magnet HS,Bayside HS");
        // keep twice as many name&pins we will populate 2 teams / school
        $names = explode(",", "team1,team2,team3,team4,team5,team6,team7,team8,team9,team10,team11,team12,team13,team14");
        $pins = explode(",", "00001,00002,00003,00004,00005,00006,00007,00008,00009,00010,00011,00012,00013,00014");
        // always make the schools
        $numSchools = count($schools);
        for ($i = 0; $i < $numSchools; $i++) {
            $school = new School();
            $school->set("name", $schools[$i]);
            $school->set("mascot", $mascots[$i]);
            if ($school->create() === false) {
                echo "Create School {$i} failed";
            }
            $schools[$i] = $school->get('OID');
            // replace school name with OID for next part
        }
        // TODO always make the teams with random ids
        $numTeams = $dataOption == 1 ? 2 : count($names);
        for ($i = 0; $i < $numTeams; $i++) {
            $team = new Team();
            $team->set("name", $names[$i]);
            $team->set("schoolId", $schools[$i / 2]);
            /*use OID from previous step two teams / school */
            $team->set("pin", $pins[$i]);
            // to test ext we need special test data
            $team->set('extDuration', $i * 100);
            $team->set('towerH', $i);
            $team->set('towerD', $i);
            if ($team->create() === false) {
                echo "Create team {$i} failed";
            }
        }
        for ($i = 1; $i <= ($dataOption == 1 ? 1 : 5); $i++) {
            $cts = new CTSData();
            $station = Station::getFromTag("cts0" . $i);
            if ($station === false) {
                break;
            }
            $cts->set('stationId', $station->get('OID'));
            // hack assume get works
            if (isStudentServer() && $i == 1) {
                $cts->set('_1st', 39);
                $cts->set('_2nd', 57);
                $cts->set('_3rd', 13);
                $cts->set('_4th', 23);
                $cts->set('_5th', 48);
            } else {
                $cts->set('_1st', 10 + $i);
                $cts->set('_2nd', 20 + $i);
                $cts->set('_3rd', 30 + $i);
                $cts->set('_4th', 40 + $i);
                $cts->set('_5th', 50 + $i);
            }
            $cts->set('tolerance', 5.0);
            if ($cts->create() === false) {
                echo "Create CTS {$i} failed";
            }
        }
        for ($i = 1; $i <= ($dataOption == 1 ? 1 : 5); $i++) {
            $cpa = new CPAData();
            $station = Station::getFromTag("cpa0" . $i);
            if ($station === false) {
                break;
            }
            $cpa->set('stationId', $station->get('OID'));
            // hack assume get works
            if ($i == 1) {
                $cpa->set('label', $i);
                $cpa->set('fence', 240);
                $cpa->set('building', 127);
                $cpa->set('sum', 367);
            } else {
                $cpa->set('label', $i);
                $cpa->set('fence', 240 + $i);
                $cpa->set('building', 127 - $i);
                $cpa->set('sum', 367);
            }
            if ($cpa->create() === false) {
                echo "Create CTA {$i} failed";
            }
        }
        $hmb = new HMBData();
        $hmb->set('_1st_on', 1);
        $hmb->set('_1st_off', 1);
        $hmb->set('_2nd_on', 1);
        $hmb->set('_2nd_off', 10);
        $hmb->set('_3rd_on', 1);
        $hmb->set('_3rd_off', 22);
        $hmb->set('cycle', 506);
        if ($hmb->create() === false) {
            echo "Create HMB {$i} failed";
        }
        $fsl_data = array(array("1", +28.030924, -80.601834, "1", +28.032708, -80.600032, "1", +28.03167, -80.59855899999999, "1", +28.031062, -80.600013, 665.8, 600.1, 574.6), array("1", +28.030924, -80.601834, "1", +28.032708, -80.600032, "1", +28.03167, -80.59855899999999, "2", +28.030975, -80.60010699999999, 629.9, 632.4, 618.6), array("1", +28.030924, -80.601834, "1", +28.032708, -80.600032, "1", +28.03167, -80.59855899999999, "3", +28.030859, -80.60001800000001, 662.5, 674.1, 608.6));
        for ($i = 0; $i < count($fsl_data); $i++) {
            $fsl = new FSLData();
            $fsl->set('a_tag', $fsl_data[$i][0]);
            $fsl->set('a_lat', $fsl_data[$i][1]);
            $fsl->set('a_lng', $fsl_data[$i][2]);
            $fsl->set('b_tag', $fsl_data[$i][3]);
            $fsl->set('b_lat', $fsl_data[$i][4]);
            $fsl->set('b_lng', $fsl_data[$i][5]);
            $fsl->set('c_tag', $fsl_data[$i][6]);
            $fsl->set('c_lat', $fsl_data[$i][7]);
            $fsl->set('c_lng', $fsl_data[$i][8]);
            $fsl->set('l_tag', $fsl_data[$i][9]);
            $fsl->set('l_lat', $fsl_data[$i][10]);
            $fsl->set('l_lng', $fsl_data[$i][11]);
            $fsl->set('a_rad', $fsl_data[$i][12]);
            $fsl->set('b_rad', $fsl_data[$i][13]);
            $fsl->set('c_rad', $fsl_data[$i][14]);
            if ($fsl->create() === false) {
                echo "Create FSLData {$i} failed";
            }
        }
        $ext = new EXTData();
        $ext->set('a_lat', +28.031848);
        $ext->set('a_lng', -80.600938);
        $ext->set('b_lat', +28.031695);
        $ext->set('b_lng', -80.600413);
        $ext->set('c_lat', +28.031579);
        $ext->set('c_lng', -80.60087300000001);
        $ext->set('t_lat', +28.031698);
        $ext->set('t_lng', -80.60075500000001);
        $ext->set('height', 102);
        if ($ext->create() === false) {
            echo "Create EXTData {$i} failed";
        }
        redirect('mgmt_main', 'Database Initialized test data!');
    } catch (ErrorInfo $e) {
        echo $e->getMessage();
        die;
    }
}