<?php

function verifyCaptcha(){
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $data = array(
        'secret' => '6LesRDsUAAAAAA6t3UgL4U4Foc9njmXX-8HIiLj_',
        'response' => $_POST["g-recaptcha-response"]
    );
    $options = array(
        'http' => array (
            'header' => 'Content-Type: application/x-www-form-urlencoded\r\n',
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );
    $context  = stream_context_create($options);
    $verify = file_get_contents($url, false, $context);
    $captcha_success=json_decode($verify);
    return $captcha_success;
}

function verifyExistance($doc,$mail){
    $fp = fopen("2021y22.csv", 'r');
    fclose($fp);
}

function setheaders() {
    $fp = fopen("2021y22.csv", 'w');
    $cabezal = array('Nombre', 'Apellido','TipoDoc','Documento',
                    'Direccion','Pais','Ciudad', 'Telefono', 'Email',
                    'Profesión','Trabaja en','Financiación','Detalle Financiación');
    if($fp){
    fputcsv($fp,$cabezal);
    fclose($fp);
    }
    else{
        die("unable to open file");
    }
}

function registrar($fila) {
    $fp = fopen("2021y22.csv", 'a');
    if($fp){
        fputcsv($fp,$fila);
        fclose($fp);        
        
    }
    else{
        die("unable to open file");
    }
    
}

function bkpregister(){
    $fecha = date("d-m-H:i:s");
    $filebkp = "bkp/registro-".$fecha.".bak.csv";
    copy("2021y22.csv",$filebkp);
}

$errors         = array();      // array to hold validation errors
$data           = array();      // array to pass back data
$filename       = "2021y22";

// validate the variables ======================================================
$data['nombre'] = $_POST['nombre'];
$data['apellido'] = $_POST['apellido'];
$data['pais'] = $_POST['pais'];
$data['ciudad'] = $_POST['ciudad'];
$data['email'] = $_POST['email'];
$data['titulo'] = $_POST['titulo'];
$data['llegada'] = $_POST['bda'];
$data['partida'] = $_POST['eda'];
$data['financiacion'] = $_POST['financiacion'];
$data['invitado'] = $_POST['invited'];
$data['carta'] = $_POST['letterinvited'];
$data['roomtype']  = $_POST['roomtype'];
$data['roomate']  = $_POST['roomate'];


if (empty($_POST['nombre']))
    $errors['nombre'] = 'Nombre is required.';

if (empty($_POST['apellido']))
    $errors['apellido'] = 'Apellido is required.'; 

if (empty($_POST['email']))
    $errors['email'] = 'E-Mail de contacto vacio o incorrecto';

if(empty($_POST['g-recaptcha-response'])){
    $errors['recaptcha'] = 'Debe validar el captcha';
}
else if(!verifyCaptcha()){
    $errors['recaptcha'] = 'Error en la validación de ReCaptcha';
}

if ( !empty($errors)) {

    // if there are items in our errors array, return those errors
    $data['success'] = false;
    $data['errors']  = $errors;
} 
else {
    $data['success'] = true;
    //bkpregister();
    $fila = $data;   
    registrar($fila);    
    $mail = $data["email"];
    $nombre = $data["nombre"] . " " . $data["apellido"];
    $msg = "Hi ". $data["nombre"] ."!\n\n".
    "You have been Successfully registered to the workshop on Groups, Geometry and Dynamics!\n\n".
    "For any question, write us to: ggdworkshop@cmat.edu.uy\n\n".
    "Regards,\n\n".
    "Organizing Commite, GGD Workshop.";
    $headers = 'From: ' . "ggdworkshop@cmat.edu.uy" . "\r\n" .
               'Reply-To: ' . "ggdworkshop@cmat.edu.uy" . "\r\n" .
               'Content-Type: ' . "text/plain; charset=UTF-8". "\r\n" .
               'X-Mailer: PHP/' . phpversion();
    mail($mail, 'Registration confirmation for GGDWorkshop', $msg, $headers);

    $data['message'] = "Registration Successfully!";

}

// return all our data to an AJAX call
echo json_encode($data);

?>