<?php
    $_cache = isset($_GET['cache']) ? trim(strval($_GET['cache'])) : '';
    $_pass1 = isset($_POST['pass1']) ? trim(strval($_POST['pass1'])) : '';
    $_pass2 = isset($_POST['pass2']) ? trim(strval($_POST['pass2'])) : '';
    
    $errors = '';
        
    if (!$_pass1)
    {
        $GLOBALS['notice'] = 'You need to enter a password.';
        include('include/show/password_complete.php');
        die;
    }
    
    if (!$_pass2)
    {
        $GLOBALS['notice'] = 'You need to re-enter your password.';
        include('include/show/password_complete.php');
        die;
    }

    if ($_pass1 && $_pass2 && $_pass1 != $_pass2)
    {
        $GLOBALS['notice'] = 'Your passwords do not match.';
        include('include/show/password_complete.php');
        die;
    }
    elseif (strlen($_pass1) < PASSWORD_MIN)
    {
        $GLOBALS['notice'] = 'Your password is not long enough. Your password must be at least ' . PASSWORD_MIN . ' characters long.';
        include('include/show/password_complete.php');
        die;
    }
    elseif (strlen($_pass1) > PASSWORD_MAX)
    {
        $GLOBALS['notice'] = 'Your password is too long. Your password cannot be more than ' . PASSWORD_MAX . ' characters long.';
        include('include/show/password_complete.php');
        die;
    }
    
    $cache = mysqli_query_logged("SELECT email FROM members_create WHERE cache = " . sq($_cache));
    if ($cache = mysqli_fetch_assoc($cache))
    {
        $_email = $cache['email'];
    }
    else
    {
        make_cookie('notice', 'Sorry, there was an error in the registration process. Please try clicking the link we emailed you again to start over.');
        header('Location: ./?s=password');
        die;
    }
    
    if (!mysqli_num_rows(mysqli_query_logged("SELECT email FROM members WHERE email = " . sq($_email))))
    {
        make_cookie('notice', 'Sorry, the email address you are trying to change your password for is invalid.');
        header('Location: ./?s=password');
        die;
    }
    
    if ($errors)
    {
        include('include/show/password_complete.php');
        die;
    }
    
    $password =  md5(strtolower($_pass1));
    
    mysqli_query_logged("UPDATE members SET password = '" . $password . "' WHERE email = " . sq($_email));
    mysqli_query_logged("DELETE FROM members_create WHERE email = " . sq($_email));
    
    make_cookie('login_email', $_email);
    make_cookie('login_password', $password, 0);

    header('Location: ./?s=userinfo');
    die;
?>