#INCLUDE "modules.bi"

CONST AS STRING ModuleName = "admin"

DIM SHARED AdminVars() AS KeyPair

SUB RegisterAdminVar(VarName AS STRING, VarValue AS STRING)
  RegisterVar(AdminVars(), VarName, VarValue)
END SUB

SUB ClearAdminVars()
  ClearVars(AdminVars())
END SUB

SUB LoadAdminPanel()
  'Is the user logged in?
  IF IsAuth() THEN
    DIM AS STRING Section, Action, LastError, ArrayValues()
    Section = ValidateChar(GetURLParam("section", 2))
    IF Section <> "" THEN
      SELECT CASE Section
        CASE "pages"
          DIM sSQL AS STRING, PageDST AS DataSet
          IF VALINT(ReadUserData("user_group")) = ADMIN_GROUP THEN
            DIM AS STRING PageList, PageName, FileName
            Action = ValidateChar(GetURLParam("action", 3))
            IF Action <> "" THEN
              SELECT CASE Action
                CASE "edit"
                  PageName = ValidateChar(GetURLParam("pagename", 4))
                  IF PageName <> "" THEN
                    IF NOT LoadPage(PageName, -1) THEN
                      LastError = Language("error_page_not_exists")
                    END IF
                  END IF
                  SiteTitle = Language("module_admin_pages_editor")
                  RegisterAdminVar("error_message", LastError)
                  SiteContent = ReadTplSnippet("pages-editor")
                CASE "delete"
                  PageName = ValidateChar(GetURLParam("pagename", 4))
                  IF PageName <> "" THEN
                    IF LoadPage(PageName, -1) THEN
                      SiteTitle = Language("module_admin_pages_delete")
                      SiteContent = ReadTplSnippet("pages-delete")
                      IF CLNG(Post("page-delete")) AND ValidateSession(Post("session_token")) THEN
                        sSQL = "DELETE FROM [pages] WHERE [name] = @PageName;"
                        AddParam("@PageName", PageName, PARAM_TYPE_TEXT)
                        ExecuteSql(sSQL)
                        ClearParams()
                        RegisterAdminVar("error_message", Language("success_page_deleted"))
                        SiteContent = ReadTplSnippet("pages-deleted")
                      END IF
                    END IF
                  END IF
                CASE "save"
                  SiteTitle = Language("module_admin_pages_editor")
                  PageName = ValidateChar(Post("page-name"))
                  IF PageName = "" THEN
                    'Page name field empty
                    IF Post("page-title") <> "" THEN
                      'Create a new page name based on the title
                      PageName = CreatePermalink(Post("page-title"))
                    ELSE
                      'We cannot create a page without a name, fail the attempt
                      LastError = Language("error_page_name_undefined")
                      RegisterAdminVar("error_message", LastError)
                      SiteContent = ReadTplSnippet("pages-editor")
                    END IF
                  END IF
                  IF PageName <> "" AND ValidateSession(Post("session_token")) THEN
                    'Hopefully we have a page name now
                    DIM objPage AS JSON_Object, DateFormat AS STRING, PageStatus AS STRING
                    IF LoadPage(PageName, -1) THEN
                      'Edititng an existing page
                      sSQL = "UPDATE [pages] SET [published] = @PagePublished, [content] = @PageContent WHERE [name] = @PageName;"
                    ELSE
                      'Creating a new page
                      sSQL = "INSERT INTO [pages] ([name], [published], [content]) VALUES (@PageName, @PagePublished, @PageContent);"
                    END IF
                    AddParam("@PageName", PageName, PARAM_TYPE_TEXT)
                    PageStatus = Post("page-status")
                    IF PageStatus = "" THEN
                      PageStatus = "0"
                    END IF
                    AddParam("@PagePublished", PageStatus, PARAM_TYPE_INTEGER)
                    JSON_FillObject(objPage, "page_title", JSON_GenerateString(Post("page-title")))
                    DateFormat = Post("page-created-date")
                    IF IsDateFormat(DateFormat) THEN
                      JSON_FillObject(objPage, "page_created_date", JSON_GenerateString(DateFormat))
                    ELSE
                      JSON_FillObject(objPage, "page_created_date", JSON_GenerateString(SystemDate() + "T" + SystemTime()))
                    END IF
                    DateFormat = Post("page-lastmod-date")
                    IF IsDateFormat(DateFormat) THEN
                      JSON_FillObject(objPage, "page_lastmod_date", JSON_GenerateString(DateFormat))
                    ELSE
                      JSON_FillObject(objPage, "page_lastmod_date", JSON_GenerateString(SystemDate() + "T" + SystemTime()))
                    END IF
                    IF JSON_GetType(Post("page-encode-content")) = JSON_TYPE_BOOLEAN THEN
                      JSON_FillObject(objPage, "page_encode_content", Post("page-encode-content"))
                    ELSE
                      JSON_FillObject(objPage, "page_encode_content", "false")
                    END IF
                    IF CBOOL(Post("page-encode-content")) THEN
                      JSON_FillObject(objPage, "page_content", JSON_GenerateString(HTMLEncode(Post("page-content"))))
                    ELSE
                      JSON_FillObject(objPage, "page_content", JSON_GenerateString(Post("page-content")))
                    END IF
                    AddParam("@PageContent", objPage.RawContent, PARAM_TYPE_TEXT)
                    ExecuteSql(sSQL)
                    ClearParams()
                    IF LoadPage(PageName, -1) THEN
                      RegisterAdminVar("error_message", Language("success_page_saved"))
                      SiteContent = ReadTplSnippet("pages-saved")
                    END IF
                  END IF
                CASE "preview"
                  PageName = ValidateChar(GetURLParam("pagename", 4))
                  IF PageName <> "" AND LoadPage(PageName) THEN
                    SiteTitle = Language("module_admin_pages_view")
                    SiteContent = ReadTplSnippet("page")
                  END IF
                CASE "page"
                  DIM CurPage AS LONG = VALINT(GetURLParam("page", 4))
                  SiteTitle = Language("module_admin_page_list")
                  ListPages("pages-list-body", -1, CurPage)
                  SiteTitle = Language("module_admin_page_list")
                  SiteContent = ReadTplSnippet("pages-list")
              END SELECT
            ELSE
              SiteTitle = Language("module_admin_page_list")
              ListPages("pages-list-body", -1)
              SiteTitle = Language("module_admin_page_list")
              SiteContent = ReadTplSnippet("pages-list")
            END IF
          ELSE
            SiteContent = "403"
          END IF
        CASE "settings"
          IF VALINT(ReadUserData("user_group")) = ADMIN_GROUP THEN
            Action = ValidateChar(GetURLParam("action", 3))
            IF Action <> "" THEN
              SELECT CASE Action
                CASE "edit"
                  SiteTitle = Language("module_admin_settings_editor")
                  SiteContent = ReadTplSnippet("settings-editor")
                  IF ValidateSession(Post("session_token")) THEN
                    DIM objSettings AS JSON_Object
                    JSON_FillObject(objSettings, "site_title", JSON_GenerateString(Post("site_title")))
                    JSON_FillObject(objSettings, "site_description", JSON_GenerateString(Post("site_description")))
                    JSON_FillObject(objSettings, "site_keywords", JSON_GenerateString(""))
                    SELECT CASE Post("site_protocol")
                      CASE "http://", "https://"
                        JSON_FillObject(objSettings, "site_protocol", JSON_GenerateString(Post("site_protocol")))
                      CASE ELSE
                        'Default protocol is http://
                        JSON_FillObject(objSettings, "site_protocol", JSON_GenerateString("http://"))
                    END SELECT
                    JSON_FillObject(objSettings, "site_domain", JSON_GenerateString(Post("site_domain")))
                    JSON_FillObject(objSettings, "site_url", JSON_GenerateString(Post("site_url")))
                    JSON_FillObject(objSettings, "site_admin", JSON_GenerateString(Post("site_admin")))
                    JSON_FillObject(objSettings, "site_email", JSON_GenerateString(Post("site_email")))
                    JSON_FillObject(objSettings, "site_encoding", JSON_GenerateString(Post("site_encoding")))
                    JSON_FillObject(objSettings, "site_template", JSON_GenerateString(Post("site_template")))
                    JSON_FillObject(objSettings, "site_language", JSON_GenerateString(Post("site_language")))
                    IF JSON_GetType(Post("site_timezone")) = JSON_TYPE_NUMERIC THEN
                      JSON_FillObject(objSettings, "site_timezone", Post("site_timezone"))
                    ELSE
                      JSON_FillObject(objSettings, "site_timezone", "0")
                    END IF
                    JSON_FillObject(objSettings, "site_index_type", JSON_GenerateString(Post("site_index_type")))
                    JSON_FillObject(objSettings, "site_index_page", JSON_GenerateString(Post("site_index_page")))
                    JSON_FillObject(objSettings, "site_index_module", JSON_GenerateString(Post("site_index_module")))
                    IF JSON_GetType(Post("site_fancy_url")) = JSON_TYPE_BOOLEAN THEN
                      JSON_FillObject(objSettings, "site_fancy_url", Post("site_fancy_url"))
                    ELSE
                      JSON_FillObject(objSettings, "site_fancy_url", "false")
                    END IF
                    JSON_FillObject(objSettings, "site_fancy_url_extension", JSON_GenerateString(Post("site_fancy_url_extension")))
                    JSON_FillObject(objSettings, "site_data_base", JSON_GenerateString(Post("site_data_base")))
                    JSON_FillObject(objSettings, "site_cache_mode", JSON_GenerateString(Post("site_cache_mode")))
                    JSON_FillObject(objSettings, "site_uploads_path", JSON_GenerateString(Post("site_uploads_path")))
                    JSON_FillObject(objSettings, "site_smtp_server", JSON_GenerateString(Post("site_smtp_server")))
                    'Save new settings on disk
                    WriteFile(DataPath + "settings.json", objSettings.RawContent)
                    LoadSettings()
                    LastError = Language("success_settings_saved")
                  END IF
                  RegisterAdminVar("error_message", LastError)
                  SiteContent = ReadTplSnippet("settings-editor")
              END SELECT
            ELSE
              SiteTitle = Language("module_admin_settings")
              SiteContent = ReadTplSnippet("settings-display")
            END IF
          ELSE
            SiteContent = "403"
          END IF
        CASE "templates"
          IF VALINT(ReadUserData("user_group")) = ADMIN_GROUP THEN
            DIM AS STRING TplPath, TplList, TplName, ListBody
            TplPath = DataPath + "templates" + PATH_DELIMITER
            TplName = ValidateChar(GetURLParam("template", 3))
            IF TplName <> "" THEN
              DIM AS STRING ModList, ModName
              ModName = ValidateChar(GetURLParam("modulename", 4))
              IF ModName <> "" THEN
                DIM objSnippets AS JSON_Object, ArrayTmpSnippets() AS JSON_Member
                DIM AS STRING SecName, SecList, FilePath
                DIM AS JSON_Member NewSnippet, EditedSnippet
                'Load template snippets
                IF ModName <> "main" THEN
                  FilePath = TplPath + TplName + PATH_DELIMITER + "modules" + PATH_DELIMITER + ModName + ".json"
                ELSE
                  FilePath = TplPath + TplName + PATH_DELIMITER + ModName + ".json"
                END IF
                objSnippets.RawContent = ReadFile(FilePath)
                IF objSnippets.RawContent <> "" THEN
                  JSON_CountMembers(objSnippets)
                END IF
                IF objSnippets.MemberCount THEN
                  REDIM ArrayTmpSnippets(objSnippets.MemberCount - 1)
                  JSON_ParseObject(objSnippets, ArrayTmpSnippets())
                END IF
                SecName = ValidateChar(GetURLParam("snippet", 5))
                IF SecName <> "" THEN
                  IF UBOUND(ArrayTmpSnippets) >= 0 THEN
                    SiteTitle = Language("module_admin_snippet_editor")
                    IF Post("snippet-content") <> "" AND ValidateSession(Post("session_token")) THEN
                      WITH EditedSnippet
                        .Name = SecName
                        .Value.RawContent = JSON_GenerateString(Post("snippet-content"))
                        .Value.ValueType = JSON_GetType(.Value.RawContent)
                      END WITH
                      JSON_UpdateMember(objSnippets, EditedSnippet)
                      WriteFile(FilePath, objSnippets.RawContent)
                      JSON_ParseObject(objSnippets, ArrayTmpSnippets())
                      LastError = Language("success_snippet_edited")
                    END IF
                    FOR i AS ULONG = 0 TO UBOUND(ArrayTmpSnippets)
                      WITH ArrayTmpSnippets(i)
                        IF .Name = SecName THEN
                          RegisterAdminVar("snippet_content", HTMLEncode(JSON_ParseString(.Value.RawContent)))
                          EXIT FOR
                        END IF
                      END WITH
                    NEXT
                    RegisterURLVar("templatename", TplName)
                    RegisterURLVar("modulename", ModName)
                    RegisterURLVar("snippetname", SecName)
                    RegisterAdminVar("template_name", TplName)
                    RegisterAdminVar("module_name", ModName)
                    RegisterAdminVar("snippet_name", SecName)
                    RegisterAdminVar("error_message", LastError)
                    SiteContent = ReadTplSnippet("template-snippet-editor")
                  END IF
                ELSE
                  'Show Snippet List
                  DIM IsRepeated AS LONG
                  SiteTitle = Language("module_admin_snippet_list")
                  'Let's check if the snippet name is already in use
                  IF Post("snippet-name") <> "" THEN
                    IF UBOUND(ArrayTmpSnippets) >= 0 THEN 
                      FOR i AS ULONG = 0 TO UBOUND(ArrayTmpSnippets)
                        IF Post("snippet-name") = ArrayTmpSnippets(i).Name THEN
                          IsRepeated = -1
                          EXIT FOR
                        END IF
                      NEXT
                    END IF
                    IF NOT IsRepeated THEN
                      WITH NewSnippet
                        .Name = Post("snippet-name")
                        .Value.RawContent = JSON_GenerateString("")
                        .Value.ValueType = JSON_GetType(.Value.RawContent)
                      END WITH
                      JSON_AddMember(objSnippets, NewSnippet, objSnippets.MemberCount)
                      WriteFile(FilePath, objSnippets.RawContent)
                      REDIM ArrayTmpSnippets(objSnippets.MemberCount)
                      JSON_ParseObject(objSnippets, ArrayTmpSnippets())
                      LastError = Language("success_snippet_added")
                    ELSE
                      LastError = Language("error_snippet_name_repeated")
                    END IF
                  END IF
                  IF UBOUND(ArrayTmpSnippets) >= 0 THEN
                    FOR i AS ULONG = 0 TO UBOUND(ArrayTmpSnippets)
                      WITH ArrayTmpSnippets(i)
                        SecName = JSON_ParseString(.Name)
                        RegisterURLVar("templatename", TplName)
                        RegisterURLVar("modulename", ModName)
                        RegisterURLVar("snippetname", SecName)
                        RegisterAdminVar("snippet_name", SecName)
                        ListBody = ReadTplSnippet("template-snippet-list-body")
                        SecList += ListBody
                        ClearAdminVars()
                        ClearURLVars()
                      END WITH
                    NEXT
                  END IF
                  RegisterURLVar("templatename", TplName)
                  RegisterURLVar("modulename", ModName)
                  RegisterAdminVar("template_name", TplName)
                  RegisterAdminVar("module_name", ModName)
                  RegisterAdminVar("snippet_list", SecList)
                  RegisterAdminVar("error_message", LastError)
                  SiteContent = ReadTplSnippet("template-snippet-list")
                END IF
              ELSE
                'Show Module List
                SiteTitle = Language("module_admin_module_list")
                'Main module is always at template root and is called main.json
                ModName = "main"
                RegisterURLVar("templatename", TplName)
                RegisterURLVar("modulename", ModName)
                RegisterAdminVar("template_module_name", PATH_DELIMITER + ModName)
                ListBody = ReadTplSnippet("template-module-list-body")
                ModList = ListBody
                ClearAdminVars()
                ClearURLVars()
                'Get registered modules
                DIM ModuleCount AS LONG, CompiledModules() AS IguanaModule
                ListCompiledModules(CompiledModules())
                ModuleCount = UBOUND(CompiledModules)
                IF ModuleCount >= 0 THEN
                  FOR i AS LONG = 0 TO ModuleCount
                    'Every module must have his own template file
                    ModName = CompiledModules(i).Name
                    IF FileExists(TplPath + TplName + PATH_DELIMITER + "modules" + PATH_DELIMITER + ModName + ".json") THEN
                      RegisterURLVar("templatename", TplName)
                      RegisterURLVar("modulename", ModName)
                      RegisterAdminVar("template_module_name", PATH_DELIMITER + "modules" + PATH_DELIMITER + ModName)
                      ListBody = ReadTplSnippet("template-module-list-body")
                      ModList += ListBody
                      ClearAdminVars()
                      ClearURLVars()
                    END IF
                  NEXT
                END IF
                RegisterAdminVar("template_name", TplName)
                RegisterAdminVar("template_module_list", ModList)
                SiteContent = ReadTplSnippet("template-module-list")
              END IF
            ELSE
              'Show Template List
              SiteTitle = Language("module_admin_templates_list")
              TplName = DIR(TplPath + "*", 16)
              IF TplName <> "" THEN
                DO WHILE TplName <> ""
                  IF TplName <> "." AND TplName <> ".." THEN
                    RegisterAdminVar("template_name", TplName)
                    RegisterUrlVar("templatename", TplName)
                    ListBody = ReadTplSnippet("template-list-body")
                    TplList += ListBody + LINE_ENDING
                    ClearAdminVars()
                    ClearURLVars()
                  END IF
                  TplName = DIR()
                LOOP
              END IF
              RegisterAdminVar("template_list", TplList)
              SiteContent = ReadTplSnippet("template-list")
            END IF
          ELSE
            SiteContent = "403"
          END IF
        CASE "languages"
          IF VALINT(ReadUserData("user_group")) = ADMIN_GROUP THEN
          ELSE
            SiteContent = "403"
          END IF
        CASE "menus"
          IF VALINT(ReadUserData("user_group")) = ADMIN_GROUP THEN
          ELSE
            SiteContent = "403"
          END IF
        CASE "captcha"
          IF VALINT(ReadUserData("user_group")) = ADMIN_GROUP THEN
          ELSE
            SiteContent = "403"
          END IF
        CASE "bbcodes"
          IF VALINT(ReadUserData("user_group")) = ADMIN_GROUP THEN
          ELSE
            SiteContent = "403"
          END IF
        CASE "modules"
          DIM ModuleRequest AS STRING = ValidateChar(GetURLParam("modulename", 3))
          IF ModuleRequest <> "" THEN
            LoadAdminModule(ModuleRequest)
          ELSE
            DIM CompiledModules() AS IguanaModule
            DIM AS STRING ModName, ModList
            DIM AS LONG ModuleCount
            'Get registered modules
            ListCompiledModules(CompiledModules())
            ModuleCount = UBOUND(CompiledModules)
            IF ModuleCount >= 0 THEN
              FOR i AS LONG = 0 TO ModuleCount
                IF CompiledModules(i).ListedForAdmin THEN
                  ModName = LCASE(CompiledModules(i).Name)
                  LoadLanguage(ModName)
                  RegisterURLVar("modulename", ModName)
                  RegisterAdminVar("module_name", Language("module_" + ModName + "_module_title"))
                  ModList += ReadTplSnippet("module-list-body")
                  ClearAdminVars()
                  ClearURLVars()
                END IF
              NEXT
            ELSE
              LastError = Language("error_module_list_empty")
            END IF
            RegisterAdminVar("module_list", ModList)
            RegisterAdminVar("error_message", LastError)
            SiteTitle = Language("module_admin_module_list")
            SiteContent = ReadTplSnippet("module-list")
          END IF
      END SELECT
    ELSE
      SiteTitle = Language("module_admin_control_panel")
      SiteContent = ReadTplSnippet("panel")
    END IF
  ELSE
    SiteContent = "403"
  END IF
END SUB

FUNCTION AdminParser(Key AS STRING) AS STRING
  DIM Result AS STRING = GetVarValue(AdminVars(), Key)
  AdminParser = Result
END FUNCTION

DIM CurrentModule AS IguanaModule

WITH CurrentModule
  .Name = ModuleName
  .ListedForAdmin = 0
  .HasOwnTemplate = -1
  .MainLoader = CINT(ProcPtr(LoadAdminPanel))
  .VarsFunction = CINT(ProcPtr(AdminParser))
END WITH

RegisterModule(CurrentModule)
