ad_page_contract {

    @author Richard Hamilton <richard.hamilton@webteamworks.com>
    @creation-date 2005-11-24

} {
    {selected_messages:integer,multiple}
    {confirm_p:boolean 0}
    {objects_context:optional "In-box"}
    {action}
    {new_folder_id:optional}
    {new_folder_name:optional}
}

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

# Check permissions on the package_id
ad_require_permission $package_id delete

# On the index page the user can select messages with checkboxes and use one of two submit
# buttons - "Delete" or "Move".

if { $action == "Delete"} {

  # The Delete action code starts here. Begin by checking whether the user has yet confirmed the request.
  if { [string is false $confirm_p] } {
    set num_entries [llength $selected_messages]

    if { $num_entries == 0 } {
        ad_returnredirect "./index?objects_context=$objects_context"
        return
    }

    set title "Confirm Message Delete [ad_decode $num_entries 1 "Entry" "Entries"]"
    set context [list $title]
    set yes_url "message-move-delete?[export_vars { selected_messages:multiple { confirm_p 1 } {objects_context $objects_context} {action "Delete"} }]"
    set no_url "./index?objects_context=$objects_context"

    return
  }

  foreach message_id $selected_messages {
    db_1row delete_message {
        select im_message__delete (:message_id, :user_id)
    }
  }

} else {

  # The Move action code starts here. Begin by checking whether the user has yet confirmed the request.
  if { [string is false $confirm_p] } {
    set num_entries [llength $selected_messages]

    if { $num_entries == 0 } {
        ad_returnredirect "./index?objects_context=$objects_context"
        return
    }

    db_1row lookup_folder_name {
        select folder_name
        from im_folder
        where folder_id = :new_folder_id
    }

    set title "Confirm Message Move [ad_decode $num_entries 1 "Entry" "Entries"]"
    set context [list $title]
    set yes_url "message-move-delete?[export_vars { selected_messages:multiple { confirm_p 1 } {objects_context $objects_context} {action "Move"} {new_folder_id $new_folder_id} }]"
    set no_url "./index?objects_context=$objects_context"

    return
  }

  foreach message_id $selected_messages {
    db_1row move_message {
        select im_message__move (:message_id, :user_id, :new_folder_id)
    }
  }

}

ad_returnredirect "./index?objects_context=$objects_context"
ad_script_abort
