<?php

// Example of field that is not required "variable_name" => "Optional"

init_request_values([
    'telephone',
]);

$email = [
    "full_name" => "Please enter your full name",
    "email" => "Please enter your email address",
    "telephone" => "Optional",
    "reason" => "Please select a reason for contacting us",
    "message" => "Please enter your message"
];

$form_details = [];
$errors = [];
$success = [];
$clean = [];

// if form is submitted
if (!empty($_REQUEST['submit']) && $_REQUEST['submit'] == true) {

    $form_validation = true;

    //do some validation
    foreach($email as $key => $value) {
        //add cases upon requirements!
        switch ($key) {
            case "answer": // honeypot
                break;
            case "email":
                if (!filter_var($_REQUEST[$key], FILTER_VALIDATE_EMAIL)) {
                    $errors[$key] = $value;
                    $form_validation = false;
                }
                $clean[$key] = filter_var($_REQUEST[$key], FILTER_SANITIZE_EMAIL);
                break;
            default:
                if ($value == "Optional") {
                    if (trim($_REQUEST[$key]!="")) {
                        $clean[$key] = $_REQUEST[$key];
                    }
                } else {
                    if (trim(empty($_REQUEST[$key]))) {
                        $errors[$key] = $value;
                        $form_validation = false;
                    }
                    $clean[$key] = $_REQUEST[$key];
                }

                break;
        }
    }

    // Check the Recaptcha
    if($form_validation){
        $url  = 'https://www.google.com/recaptcha/api/siteverify';
        $data = [
            'secret'   => '6LcoU44nAAAAAB1Blzo8KIUbKJ67fnPv89caPfzI',
            'response' => $_REQUEST['recaptcha'] ?? null,

        ];

        $options = [
            'http' => [
                'header'  => 'Content-type: application/x-www-form-urlencoded\r\n',
                'method'  => 'POST',
                'content' => http_build_query($data),
            ],
        ];

        $context    = stream_context_create($options);
        $result     = file_get_contents($url, false, $context);
        $resultJson = json_decode($result);
        

        if (config('app.debug')) {
            $recaptcha_score = 1;
        } else {
            $recaptcha_score = $resultJson->score ?? 0;
        }

        if ($recaptcha_score < 0.5) {
            $errors['recaptcha'] = 'We could not verify that you are not a robot. ';
            $form_validation     = false;
        }
    }


    // if form data validates
    if ($form_validation === true) {

        // send the email
        if (empty($_REQUEST['answer'])) { // honeypot is empty
            //set header
            $to = DEV_MODE ? DEV_EMAIL : config('site.contact_email');

            //generate message
            $subject = 'New Enquiry from ' . $clean['full_name'];

            $options = [
                'validated_inputs' => $clean
            ];

            $email_body = $twig->render('emails/contact_email/contact_email.twig', $options);
            $params = [
                'reply_to' => $clean['email'],
            ];

            $sent = email($to, $subject, $email_body, $params);
        } else {
            $sent = true; // if honeypot is not empty, fake it as if the email has been sent.
        }

        if ($sent == true) {
            $success['title'] = '<h2>Thank you</h2>';
            $success['message'] = '<p>We will reply as soon as possible.</p>';
            $success['hide_form'] = true;
        } else {
            $errors['messagefail'] = 'We encountered an error sending to this email';
        }
    }
}

if (!empty($_REQUEST['ajax']) && $_REQUEST['ajax'] == true) {

    $json = [
        'errors' => $errors,
        'success' => $success,
    ];

    exit(json_encode($json));

} else {

    $form_details['errors'] = $errors;
    $form_details['success'] = $success;
    $form_details['request'] = $_REQUEST;
    $form_details['self'] = $_SERVER['REQUEST_URI'];

    $twig->addGlobal('form_details', $form_details);

}
