/**
 * TODO: too much code in churchresource_updateBooking, split it up
 * FIXME: the changes for using email template are breaking logging in case no email is send
 * otherwise logging of complete mails dont seems useful => only log important things in a short text?
 *
 * @param array $params
 * @return multitype:multitype:unknown
 */
function churchresource_updateBooking($params, $sendEMails = true)
{
    global $base_url, $user;
    $oldBooking = getBooking($params["id"]);
    $bUser = churchcore_getPersonById($oldBooking->person_id);
    $ressources = churchcore_getTableData("cr_resource", "resourcetype_id,sortkey,bezeichnung");
    $i = new CTInterface();
    $i->setParam("resource_id");
    $i->setParam("status_id");
    $i->addTypicalDateFields();
    $i->setParam("text", false);
    $i->setParam("location", false);
    $i->setParam("note", false);
    if (empty($params["text"])) {
        $res = db_query('SELECT text FROM {cr_booking}
                     WHERE id=:id', array(":id" => $params["id"]))->fetch();
        $params["text"] = $res->text;
    }
    $i->setParam("person_id", false);
    $id = db_update("cr_booking")->fields($i->getDBInsertArrayFromParams($params))->condition("id", $params["id"], "=")->execute(false);
    $changes = null;
    $exceptions = churchcore_getTableData("cr_exception", null, "booking_id=" . $params["id"]);
    // look which exceptions are already saved in DB.
    if (isset($params["exceptions"])) {
        foreach ($params["exceptions"] as $exception) {
            $current_exc = null;
            // It is not possible to search exceptions by id, because ChurchCal Exc have other IDs
            if ($exceptions) {
                foreach ($exceptions as $e) {
                    if (churchcore_isSameDay($e->except_date_start, $exception["except_date_start"]) && churchcore_isSameDay($e->except_date_end, $exception["except_date_end"])) {
                        $current_exc = $e;
                    }
                }
            }
            if ($current_exc) {
                $exceptions[$current_exc->id]->exists = true;
            } else {
                $changes["add_exception"][] = $exception;
            }
        }
    }
    // delete removed exceptions from DB.
    if ($exceptions) {
        foreach ($exceptions as $e) {
            if (!isset($e->exists)) {
                $changes["del_exception"][] = (array) $e;
            }
        }
    }
    // get all additions
    $additions = churchcore_getTableData("cr_addition", null, "booking_id=" . $params["id"]);
    // look which additions are already saved in DB.
    if (isset($params["additions"])) {
        foreach ($params["additions"] as $addition) {
            $current_add = null;
            // It is not possible to search additions by id, because ChurchCal adds have other IDs
            if ($additions) {
                foreach ($additions as $a) {
                    if (churchcore_isSameDay($a->add_date, $addition["add_date"]) && $a->with_repeat_yn == $addition["with_repeat_yn"]) {
                        $current_add = $a;
                    }
                }
            }
            if ($current_add) {
                $additions[$current_add->id]->exists = true;
            } else {
                $changes["add_addition"][] = $addition;
            }
        }
    }
    // delete removed additions from DB.
    if ($additions) {
        foreach ($additions as $a) {
            // churchresource_delAddition($a->id);
            if (!isset($a->exists)) {
                $changes["del_addition"][] = (array) $a;
            }
        }
    }
    // save new exceptions
    $res_exceptions = array();
    $res_additions = array();
    $days = array();
    $resources = churchcore_getTableData("cr_resource");
    //TODO: only get needed resource_id
    if ($changes) {
        if (isset($changes["add_exception"])) {
            foreach ($changes["add_exception"] as $exc) {
                // Check, if exception not alreay in DB (only possible when coming from Cal)
                $db = db_query("SELECT id FROM {cr_exception}\n                        WHERE booking_id=:booking_id AND except_date_start=:start", array(":booking_id" => $params["id"], ":start" => $exc["except_date_start"]))->fetch();
                if (!$db) {
                    $id = addException($params["id"], $exc["except_date_start"], $exc["except_date_end"], $user->id);
                    if (isset($exc["id"])) {
                        $res_exceptions[$exc["id"]] = $id;
                    }
                    $days[] = $exc["except_date_start"];
                }
            }
            if ($sendEMails && getConf("churchresource_send_emails", true) && count($days) && $bUser) {
                $data = array('canceled' => true, 'surname' => $bUser->vorname, 'name' => $bUser->name, 'nickname' => $bUser->spitzname ? $bUser->spitzname : $bUser->vorname, 'user' => $user, 'resource' => $resources[$params["resource_id"]]->bezeichnung, 'booking' => $booking, 'days' => implode(", ", $days), 'person' => $bUser, 'contact' => getConf('site_mail'));
                $lang = getUserLanguage($oldBooking->person_id);
                $content = getTemplateContent('email/bookingRequest', 'churchresource', $data, null, $lang);
                churchresource_send_mail("[" . getConf('site_name') . "] " . t2($lang, 'updated.booking.request') . ": " . $params["text"], $content, $bUser->email);
            }
        }
        if (isset($changes["del_exception"])) {
            foreach ($changes["del_exception"] as $exc) {
                $db = db_query("SELECT id FROM {cr_exception}\n                        WHERE booking_id=:booking_id AND except_date_start=:start", array(":booking_id" => $params["id"], ":start" => $exc["except_date_start"]))->fetch();
                if ($db) {
                    churchresource_delException(array("id" => $db->id));
                }
            }
        }
        if (isset($changes["add_addition"])) {
            foreach ($changes["add_addition"] as $add) {
                $db = db_query("SELECT id FROM {cr_addition}\n                      WHERE booking_id=:booking_id AND add_date=:date", array(":booking_id" => $params["id"], ":date" => $add["add_date"]))->fetch();
                if (!$db) {
                    $id = addAddition($params["id"], $add["add_date"], $add["with_repeat_yn"], $user->id);
                    if (isset($add["id"])) {
                        $res_additions[$add["id"]] = $id;
                    }
                }
            }
        }
        if (isset($changes["del_addition"])) {
            foreach ($changes["del_addition"] as $add) {
                $db = db_query("SELECT id FROM {cr_addition}\n                      WHERE booking_id=:booking_id AND add_date=:date", array(":booking_id" => $params["id"], ":date" => $add["add_date"]))->fetch();
                if ($db != false) {
                    churchresource_delAddition($db->id);
                }
            }
        }
    }
    // FIXME: check logic for correct function; i am not sure what should happen exactly in which cases
    // TODO: maybe use $params as data and add further values
    $booking = getBooking($params["id"]);
    $changedFields = churchcore_getFieldChanges(getBookingFields(), $oldBooking, $booking, false);
    $data = array('enddate' => churchcore_stringToDateDe($params["enddate"]), 'startdate' => churchcore_stringToDateDe($params["startdate"]), 'resource' => $resources[$params["resource_id"]]->bezeichnung, 'changes' => str_replace("\n", "<br>", $changedFields), 'booking' => $booking, 'bookingUrl' => $base_url . "?q=churchresource&id=" . $params["id"], 'text' => $params['text'], 'note' => isset($params['location']) ? $params['location'] : "", 'pending' => $params["status_id"] == CR_PENDING, 'approved' => $params["status_id"] == CR_APPROVED && ($oldBooking->status_id != CR_APPROVED || $changedFields != null), 'canceled' => $params["status_id"] == CR_CANCELED, 'deleted' => $params["status_id"] == CR_DELETED, 'contact' => getConf('site_mail'));
    $logInfo = ' :: ' . t('bookingX.for.resource.on.datetime', $params["text"], $resources[$params["resource_id"]]->bezeichnung, $params["startdate"], isset($params['location']) ? $params['location'] : "");
    $subject = t('booking.request.updated');
    if ($data['pending']) {
        $logInfo = t('booking.updated') . $logInfo;
    } elseif ($data['approved']) {
        $logInfo = t('booking.approved') . $logInfo;
    } elseif ($data['canceled']) {
        $logInfo = t('booking.canceled') . $logInfo;
    } elseif ($data['deleted']) {
        $logInfo = t('booking.deleted') . $logInfo;
    }
    if ($sendEMails && getConf("churchresource_send_emails", true)) {
        if (($params["status_id"] != $oldBooking->status_id || $changedFields != null) && $bUser) {
            $adminmails = explode(",", $resources[$params["resource_id"]]->admin_person_ids);
            // if current user is not resource admin OR is not the booking creating user
            if (!in_array($user->id, $adminmails) || $user->id != $bUser->id) {
                $content = getTemplateContent('email/bookingUpdated', 'churchresource', $data);
                churchresource_send_mail("[" . getConf('site_name') . "] {$subject}: " . $params["text"], $content, $bUser->email);
            }
        }
    }
    if ($changedFields) {
        cr_log("UPDATE BOOKING\n" . $logInfo, 3, $booking->id);
    }
    return array("exceptions" => $res_exceptions, "additions" => $res_additions);
}
function churchresource_updateBooking($params, $changes = null)
{
    global $base_url, $user;
    // Only bigchange, when I get repeat_id. Otherwise it is only a time shift.
    $bigchange = isset($params["repeat_id"]);
    $old_arr = getBooking($params["id"]);
    $buser = churchcore_getPersonById($old_arr->person_id);
    $ressources = churchcore_getTableData("cr_resource", "resourcetype_id,sortkey,bezeichnung");
    $i = new CTInterface();
    $i->setParam("resource_id");
    $i->setParam("status_id");
    if ($bigchange) {
        $i->addTypicalDateFields();
        $i->setParam("text");
        $i->setParam("location");
        $i->setParam("note");
    } else {
        $i->setParam("startdate");
        $i->setParam("enddate");
        $res = db_query('select * from {cr_booking} where id=:id', array(":id" => $params["id"]))->fetch();
        $params["text"] = $res->text;
    }
    $i->setParam("person_id");
    $id = db_update("cr_booking")->fields($i->getDBInsertArrayFromParams($params))->condition("id", $params["id"], "=")->execute(false);
    // No changes mean not from Cal, so I have to check changes manuelly
    if (is_null($changes) && $bigchange) {
        // Hole alle Exceptions aus der DB
        $exc = churchcore_getTableData("cr_exception", null, "booking_id=" . $params["id"]);
        // Vergleiche erst mal welche schon in der DB sind oder noch nicht in der DB sind.
        if (isset($params["exceptions"])) {
            foreach ($params["exceptions"] as $exception) {
                $current_exc = null;
                // Look for Exc. This is not possible to make by id, cause ChurchCal Exc have other IDs
                if ($exc != false) {
                    foreach ($exc as $e) {
                        if (churchcore_isSameDay($e->except_date_start, $exception["except_date_start"]) && churchcore_isSameDay($e->except_date_end, $exception["except_date_end"])) {
                            $current_exc = $e;
                        }
                    }
                }
                if ($current_exc != null) {
                    $exc[$current_exc->id]->vorhanden = true;
                } else {
                    $changes["add_exception"][] = $exception;
                }
            }
        }
        // L�sche nun alle, die in der DB sind, aber nicht mehr vorhanden sind.
        if ($exc != false) {
            foreach ($exc as $e) {
                if (!isset($e->vorhanden)) {
                    $changes["del_exception"][] = (array) $e;
                }
            }
        }
        // Hole alle Additions aus der DB
        $add = churchcore_getTableData("cr_addition", null, "booking_id=" . $params["id"]);
        // Vergleiche erst mal welche schon in der DB sind oder noch nicht in der DB sind.
        if (isset($params["additions"])) {
            foreach ($params["additions"] as $addition) {
                $current_add = null;
                // Look for additions. This is not possible to make by id, cause ChurchCal Additions have other IDs
                if ($add != false) {
                    foreach ($add as $a) {
                        if (churchcore_isSameDay($a->add_date, $addition["add_date"]) && $a->with_repeat_yn == $addition["with_repeat_yn"]) {
                            $current_add = $a;
                        }
                    }
                }
                if ($current_add != null) {
                    $add[$current_add->id]->vorhanden = true;
                } else {
                    $changes["add_addition"][] = $addition;
                }
            }
        }
        // L�sche nun alle, die in der DB sind, aber nicht mehr vorhanden sind.
        if ($add != false) {
            foreach ($add as $a) {
                if (!isset($a->vorhanden)) {
                    //churchresource_delAddition($a->id);
                    $changes["del_addition"][] = (array) $a;
                }
            }
        }
    }
    // New Exception-Ids will be saved here
    $res_exceptions = array();
    $res_additions = array();
    $days = array();
    // Now do the changes!
    if ($changes != null) {
        if (isset($changes["add_exception"])) {
            foreach ($changes["add_exception"] as $exc) {
                // Check, if exception not alreay in DB (only when coming from Cal it is possible)
                $db = db_query("select id from {cr_exception} where booking_id=:booking_id and except_date_start=:start", array(":booking_id" => $params["id"], ":start" => $exc["except_date_start"]))->fetch();
                if ($db == false) {
                    $id = addException($params["id"], $exc["except_date_start"], $exc["except_date_end"], $user->id);
                    if (isset($exc["id"])) {
                        $res_exceptions[$exc["id"]] = $id;
                    }
                    $days[] = $exc["except_date_start"];
                }
            }
            if (count($days) > 0 && $buser != null) {
                $txt = "<h3>Hallo " . $buser->vorname . "!</h3><p>Bei Deiner Serien-Buchungsanfrage '" . $params["text"] . "' fuer " . $ressources[$params["resource_id"]]->bezeichnung . " mussten leider von " . $user->vorname . " " . $user->name . " folgende Tage abgelehnt werden: <b>" . implode(", ", $days) . "</b><p>";
                churchresource_send_mail("[" . variable_get('site_name') . "] Aktualisierung der Buchungsanfrage: " . $params["text"], $txt, $buser->email);
            }
        }
        if (isset($changes["del_exception"])) {
            foreach ($changes["del_exception"] as $exc) {
                $db = db_query("select id from {cr_exception} where booking_id=:booking_id and except_date_start=:start", array(":booking_id" => $params["id"], ":start" => $exc["except_date_start"]))->fetch();
                if ($db != false) {
                    churchresource_delException(array("id" => $db->id));
                }
            }
        }
        if (isset($changes["add_addition"])) {
            foreach ($changes["add_addition"] as $add) {
                $db = db_query("select id from {cr_addition} where booking_id=:booking_id and add_date=:date", array(":booking_id" => $params["id"], ":date" => $add["add_date"]))->fetch();
                if ($db == false) {
                    $id = addAddition($params["id"], $add["add_date"], $add["with_repeat_yn"], $user->id);
                    if (isset($add["id"])) {
                        $res_additions[$add["id"]] = $id;
                    }
                }
            }
        }
        if (isset($changes["del_addition"])) {
            foreach ($changes["del_addition"] as $add) {
                $db = db_query("select id from {cr_addition} where booking_id=:booking_id and add_date=:date", array(":booking_id" => $params["id"], ":date" => $add["add_date"]))->fetch();
                if ($db != false) {
                    churchresource_delAddition($db->id);
                }
            }
        }
    }
    $txt = "";
    $info = "'" . $params["text"] . "' fuer " . $ressources[$params["resource_id"]]->bezeichnung . " (" . $params["startdate"] . "h";
    if ($params["location"] != "") {
        $info = $info . " in " . $params["location"];
    }
    $info = $info . ")";
    $arr = getBooking($params["id"]);
    $changes = churchcore_getFieldChanges(getBookingFields(), $old_arr, $arr, false);
    if ($params["status_id"] == 1) {
        $txt = " wurde aktualisiert und wartet auf Genehmigung.";
    } else {
        if ($params["status_id"] == 2 && ($old_arr->status_id != 2 || $changes != null)) {
            $txt = " wurde von {$user->vorname} {$user->name} genehmigt!<p>";
        } else {
            if ($params["status_id"] == 3) {
                $txt = " wurde leider abgelehnt, bitte suche Dir einen anderen Termin.<p>";
            } else {
                if ($params["status_id"] == 99) {
                    $txt = " wurde geloescht, bei Fragen dazu melde Dich bitte bei: " . variable_get('site_mail', 'Gemeinde-Buero unter info@elim-hamburg.de oder 040-2271970') . "<p>";
                }
            }
        }
    }
    if ($txt != "" && $buser != null) {
        $txt = "<h3>Hallo " . $buser->vorname . "!</h3><p>Deine Buchungsanfrage " . $info . $txt;
        if ($changes != null) {
            $txt .= "<p><b>Folgende Anpassung an der Buchung wurden vorgenommen:</b><br/>" . str_replace("\n", "<br>", $changes);
        }
        if ($params["status_id"] < 3) {
            $txt .= '<p><a class="btn" href="' . $base_url . "?q=churchresource&id=" . $params["id"] . '">Zur Buchungsanfrage &raquo;</a>';
        }
        $adminmails = explode(",", $ressources[$params["resource_id"]]->admin_person_ids);
        // Wenn der aktuelle User nicht Admin ist ODER wenn der Benutzer nicht der ist, der die Buchung erstellt hat.
        if (!in_array($user->id, $adminmails) || $user->id != $buser->id) {
            churchresource_send_mail("[" . variable_get('site_name', 'ChurchTools') . "] Aktualisierung der Buchungsanfrage: " . $params["text"], $txt, $buser->email);
        }
    }
    if ($changes != null) {
        cr_log("UPDATE BOOKING\n" . $txt, 3, $arr->id);
    }
    $res = array("exceptions" => $res_exceptions, "additions" => $res_additions);
    return $res;
}