<?php
 
//nastaveni proměnných
$_SESSION['email'] = $_POST['email'];
$_SESSION['first_name'] = $_POST['firstname'];
$_SESSION['last_name'] = $_POST['lastname'];

//chrana proti SQL injections
$first_name = $mysqli -> escape_string($_POST['firstname']);
$last_name = $mysqli -> escape_string($_POST['lastname']);
$email = $mysqli -> escape_string($_POST['email']);
$password = $mysqli -> escape_string(password_hash($_POST['password'],PASSWORD_BCRYPT));
$hash = $mysqli -> escape_string( md5( rand(0,1000)));
//kontrola existence emailu
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'") or die($mysqli->error());
if ($result->num_rows > 0) {
    $_SESSION['message'] = 'uzivatel s tímto emailem již existuje';
    header("location: error.php");
}
else {
    $sql = "INSERT INTO users (first_name, Last_name, email, password, hash)"
         ."VALUES ('$first_name','$last_name','$email','$password','$hash')";
    //pridani uzivatele do databaze
    if ($mysqli->query($sql)){
         $_SESSION['active'] = 0; //dokud uzivatel neaktivuje svuj ucet pres verify.php
         $_SESSION['logged_in'] = true;
         $_SESSION['message'] = "Ověřovací link vám byl odeslán na váš email: $email";
         //poslání registračního emailu
         $to = $email;
         $subject = 'Overeni uctu (iagriculture.cz)';
         $message_body = 'Dobrý den, '.$first_name.' ověřte váš účet kliknutím na iagriculture.cz odkaz: http://iagriculture.cz/verify.php?email='.$email.'&hash='.$hash;
         $headers .= 'From: <info@agriculture.cz>';
         mail($to, $subject, $message_body,$headers );
         header("location: success.php");
    }
    else{
        $_SESSION['message'] = 'Registrace neproběhla úspěšně!';
        header("location: error.php");
    }
  
}
        
?>
