wwDemo::Guest_Book
FUNCTION Guest_Book
************************************************************************
* wwDemoProcess :: GuestBook
*********************************
***  Function: This method acts as a 'controller' to the 
***            template 'view' called with ExpandTemplate().
***            This code handles all the logic for displaying
***            GuestBook form. Basically it handles each of the
***            actions (button/link clicks) in a single method
***            since there is much common behavior. The template
***            page is 
***
***            There's no model or business object here to demonstrate
***            that you can easily access FoxPro tables directly.
***            Although this works I would recommend to use business
***            objects as this facilitates the 'databinding' of
***            form data into object properties (there are other
***            samples that demonstrate this).
***
***            Note that every operation works 'statelessly'
***            and receives the guest id of the currently displayed
***            record. All operations such as Next/Prev etc are
***            performed on the current record. So Next goes to
***            current record first, moves next, then displays
***            that new record's information.
***
***            Note that the template page displays PRIVATE
***            variables and fields from the database as simple
***            expressions to convey the content. See guest.wc.
************************************************************************

*** Operation to perform based on query string parameter
lcAction = UPPER(Request.QueryString("Action"))

*** Guest Id/pk - state - either from QueryString or From ID form field
pcID = Request.Params("ID")

*** Other values used on the page
pcErrorMessage = ""
pcErrorIcon = "ERROR"
pcPassword = ""
llError = .F.


*** Open the guest table we'll use to display data from
IF !USED("Guest")			
   USE (THIS.cDataPath + "Guest") IN 0
ENDIF
SELE Guest

*** Generate a new CAPTCHA AFTER you've checked it!
Captcha = CREATEOBJECT("wwWebMathCaptcha")
Captcha.Id = "Captcha"
Captcha.Text = "Please validate the code:"


*** Render it into HTML
pcCaptchaHtml = Captcha.Render()


*** If an ID was provided let's locate to the record
*** If not, is it new? If not clear out and go to bottom
IF EMPTY(pcID)
  lcAction="BOTTOM"
ELSE
  IF pcID#"NEW_ID"   && New Record get's NEW_ID
     LOCATE FOR CustId=pcID
     IF !FOUND()
        pcErrorMsg="Invalid Record. Going to bottom of file..."
        lcAction="BOTTOM"
     ENDIF   
  ENDIF
ENDIF   

*** Handle the button clicks of the page
DO CASE
  *** List Selection or List Refresh button selection
  CASE Request.IsFormVar("btnRefresh")
     pcID = Request.Form("cmbName")
     LOCATE FOR CustId = pcID
     IF !FOUND()
        GO BOTTOM
     ENDIF
     pcID = Guest.custId
  
    *** Save Operation
    CASE Request.IsFormVar("btnSubmit")  
	 IF !Process.CheckAntiForgeryToken(900)
	 	Response.Status = 500
	    this.StandardPage("Request Forgery","It appears this request has been tampered with.")
	    RETURN
	 ENDIF
		
	 *** Capturing information manually
	 *** for demonstration. Also can look into
	 *** FormVarsToObject() to capture data directly
	 *** into object properties or SCATTER NAME objects.	
	 lcName = Request.Form("txtName")
	 lcEmail = Request.Form("txtEmail")
	 lcPassword = Request.Form("txtPassword")

     *** Minimal Error checking - we need name and password
     IF EMPTY(lcName) AND EMPTY(Request.Form("txtCompany")) 
        pcErrorMessage = "Incomplete Input<hr/>You have to enter at least a name or company."
     ENDIF
     IF EMPTY(lcEmail)
        pcErrorMessage = "Incomplete Input<hr/>You have to enter an email address."
     ENDIF
     IF EMPTY(Request.Form("txtPassword"))
        pcErrorMessage = "Incomplete Input<hr/>You have to enter a password to save this entry."
     ENDIF            
     
	*** Captcha.  The variable to check is Captcha.ID + "_Input"
	IF !Captcha.ValidateCaptcha()  
	   pcErrorMessage = "Invalid form validation."
	ENDIF		

	IF EMPTY(pcErrorMessage)
		SELECT guest

	    IF EMPTY(pcID) OR pcID="NEW_ID"
	         *** Minimal Dupe check
	         LOCATE FOR UPPER(NAME)=UPPER(TRIM(Request.Form("txtName"))) AND ;
	                    UPPER(COMPANY)=UPPER(TRIM(Request.Form("txtCompany")))
	         IF !FOUND()
	            *** Add a record, create new ID
	            APPEND BLANK
	            REPLACE custid with sys(2015), ;
	                   entered with datetime(), ;
	                   name WITH lcName,;
	                   password with lcPassword
	                   
	            *** Update form variable to new id so that the 
	            *** combo properly displays the new entry - otherwise
	            *** combo uses existing POST value and displays previous selection
	            Request.SetKey("cmbName",CustId)
	          ELSE
	             pcErrorMessage = "This name has already been entered<hr>" + ;
		                          "Please check if you've previously entered yourself into the guestbook, "+;
	                              "or change your name entry slightly..."
	          ENDIF
	     ELSE
	         *** Check password
	         pcPassWord=PADR(lcPassword,8)
	         IF UPPER(guest.password) # UPPER(pcPassword)
	            pcErrorMessage="The password you typed does not allow you to change the selected entry..."
	            pcCustId=guest.custid
	            pcPassword=""
	         ENDIF
	     ENDIF

	     *** And finally write the data to the database
	     REPLACE company with Request.Form("txtCompany"),;
          	     name with lcName,;
	             Email with lcEmail,;
	             Location with Request.Form("txtLocation"),;
	             Message with Request.Form("txtMessage")		 


   	     
	            
		  pcErrorMessage="Thank you for your guest book entry."
	      pcID = guest.custid
      ENDIF
  *** Navigation Key trapping     
  CASE lcAction="TOP"
    GO TOP
    pcID = Guest.custId
  CASE lcAction="BOTTOM"
    GO BOTTOM
    pcID = Guest.custId
  CASE lcAction="NEXT"
     IF !EOF()
        SKIP  
        IF EOF()
           pcErrorMessage="You're at the last guest book entry."
        ENDIF
     ELSE
        GO BOTTOM
     ENDIF
     
     IF EOF()
        GO BOTTOM
           pcErrorMessage="You're at the last guest book entry."
     ENDIF
     pcID = Guest.custId
  CASE lcAction="PREVIOUS" AND !llError
     IF !BOF()
        SKIP -1
     ENDIF
     IF BOF()
        pcErrorMessage="You're at the beginning of the guest book."
     ENDIF
     pcID = Guest.custId
  CASE lcAction="ADD"
     *** Don't add record - move to 'ghost rec' to show blank record
     GO BOTTOM
     SKIP
     pcErrorMessage="Please fill out the guest book form and click the Save button..."
     pcErrorIcon = "INFO"
     pcID = "NEW_ID"

      
ENDCASE

*** Query for Customer Lookup Drop Down List Data to bind
*** to top list box
SELECT CustId, Name FROM guest ;
       ORDER BY name ;
       INTO CURSOR TQuery

*** Make sure our guest record stays selected
SELECT Guest


*** We have to submit the captcha AFTER checking it so we don't
*** write the new value into session. This routine
*** creates a Captcha ID and submits it to Session
Captcha.SubmitCaptcha() 

*** Render it into HTML
pcCaptchaHtml = Captcha.Render()


*** Display the template HTML page from wconnect sample directory
Response.ExpandTemplate(THIS.cHTMLPagePath + "wcscripts\guestbook.wc")
ENDFUNC