# packages/notes/www/add-edit.tcl
ad_page_contract {
    @author Richard Hamilton (richard.hamilton@webteamworks.com)
    @creation-date 18-09-2005
    @cvs-id@ $Id$
    Intrasite Message folder add/edit' page
} {
    folder_id:integer,notnull,optional
} -properties {
    context:onevalue
}

# the unique identifier for this package
set package_id  [ad_conn package_id]
set package_url [ad_conn package_url]
set user_id     [ad_conn user_id]

# Check permissions on the package_id
ad_require_permission $package_id write

set title "Add or Edit Folder"

if {[info exists folder_id]} {
    
    ad_require_permission $package_id write
    # Need to replace this with a check for url surgery - i.e. check user_id and immutable_p
    
    # Ensure that the folder belongs to the requesting user.
    db_1row folder_owner_p {
        select im_message__folder_owner_p(:folder_id, :user_id) as folder_owner_p
    }
    
    if { [string is false $folder_owner_p] } { ad_script_abort }

    set context [list "Edit Folder"]

} else {
    ad_require_permission $package_id create

    set context [list "Add New Folder"]
}

template::form create new_folder

if {[template::form is_request new_folder] && [info exists folder_id]} {

  template::element create new_folder folder_id \
      -widget hidden \
      -datatype number \
      -value $folder_id

  db_1row get_folder_name {
    select folder_name
    from im_folder
    where folder_id = :folder_id
  }
} else { 
    set folder_name {}
}

template::element create new_folder folder_name \
    -datatype text \
    -label "Folder Name" \
    -html { size 30 } \
    -value $folder_name

if [template::form is_valid new_folder] {
  form get_values new_folder folder_name

  set peeraddr [ad_conn peeraddr]

  if [info exists folder_id] {
    db_dml update_folder_name {
      update im_folder
      set folder_name = :folder_name
      where folder_id = :folder_id
    }
  } else {
    db_1row folder_new {
      select im_folder__new(:folder_name, :user_id, 'false')
    }
  }

  ad_returnredirect "./"
}

set title [ad_quotehtml $title]

ad_return_template
