<?php
header('Content-Type: text/html; charset=utf-8');
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    
    if (!empty($_POST["website"])) {
        header("Location: /thank/");
        exit;
    }
    
    $errors = array();
    
    $fullname = isset($_POST["name"]) ? trim($_POST["name"]) : "";
    $useremail = isset($_POST["email"]) ? trim($_POST["email"]) : "";
    $userphone = isset($_POST["phone"]) ? trim($_POST["phone"]) : "";
    $usermessage = isset($_POST["message"]) ? trim($_POST["message"]) : "";
    $usersubject = isset($_POST["subject"]) ? trim($_POST["subject"]) : "New Form Submission";
    $click_id = isset($_POST["click_id"]) ? trim($_POST["click_id"]) : "";
    
    if (empty($fullname)) {
        $errors[] = "Name is required";
    }
    
    if (empty($useremail)) {
        $errors[] = "Email is required";
    } elseif (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Email format is invalid";
    }
    
    if (empty($usermessage)) {
        $errors[] = "Message is required";
    }
    
    if (!empty($errors)) {
        $error_param = urlencode(implode(", ", $errors));
        header("Location: /contact/?error=" . $error_param);
        exit;
    }
    
    $fullname = htmlspecialchars($fullname, ENT_QUOTES, 'UTF-8');
    $useremail = filter_var($useremail, FILTER_SANITIZE_EMAIL);
    $userphone = htmlspecialchars($userphone, ENT_QUOTES, 'UTF-8');
    $usermessage = htmlspecialchars($usermessage, ENT_QUOTES, 'UTF-8');
    $usersubject = htmlspecialchars($usersubject, ENT_QUOTES, 'UTF-8');
    $click_id = htmlspecialchars($click_id, ENT_QUOTES, 'UTF-8');
    
    $recipient = "hello@compactliving.hk";
    
    $emailheaders = "MIME-Version: 1.0" . "\r\n";
    $emailheaders .= "Content-type: text/plain; charset=UTF-8" . "\r\n";
    $emailheaders .= "From: " . $useremail . "\r\n";
    $emailheaders .= "Reply-To: " . $useremail . "\r\n";
    
    $emailbody = "Name: " . $fullname . "\r\n";
    $emailbody .= "Email: " . $useremail . "\r\n";
    
    if (!empty($userphone)) {
        $emailbody .= "Phone: " . $userphone . "\r\n";
    }
    
    if (!empty($click_id)) {
        $emailbody .= "Click ID: " . $click_id . "\r\n";
    }
    
    $emailbody .= "Subject: " . $usersubject . "\r\n\r\n";
    $emailbody .= "Message:\r\n";
    $emailbody .= $usermessage . "\r\n";
    
    $finalmessagesubject = "Contact Form: " . $usersubject;
    
    mail($recipient, $finalmessagesubject, $emailbody, $emailheaders);
    
    $redirect_url = "/thank/";
    if (!empty($click_id)) {
        $redirect_url .= "?click_id=" . urlencode($click_id);
    }
    
    header("Location: " . $redirect_url);
    exit;
    
}

?>