<?php

$inputRules = [
    "email" => ["required" => true, "validate" => ["filter" => FILTER_VALIDATE_EMAIL]],
    "message" => ["required" => true, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
];

if (!empty($__RB_config['g_r_secret']) && (empty($_SESSION) || empty($_SESSION['signed_in']))) {
    $inputRules['g-recaptcha-response'] = ["required" => true, "validate" => ["custom" => 'reCaptcha']];
}

function reCaptcha($recaptcha){
    global $__RB_config;

    $secret = $__RB_config['g_r_secret'];
    $ip = $_SERVER['REMOTE_ADDR'];

    $postvars = array("secret" => $secret, "response"=> $recaptcha, "remoteip"=> $ip);
    $url = "https://www.google.com/recaptcha/api/siteverify";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
    $data = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($data, true);

    if(!empty($res) && isset($res['success']) && !$res['success']) {
        return false;
    }

    return true;
}

if (__RB_validateInput($inputRules, 'contact')) {
    $__RB_errorBackup = $__RB_error;

    $inputRules = [
        "name" => ["required" => false, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
        "first_name" => ["required" => false, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
        "last_name" => ["required" => false, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
        "phone" => ["required" => false, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
        "subject" => ["required" => false, "validate" => ["filter" => FILTER_SANITIZE_FULL_SPECIAL_CHARS]],
    ];

    __RB_validateInput($inputRules, 'contact');

    $__RB_error = $__RB_errorBackup;

    $json = "";

    if (__RB_api_cloud(__RB_API_ACTION_CLOUD_ADD_CONTACT_MESSAGE, $_POST, $json)) {
        if ($json && is_array($json) && !empty($json['code']) && !empty($json['status']) && $json['status'] == 'failed') {
            __RB_errorHandler('contact', $json['code'] <= 1 ? 'process' : 'emailMessage', $json['code'] <= 1 ? 'Process error' : 'Email or message incorrect / missing');

        } else {
            $__RB_success['contact'] = true;
        }

    } else {
        if ($json && is_array($json) && !empty($json['code'])) {
            __RB_errorHandler('contact', $json['code'] <= 1 ? 'process' : 'emailMessage', $json['code'] <= 1 ? 'Process error' : 'Email or message incorrect / missing');

        } else {
            __RB_errorHandler('contact', 'process', 'Process error aaa');
        }
    }

}

