#!/bin/bash

echo "Content-type: text/html"
echo ""

# Log the raw POST data for debugging
read POST_DATA
echo "POST Data: $POST_DATA" >> /tmp/contact_form.log

# URL decoding function
urldecode() {
    local url_encoded="${1//+/ }"
    printf '%b' "${url_encoded//%/\\x}"
}

# Parse the form data using IFS
NAME=""
EMAIL=""
SUBJECT=""
MESSAGE=""

IFS='&' # Split fields by "&"
for param in $POST_DATA; do
    IFS='=' read -r key value <<< "$param"
    key=$(urldecode "$key")
    value=$(urldecode "$value")
    
    case $key in
        name) NAME="$value" ;;
        email) EMAIL="$value" ;;
        subject) SUBJECT="$value" ;;
        message) MESSAGE="$value" ;;
    esac
done

# Log the parsed values for debugging
echo "Name: $NAME, Email: $EMAIL, Subject: $SUBJECT, Message: $MESSAGE" >> /tmp/contact_form.log

# Create the email with proper headers
EMAIL_BODY=$(cat <<EOF
From: $EMAIL
To: info@willowmecreations.com, bethany@willowmecreations.com
Subject: $SUBJECT

Name: $NAME
Email: $EMAIL
Message: $MESSAGE
EOF
)

# Log the email body for debugging
echo "Email Body: $EMAIL_BODY" >> /tmp/contact_form.log

# Send the email using msmtp
echo "$EMAIL_BODY" | msmtp info@willowmecreations.com, bethany@willowmecreations.com

# Response back to the browser
cat <<EOF
<html>
<head>
    <meta http-equiv="refresh" content="5;url=/index.html">
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            background-color: #f4f4f4;
            padding-top: 50px;
        }
        .success-message {
            background-color: #4CAF50;
            color: white;
            padding: 20px;
            border-radius: 5px;
            display: inline-block;
        }
    </style>
</head>
<body>
    <div class="success-message">
        <h1>Message Sent Successfully!</h1>
        <p>Thank you for reaching out. You will be redirected to the homepage shortly.</p>
        <p>If not, <a href="/index.html">click here</a> to return to the homepage.</p>
    </div>
</body>
</html>
EOF
