<?php

foreach ($safeRequest as $key => $value) {// import the filtered request variables
    ${$key} = addslashes($value);
}
$sefAdmin = new sef();
if (!$system->checkTables($usection)) { // check if all tables needed for this section exist!
    //unset($action);
    unset($submitedData); // do nothing and inform for the error
    $messages->errorMessages = array();
    $messages->addError(t("Σφάλμα συστήματος! Ο έλεγχος των πινάκων απέτυχε"));
} else {

    $alangID = $language->getDefaultLanguage();
    $langExt = $language->getLanguageExtension($alangID);
    $tableSectionID = $system->getTableSectionID($usection);
    $itemID = (int)$itemID;
    $itemID = (!empty($itemID)) ? $itemID : null;
    $requiredVars = $variables->getRequiredVars($tableSectionID);
    $usectionTitle = $system->getTableSectionTitle($tableSectionID);
    $hasAttachments = $system->getSectionProperty($tableSectionID, "hasAttachments");
    $isMultilingualSite = $language->isMultilingualSite();
    if ($itemID) {
        $usectionRows = $db->getNumRows("select * from `$usection` where id='$itemID'");
        if (!$usectionRows) {
            $messages->addError(t("Η εγγραφή δεν βρέθηκε") . "!");
            $action = "form";
            unset($itemID);
        }
    }
    $fieldsRows = $db->getNumRows("select * from `fields` where tableSectionID='$tableSectionID' and active=1 order by sort");
    if (!$fieldsRows) $messages->addError(t("Δεν βρέθηκαν ενεργά πεδία σε αυτή την ενότητα") . "!");
    if (!$system->isDefaultTitleExists($system->getTableSectionID($usection))) $messages->addError(t("Θα πρέπει να καταχωρήσετε ένα πεδίο [Κύριος τλιτλος (title)] πριν αρχίσετε να χρησιμοποιείτε αυτή την ενότητα"));

    $vars = $variables->getVarNamesByLanguage($tableSectionID, 0); // get non Multilingual var names of request
    $Lvars = $variables->getVarNamesByLanguage($tableSectionID, 1); // get non Multilingual var names of request
    $content_table = "content_" . $usection;
    $vars = (is_array($vars)) ? $vars : array();
    $Lvars = (is_array($Lvars)) ? $Lvars : array();
    if ($requiredVars) {
        foreach ($requiredVars as $row) {
            $varName = ($row->isMultilingual) ? $row->fieldVarName . $language->getLanguageExtension($alangID) : $row->fieldVarName;
            if (!${$varName}) $messages->addError(t("Το πεδίο [") . " " . t($row->fieldDescription) . " " . t("] πρέπει να συμπληρωθεί"));
        }
    }
    if (!$_REQUEST['title_gr']) $messages->addError(t("Δεν μπορεί να καταχωρηθεί μια εγγραφή χωρίς κύριο τίτλο") . "!");
    if (isset($_REQUEST['delete'])) $messages->hasErrors = NULL;

    if (!$itemID) { // check limits in add mode
        $q = "select $usection.id as id  from " . $usection . ", content_" . $usection . " where " . $usection . ".userID='$userID' and " . $usection . ".id=content_" . $usection . ".mainID and content_" . $usection . ".langID=" . $langID;
        $orio = $content->getValue('users_types', 3, 'orio', $langID);
        $records = $db->getRecords($q);
        $numOfRecords = count($records);
        $orio = (int)$orio;
        if ($numOfRecords == $orio) {
            $messages->addError(t("Έχετε συμπληρώσει το όριο των καταχωρήσεων που δικαιούστε") . "!");
        }
    }

    if ($itemID) {
        // edit mode
        if (!$content->recordExists($itemID, $usection)) $messages->addError(t("Η εγγραφή δεν βρέθηκε"));
        if (!$messages->hasErrors) {
            // no errors proceed to edit/delete
            if (isset($_REQUEST['delete'])) {
                // delete
                $content->removeContent($itemID, $usection);
                $messages->addMessage(t("Η διαγραφή ολοκληρώθηκε με επιτυχία"));
            } else { // edit

                // first of all remove all existing tags for this record
                $content->removeTags($tableSectionID, $itemID);
                // We 'll add any tags defined in the language section below...

                // first of all remove all existing seo info for this record
                $content->removeSEOTags($tableSectionID, $itemID);
                // We 'll add any seo info defined in the language section below...

                // check for  dates or selectLists
                $fields = $db->getRecords("select * from `fields` where tableSectionID='$tableSectionID' and active=1 order by sort");
                foreach ($fields as $field) { // check every field
                    if (isset($_REQUEST[$field->fieldVarName])) $thisVar = $_REQUEST[$field->fieldVarName];
                    if ($field->fieldType == "date" && $thisVar) { // convert date to timestamp before storing in database
                        $givenDate = $thisVar;
                        ${$field->fieldVarName} = $dates->makeTimestamp($givenDate);
                    }
                    if ($field->fieldType == "selectList") { // store the multiple values to `selectlists` mysql table and turn to zero the value of the field
                        $howManyOptions = count($thisVar);
                        if ($howManyOptions || $_REQUEST['forceDeleteOptions']) {
                            $selectedOptions = $thisVar; // reference to the array
                            $usectionID = $tableSectionID;
                            $fieldID = $field->id;
                            $db->query("delete from `selectlists` where itemID='$itemID' and sectionID='$usectionID' and fieldID='$fieldID' "); // delete any old values
                            foreach ($selectedOptions as $optionID) {
                                $db->query(("INSERT INTO `selectlists` VALUES('', $usectionID, $fieldID, $itemID, $optionID)"));
                            }
                        }
                    }
                    if ($field->fieldType == "decimal") ${$field->fieldVarName} = str_replace(",", ".", ${$field->fieldVarName}); // fix decimal digits seperator
                }
                $alias = $variables->toLatin($_REQUEST['title' . $langExt]);
                $basicAlias = $alias;
                $active = (!empty($_REQUEST['active'])) ? (int)$_REQUEST['active'] : 0;
                $private = 1;
                $values = "SET  `active`='" . $active . "', `private`='" . $private . "', `alias`='" . $alias . "', ";
                if ($system->getSectionProperty($tableSectionID, 'hasGoogleMaps')) {
                    $lat = (!empty($lat)) ? $lat : null;
                    $lng = (!empty($lng)) ? $lng : null;
                    $zoom = (!empty($zoom)) ? $zoom : null;
                    $values .= "`lat`='" . $lat . "',  `lng`='" . $lng . "',  `zoom`='" . $zoom . "', ";
                }
                if (count($vars)) {
                    foreach ($vars as $var) {
                        ${$var} = (isset(${$var})) ? ${$var} : null;
                        $values .= "`" . $var . "`='" . ${$var} . "', ";
                    }
                }
                $values = substr($values, 0, -2);
                $q = "UPDATE `$usection` " . $values . " where id='" . $itemID . "'";
                $db->query($q);
                $Lresult = $db->getRecords("SELECT * FROM languages WHERE active=1 ");

                // update the alias
                $aliasID = $db->getRecord("select id from aliases where  itemID='" . $itemID . "' and isCategory='0' and sectionID='" . $tableSectionID . "'")->id;

                $aliasIndex = null;
                $aliases = $sefAdmin->isAliasExists($basicAlias, $itemID, $tableSectionID);
                while ($aliases) {
                    $aliasIndex = (int)$aliasIndex;
                    $aliasIndex++;
                    $aliasToTest = $basicAlias . "_" . $aliasIndex;
                    $aliases = $sefAdmin->isAliasExists($aliasToTest, $itemID, $tableSectionID);
                }
                $basicAlias = ($aliasToTest) ? $aliasToTest : $basicAlias;
                if ($aliasID) {
                    $aliasFound = true;
                    $values = "SET  `active`='1', `private`='1', `alias`='" . $basicAlias . "', `sectionID`='" . $tableSectionID . "', `itemID`='" . $itemID . "', `isCategory`='0'";
                    $q = "UPDATE `aliases` " . $values . " where id='" . $aliasID . "'";
                    $db->query($q);

                } else { // alias not found, let's create a new one
                    $aliasFound = false;
                    $keys = "`id`, `active`, `private`, `alias`, `sectionID`, `itemID`, `isCategory`";
                    $values = "'', '1', '1', '" . $basicAlias . "', '" . $tableSectionID . "', '" . $itemID . "', '0'";
                    $q = "INSERT INTO aliases (" . $keys . ") VALUES(" . $values . ")";
                    $db->query($q);
                    $aliasID = $db->lastID();
                }
                foreach ($Lresult as $Lrow) {
                    $extension = ($Lrow->extension) ? $Lrow->extension : '_gr';
                    $languageID = $Lrow->id;
                    $foundrecord = $db->getNumRows("select id from content_$usection where langID='$languageID' and mainID='$itemID'");

                    $alias = $variables->toLatin($_REQUEST['title' . $extension]);
                    list($part1, $part2) = explode("_", $basicAlias);
                    if ($part2) $alias = $alias . "_" . $part2;
                    if ($isMultilingualSite) $title_en = empty($title_en) ? $title_gr : $title_en; // make sure there is an english title for multilingual sites
                    if ($foundrecord) {
                        $values = "SET ";
                        foreach ($Lvars as $var) {
                            $values .= "`" . $var . "`='" . ${$var . $extension} . "', ";
                        }
                        $values = substr($values, 0, -2);
                        $q = "UPDATE content_$usection " . $values . " where langID=" . $languageID . " and mainID='" . $itemID . "'";
                        $db->query($q);

                        // first make sure that an alias record exists in this language
                        $exists = $db->getRecord("SELECT langID from `content_aliases` where mainID='" . $aliasID . "' and langID='" . $languageID . "'")->langID;
                        if ($aliasFound && $exists) {
                            // update the multilingual alias
                            $values = "SET `title`='" . $alias . "'";
                            $q = "UPDATE `content_aliases` " . $values . " where mainID='" . $aliasID . "' and langID='" . $languageID . "'";
                            $db->query($q);
                        } else { // need to insert a new alias for this language
                            $keys = "`id`, `mainID`, `langID`, `title`";
                            $values = "'', '" . $aliasID . "', '" . $languageID . "', '" . $alias . "'";
                            $q = "INSERT INTO content_aliases (" . $keys . ") VALUES(" . $values . ")";
                            $db->query($q);
                        }
                        // ----- add the new tags of this language (old tags have been removed)
                        $tags = explode("|||", ${"tags" . $extension});
                        $content->addTags($tags, $tableSectionID, $itemID, $languageID);

                        if ($_REQUEST['enableSEO']) {
                            // ----- add the new SEO tags of this language (old tags have been removed)
                            $title = ${'seo_title' . $extension};
                            $description = ${'seo_description' . $extension};
                            $keywords = ${'seo_keywords' . $extension};
                            $meta = ${'seo_meta' . $extension};
                            $db->query("INSERT INTO `seo` 
							(title, description, keywords, meta, overwrite_title, sectionID, itemID, langID) 
							VALUES 
							('$title', '$description', '$keywords', '$meta', '$overwrite_title', '$tableSectionID', '$itemID', '$languageID')");
                        }

                    } else { // need to insert a new record for this language
                        $keys = "id, mainID, langID";
                        $values = "'', '$itemID', '$languageID'";
                        foreach ($Lvars as $var) {
                            $keys .= ", " . $var;
                            $values .= ",'" . ${$var . $extension} . "'";
                        }
                        $q = "INSERT INTO content_$usection (" . $keys . ") VALUES(" . $values . ")";
                        $db->query($q);

                        // add the alias for this language
                        $keys = "`id`, `mainID`, `langID`, `title`";
                        $values = "'', '" . $aliasID . "', '" . $languageID . "', '" . $alias . "'";
                        $q = "INSERT INTO content_aliases (" . $keys . ") VALUES(" . $values . ")";
                        $db->query($q);

                        // ----- add the new tags of this language (old tags have been removed)
                        $tags = explode("|||", ${"tags" . $extension});
                        $content->addTags($tags, $tableSectionID, $itemID, $languageID);

                        if ($_POST['enableSEO']) {
                            // ----- add the new SEO tags of this language (old tags have been removed)
                            $title = ${'seo_title' . $extension};
                            $description = ${'description' . $extension};
                            $keywords = ${'keywords' . $extension};
                            $meta = ${'meta' . $extension};
                            $db->query("INSERT INTO `seo` 
							(title, description, keywords, meta, overwrite_title, sectionID, itemID, langID) 
							VALUES 
							('$seo_title', '$seo_description', '$seo_keywords', '$seo_meta', '$overwrite_title', '$tableSectionID', '$itemID', '$languageID')");
                        }

                    }
                }
                $messages->addMessage(t("Η επεξεργασία των στοιχείων ολοκληρώθηκε με επιτυχία"));
            }
            // show listing after editing the record
            $_REQUEST['catID'] = 0;
            $_REQUEST['action'] = "list";
            $action = "list";
            $catID = 0;
        } else {
            $_REQUEST['itemID'] = $itemID; // display edit form again
            $_POST['submitedData'] = NULL;
        }
    } else {        //add mode
        if (!$messages->hasErrors) {
            // check for dates or selectLists
            $inserts = array();
            $fields = $db->getRecords("select * from `fields` where tableSectionID='$tableSectionID' and active=1 order by sort");
            foreach ($fields as $field) { // check every field
                $thisVar = (!empty($_REQUEST[$field->fieldVarName])) ? $_REQUEST[$field->fieldVarName] : null;
                if ($field->fieldType == "date" && $thisVar) { // convert date to timestamp before storing in database
                    $givenDate = $thisVar;
                    if ($field->fieldVarName == "eventDate") {
                        $ed = $givenDate;
                    }
                    ${$field->fieldVarName} = $dates->makeTimestamp($givenDate);
                }
                if ($field->fieldType == "selectList") { // store the multiple values to `selectlists` mysql table and turn to zero the value of the field
                    $howManyOptions = count($thisVar);
                    if ($howManyOptions) {
                        $selectedOptions = $thisVar; // reference to the array
                        $usectionID = $tableSectionID;
                        $fieldID = $field->id;
                        foreach ($selectedOptions as $optionID) {
                            $db->query(("INSERT INTO `selectlists` VALUES('', $usectionID, $fieldID, '-1', $optionID)"));
                        }
                    }
                }
                if ($field->fieldType == "decimal") ${$field->fieldVarName} = str_replace(",", ".", ${$field->fieldVarName}); // fix decimal digits seperator
            }
            $keys = "`active`, `private`, `alias`, ";
            if ($system->getSectionProperty($tableSectionID, 'hasGoogleMaps')) {
                $keys .= "`lat`, `lng`, `zoom`, ";
            }
            $alias = $variables->toLatin($_REQUEST['title' . $langExt]);
            $basicAlias = $alias;
            $active = (!empty($_REQUEST['active'])) ? (int)$_REQUEST['active'] : 0;
            $private = 1;
            $values = "'" . $active . "', '" . $private . "', '" . $alias . "', ";
            if ($system->getSectionProperty($tableSectionID, 'hasGoogleMaps')) {
                if (empty($lat) || empty($lng) || empty($zoom)) {
                    $lat = "37.98413";
                    $lng = "23.72808";
                    $zoom = 6;
                    $messages->addMessage(t("Δεν βρέθηκε γεωγραφικός προσδιορισμός και ορίστηκαν οι εξ ορισμού συντεταγμένες"));
                    $messages->addMessage(t("Παρακαλούμε κάντε τις απαραίτητες διορθώσεις αν χρειάζεται"));
                }
                $values .= "'" . $lat . "', '" . $lng . "', '" . $zoom . "', ";
            }
            foreach ($vars as $var) {
                $keys .= "`" . $var . "`, ";
                ${$var} = (isset(${$var})) ? ${$var} : null;
                $values .= "'" . ${$var} . "', ";
            }
            $keys = substr($keys, 0, -2);
            $values = substr($values, 0, -2);
            $q = "INSERT INTO $usection (" . $keys . ") VALUES(" . $values . ")";
            $db->query($q);
            $itemID = $db->lastID();

            // add the alias
            $aliasIndex = null;
            $aliases = $sefAdmin->isAliasExists($basicAlias, $itemID, $tableSectionID);
            while ($aliases) {
                $aliasIndex = (int)$aliasIndex;
                $aliasIndex++;
                $aliasToTest = $basicAlias . "_" . $aliasIndex;
                $aliases = $sefAdmin->isAliasExists($aliasToTest, $itemID, $tableSectionID);
            }
            $basicAlias = ($aliasToTest) ? $aliasToTest : $basicAlias;

            $keys = "`id`, `active`, `private`, `alias`, `sectionID`, `itemID`, `isCategory`";
            $values = "'', '1', '1', '" . $basicAlias . "', '" . $tableSectionID . "', '" . $itemID . "', '0'";
            $q = "INSERT INTO aliases (" . $keys . ") VALUES(" . $values . ")";
            $db->query($q);
            $aliasID = $db->lastID();


            $hasCalendar = (!empty($_REQUEST['calendar']) && !empty($_REQUEST['daysOfEvent']));
            if ($hasCalendar) { // αν εχει οριστει δημοσιευση και στο ημερολογιο
                $lastIDs = array();
                $daysOfEvent = (int)$_REQUEST["daysOfEvent"] ? $_REQUEST["daysOfEvent"] : 1; // για ποσες μερες ισχυει το event
                $startDate = explode("/", $ed);
                $day = $startDate[0];
                $month = $startDate[1];
                $year = $startDate[2];
                for ($i = 0; $i < $daysOfEvent; $i++) {
                    $timestamp = gmmktime(0, 0, 0, $month, $day, $year) + ($i * 86400);
                    $d = getdate($timestamp);
                    $thisday = $d["mday"];
                    $thismonth = $d["mon"];
                    $thisyear = $d["year"];
                    $eventAlias = "event_" . $thisday . "_" . $thismonth . "_" . $thisyear;
                    $active = (int)$_REQUEST['active'];
                    $private = (int)$_REQUEST['private'];
                    $db->query("insert into events values(null, '$active', '$private', '$eventAlias', '0', '$thisday', '$thismonth', '$thisyear')");
                    $lastIDs[$i] = $db->lastID(); // store to array in order to use it later for content_events table (see bellow in multilingual support)
                }
            }
            $Lresult = $db->getRecords("SELECT * FROM languages WHERE active=1 ");
            foreach ($Lresult as $Lrow) {
                $extension = ($Lrow->extension) ? $Lrow->extension : '_gr';
                $languageID = $Lrow->id;
                $keys = "id ,mainID, langID";
                $values = "'', '$itemID', '$languageID'";
                if ($isMultilingualSite) $title_en = empty($title_en) ? $title_gr : $title_en; // make sure there is an english title for multilingual sites
                $foundTitle = false;
                foreach ($Lvars as $var) {
                    $keys .= ", " . $var;
                    $values .= ",'" . ${$var . $extension} . "'";
                    if ($var == "title") $foundTitle = (${$var . $extension} != null);
                }
                $alias = $variables->toLatin($_REQUEST['title' . $extension]);
                list($part1, $part2) = explode("_", $basicAlias);
                if ($part2) $alias = $alias . "_" . $part2;
                if ($foundTitle) { // do not add any empty title language records
                    $q = "INSERT INTO content_$usection (" . $keys . ") VALUES(" . $values . ")";
                    $db->query($q);

                    // add the multilingual alias
                    $keys = "`id`, `mainID`, `langID`, `title`";
                    $values = "'', '" . $aliasID . "', '" . $languageID . "', '" . $alias . "'";
                    $q = "INSERT INTO content_aliases (" . $keys . ") VALUES(" . $values . ")";
                    $db->query($q);

                    if ($hasCalendar) { // αν εχει οριστει δημοσιευση και στο ημερολογιο
                        for ($i = 0; $i < $daysOfEvent; $i++) {
                            $title = ${"title" . $extension};
                            $urlView = ($usection == "pages") ? "render" : "node";
                            $eventCalendarURL = (${"url" . $extension}) ? ${"url" . $extension} : "index.php?section=" . $usection . "&view=" . $urlView . "&id=" . $itemID . "&langID=" . $languageID;
                            $thisID = $lastIDs[$i];
                            $db->query("insert into content_events values(null, '$thisID', '$languageID', '$title', '$eventCalendarURL' )");
                        }
                    }
                }
                // ----- add any given tags of this language
                $tags = explode("|||", ${"tags" . $extension});
                $content->addTags($tags, $tableSectionID, $itemID, $languageID);

                if ($_POST['enableSEO']) {
                    // ----- add the new SEO tags of this language (old tags have been removed)
                    $title = ${'seo_title' . $extension};
                    $description = ${'seo_description' . $extension};
                    $keywords = ${'seo_keywords' . $extension};
                    $meta = ${'seo_meta' . $extension};
                    $db->query("INSERT INTO `seo` 
					(title, description, keywords, meta, overwrite_title, sectionID, itemID, langID) 
					VALUES 
					('$title', '$description', '$keywords', '$meta', '$overwrite_title', '$tableSectionID', '$itemID', '$languageID')");
                }


            }


            // -----update the itemID in selectlists table
            $db->query("update `selectlists` set itemID='$itemID' where itemID='-1' ");
            //-----------------------------------
            $messages->addMessage(t("Η αποθήκευση των στοιχείων ολοκληρώθηκε με επιτυχία"));
            if ($hasAttachments) {
                $messages->addMessage(t("Μπορείτε τώρα να επισυνάψετε εικόνες, αρχεία ή videos"));
                $_REQUEST['itemID'] = $itemID; // display the edit form to attach images or and files...
                $_REQUEST['action'] = "form";
                $action = "form";
            }
        } else {
            $_POST['submitedData'] = NULL;
            $_POST['action'] = $action = NULL;
        }
    }


}// end saving data

if ($messages->hasErrors) {
    $messages->messages = array();
    $messages->printSystemMessages();
}
?>