ad_page_contract {

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

} {
    {selected_addressees:integer,multiple}
    {confirm_p:boolean 0}
    {message_id:integer,notnull}
    {address_mode:integer,notnull}
}

set user_id [ad_verify_and_get_user_id]

# Is the requesting user the author? If not - ignore the request.
db_1row message_author_p {
        select im_message__author_p(:message_id, :user_id) as message_author_p
}

if { [string is false $message_author_p] } { ad_script_abort }

# Check permissions on the package_id
ad_require_permission [ad_conn package_id] write

# Extract the user names to match the ids in $selected_addressees
set in_clause [template::util::tcl_to_sql_list $selected_addressees]

db_multirow addressee_names lookup_names "
        select first_names||' '||last_name as full_name from cc_users where user_id in ($in_clause)
"

# Determine address mode for addressees to be added.

db_1row get_mode_desc "
        select mode_desc from im_address_mode where mode_id = :address_mode
"

if { [string is false $confirm_p] } {
    set num_entries [llength $selected_addressees]

    if { $num_entries == 0 } {
        ad_returnredirect "add-remove-addressees"
        return
    }

    set title "Confirm Addressees [ad_decode $num_entries 1 "Entry" "Entries"]"
    set context [list $title]
    set yes_url "confirm-addressee?[export_vars { selected_addressees:multiple { confirm_p 1 } {message_id} {address_mode} }]"
    set no_url "./complex-search?message_id=$message_id&target=confirm-addressee"

    return
}

foreach selected_addressee $selected_addressees {
    db_0or1row insert_addressee {
        select im_addressee__insert (:message_id, :selected_addressee, :address_mode, :user_id)
    }
}

ad_returnredirect "message-display?message_id=$message_id"
ad_script_abort
