/**
 * Delete a treasure hunt stage in a road and all fields associated. Then, 
 * repositions the other stages in the road and checks if road is valid.
 * 
 * @param int $id The stage id.
 * @param stdClass $context The context object.
 */
function treasurehunt_delete_stage($id, $context)
{
    global $DB;
    $stage_result = $DB->get_record('treasurehunt_stages', array('id' => $id), 'position,roadid', MUST_EXIST);
    // It can not be delete a stage of a started road.
    if (treasurehunt_check_road_is_blocked($stage_result->roadid)) {
        print_error('notdeletestage', 'treasurehunt');
    }
    $DB->delete_records('treasurehunt_stages', array('id' => $id));
    $DB->delete_records('treasurehunt_attempts', array('stageid' => $id));
    $sql = 'UPDATE {treasurehunt_stages} ' . 'SET position = position - 1 WHERE roadid = (?) AND position > (?)';
    $params = array($stage_result->roadid, $stage_result->position);
    $DB->execute($sql, $params);
    // Check if road is valid.
    treasurehunt_set_valid_road($stage_result->roadid);
    // Trigger deleted stage event.
    $eventparams = array('context' => $context, 'objectid' => $id);
    \mod_treasurehunt\event\stage_deleted::create($eventparams)->trigger();
}
             $stage->noanswers += NUMBER_NEW_ANSWERS;
         }
     }
 } else {
     // new entry
     require_capability('mod/treasurehunt:addstage', $context);
     $title = get_string('addingstage', 'treasurehunt');
     $roadid = required_param('roadid', PARAM_INT);
     $select = "id = ?";
     $params = array($roadid);
     // Compruebo si existe el camino
     if (!$DB->record_exists_select('treasurehunt_roads', $select, $params)) {
         print_error('invalidentry');
     }
     // Compruebo si no esta bloqueado y por tanto no se puede anadir ninguna etapa.
     if (treasurehunt_check_road_is_blocked($roadid)) {
         print_error('notcreatestage', 'treasurehunt', $returnurl);
     }
     $stage = new stdClass();
     $stage->id = null;
     $stage->roadid = $roadid;
 }
 if (!isset($stage->questiontext) || $stage->questiontext === '') {
     $stage->addsimplequestion = optional_param('addsimplequestion', 0, PARAM_INT);
     $stage->noanswers = optional_param('noanswers', 2, PARAM_INT);
     if (!empty($addanswers)) {
         $stage->noanswers += NUMBER_NEW_ANSWERS;
     }
 }
 $stage->cmid = $cmid;
 $returnurl = new moodle_url('/mod/treasurehunt/edit.php', array('id' => $cmid, 'roadid' => $stage->roadid));