<?php
    require_once('include/functions/valid_email.php');
    require_once('include/functions/send_email.php');
    
    $_email = isset($_POST['email']) ? trim(strval($_POST['email'])) : '';
    
    if (!$_email || !is_valid_email($_email))
    {
        make_cookie('notice', 'Sorry, your email address is not valid.');
        header('Location: ./?s=new');
        die;
    }
    elseif (mysqli_num_rows(mysqli_query_logged("SELECT email FROM members WHERE email = " . sq($_email))))
    {
        make_cookie('notice', 'Sorry, that email address is already in use by another member.');
        header('Location: ./?s=new');
        die;
    }
    else
    {
        $cache = md5(time() . chr(mt_rand(97, 122)) . chr(mt_rand(97, 122)) . chr(mt_rand(97, 122)) . chr(mt_rand(97, 122)));
        mysqli_query_logged("REPLACE INTO members_create SET email = " . sq($_email) . ", cache = '" . $cache . "'");
        $number = substr_count(str_replace('www.', '', strtolower($_SERVER['HTTP_HOST'])), '.');
        $url = 'http://' . ($number == 1 ? 'www.' : '') . str_replace('www.', '', strtolower($_SERVER['HTTP_HOST'])) . '/?s=new_complete&c=' . $cache;
        $body = "You have requested an account with the Quilts Community, in order to continue please click the following link:\r\n\r\n\t" . $url . "\r\n\r\nIf you did not request this registration, please do nothing, we will not email you again.";
        send_email($_email, 'Quilts Community Registration', $body);
        header('Location: ./?s=new_thanks');
        die;
    }
?>