<?php
require_once("include/session.php");

class Process
    {
    function Process(){
    global $session;
    if(isset($_POST['sublogin'])){
    $this->procLogin();
    }

    else if(isset($_POST['subforgot'])){
    $this->procForgotPass();
    }
 
    else if($session->logged_in){
    $this->procLogout();
    }
    else{
    header("Location: index.php");
    }
}

function procLogin(){
    global $session, $form;
    $retval = $session->login($_POST['user'], $_POST['pass']);
    if($retval){
    header("Location: ".$session->referrer);
    }
    /* Login failed */
    else{
    $_SESSION['value_array'] = $_POST;
    $_SESSION['error_array'] = $form->getErrorArray();
    header("Location: ".$session->referrer);
    }
}

function procLogout(){
    global $session;
    $retval = $session->logout();
    header("Location: index.php");
}

function procForgotPass(){
    global $database, $session, $mailer, $form;
    // Username error checking 
    $subuser = $_POST['passuser'];
    $field = "passuser";  //Use field name for username
    if(!$subuser || strlen($subuser = trim($subuser)) == 0){
    $form->setError($field, "Username not entered<br>");
    }
    else{
    // Make sure username is in database 
    $subuser = stripslashes($subuser);
    if(!$database->usernameTaken($subuser)){
    $form->setError($field, "Username is not valid<br>");
    }
    }
    // Errors exist, have user correct them 
    if($form->num_errors > 0){
    $_SESSION['value_array'] = $_POST;
    $_SESSION['error_array'] = $form->getErrorArray();
    }
    // Generate new password and email it to user 
    else{
    // Generate new password */
    $newpass = $session->generateRandStr(10);
    // Get email of user */
    $usrinf = $database->getUserInfo($subuser);
    $email  = $usrinf['email'];
    //Attempt to send the email with new password 
    if($mailer->sendNewPass($subuser,$email,$newpass)){
    // Email sent, update database 
    $database->updateUserField($subuser, "password", md5($newpass));
    $database->updateUserField($subuser, "pwdlastset", time());
    $_SESSION['forgotpass'] = true;
    }
    else{
    $_SESSION['forgotpass'] = false;
    }
    }
    header("Location: ".$session->referrer);
}

}


// Initialize process 
$process = new Process;

?>
