#|

# Contact Form

GET /contact            Index
GET /contact/admin      Admin Panel
GET /contact/:id        View Submission    TODO

DELETE /contact         Clear All
DELETE /contact/:id     Delete By ID

POST /contact           New Submission

|#

(in-package #:cl-deck-builder2.web)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun render-feedback (&optional (tpl #P"contact/index.html"))
  (render-with-env tpl (append
                        (list :active "/contact")
                        (auth (:admin)
                              (list :feedback (select-feedback))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defroute ("/contact" :method :GET) ()
  "Contact Form Index Page"
  (v:info :contact "GET /contact")

  (with-logged-in-user
    (render-feedback)))

(defroute ("/contact/admin" :method :GET) ()
  "Contact Form Admin Panel"
  (with-logged-in-user
    (render-feedback #P"contact/admin.html")))

(defroute ("/contact" :method :DELETE) ()
  "Delete *ALL* FEEDBACK."
  (v:info :contact "DELETE /contact")

  (auth (:admin)
        (progn
          (delete-from 'feedback)
          (flash-message (_ "Feedback cleared."))
          (render-feedback #P"contact/list.html"))
        (flash-error (_ "Something went wrong. Try again?"))))

(defroute ("/contact/:id/delete" :method :DELETE) (&key id)
  "Delete FEEDBACK with matching ID."

  (auth (:admin)
        (handler-case
            (ratify:with-parsed-forms
                ((:integer id))
              (delete-by-values 'feedback :id id))
          (ratify:combined-error (e)
            (flash-error e)))))

(defroute ("/contact" :method :POST) (&key _parsed)
  "User Submit Feedback POST Route. Login Required."
  (v:info :contact "POST /contact => ~a" _parsed)

  (with-logged-in-user
    (let ((user (find-dao 'user :email (user-name)))
          (body (query-param "query" _parsed)))
      (handler-case
          (ratify:with-parsed-forms
              ((:string body))
            (if (ignore-errors
                 (create-feedback user body))
                (flash-message (_ "Thanks! We got your message."))
                (flash-error (_ "Something went wrong. Try again?"))))
        (ratify:combined-error (e)
          (flash-error e))))
    (redirect "/contact")))
