<?php

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

$email = [
    "job" => "Optional",
    "job_link" => "Optional",
    "first_name" => "Please enter your first name",
    "last_name" => "Please enter your last name",
    "email" => "Please enter your email address",
    "telephone" => "Please enter your phone number",
    "cv" => "Please attach your CV"
];

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

$cv_file_name = false;
$cv_file_temp = false;
$cv_file_path = false;



// 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;
            case "cv":


                $valid_extensions = array('pdf' , 'doc' , 'ppt', 'docx', 'txt'); // valid extensions
                $path = __DIR__ . '/../../../uploads/files/'; // upload directory

                if($_FILES['cv'])
                {
                    $f = $_FILES['cv']['name'];
                    $cv_file_temp = $_FILES['cv']['tmp_name'];

                    // get uploaded file's extension
                    $ext = strtolower(pathinfo($f, PATHINFO_EXTENSION));

                    // can upload same image using rand function
                    $final_f = rand(1000,1000000) . preg_replace('/\s+/', '_', $f);

                    // check's valid format
                    if( in_array($ext, $valid_extensions) ) {

                        $cv_file_path  = $path . strtolower($final_f);
                        $cv_file_name = strtolower($final_f);

                        $saved = move_uploaded_file($_FILES['cv']['tmp_name'], $cv_file_path);

                        if(empty($saved)) {
                            $errors['cv'] = 'Your Resume/CV failed to upload. Please make sure the file is a valid PDF, DOC(X), PPT or text file';
                            $form_validation = false;
                        }

                    }else{
                        $errors['cv'] = 'Please upload a valid file';
                        $form_validation = false;
                    }

                    $clean[$key] = SITE_URL . '/uploads/files/' . $cv_file_name;
                }

                break;
            default:
                if ($value == "Optional") {
                    if (trim($_REQUEST[$key]!="")) {
                        $clean[$key] = $_REQUEST[$key];
                    }
                } else {
                    if (trim($_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'   => '6LeJ3DsaAAAAAIFHCE2dLeebvNhg_qjS8mcKWP-G',
            'response' => $_REQUEST['recaptcha'],
        ];

        $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 ($resultJson->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) {

        //set header
        $to = config('site.contact_email');

        $email_header  = "From: " . $to . ",\r\n";
        $email_header .= "Reply-To:" . filter_var($clean['email']) . "\r\n";
        $email_header .= "Return-Path: " . $to . "\r\n";
        $email_header .= "MIME-Version: 1.0" . "\r\n";
        $email_header .= "Content-type:text/html;charset=utf-8" . "\r\n";

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

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

        $email_body = $twig->render('emails/contact_email/contact_email.twig', $options);

        // send the email
        if (empty($_REQUEST['answer'])) { // honeypot is empty
            $sent = mail($to, $subject, $email_body, $email_header);
            mail(DEV_EMAIL, 'COPY: '.$subject, $email_body, $email_header);
        } 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);

}
