xquery version "1.0";

declare option exist:serialize "method=xhtml media-type=text/html indent=yes";
 
let $app-collection := '/db/apps/terms'
let $data-collection := '/db/apps/terms/data'
 
(: get the form data that has been "POSTed" to this XQuery :)
let $item := request:get-data()
 
(: get the next ID from the next-id.xml file :)
let $next-id-file-path := concat($app-collection, '/edit/next-id.xml')
let $next-id := doc($next-id-file-path)/data/next-id/text() 
let $file := concat($next-id, '.xml')

(: log into the collection :)
let $login := xmldb:login($app-collection, 'admin', 'myadminpassword')

(: create the new file with a still-empty id element :)
let $store := xmldb:store($data-collection, $file, $item)
let $new-document := doc(concat($data-collection, '/', $file))

(: add the correct ID to the new document we just saved :)
let $update-id := update value $new-document/term/id with $next-id

(: update the next-id.xml file :)
let $new-next-id :=  update value $next-id with $next-id + 1

(: we need to return the original ID number in our results, 
   but the previous update expression increased $next-id by 1 :)
let $original-id := $next-id - 1

return
<html>
    <head>
        <title>Save Conformation</title>
    </head>
    <body>
        <a href="../index.xhtml">Term Home</a>
        <p>Term {$original-id} has been saved.</p>
        <a href="../views/list-items.xq">List all Terms</a> 
    </body>
</html>