<?php

require_once('config.php');

require_once('classes/user.php');
$user_class = new User();

if(isset($_GET['token']) && $_GET['token'] != ''){
    $token = $_GET['token'];
    if(($user = $user_class->get_user_by_token($token))){
        $_SESSION['recover_user_id'] = $user['id'];
        header('Location: '.baseUrl('change_password.php'));
        die();
    }
}

if(isset($_POST['submit']) && $_POST['submit'] == "recover")
{

    $email = $_POST['email'];

    if(!($user = $user_class->get_user_by_email($email))){
        $recover['errors'][] = "User not found.";
    }else{
        $token = $user_class->generate_random_string(50);
        $user_class->update_user_data(array('token' => $token),$user['id']);
        $to = $user['email'];
        $subject = "Recover Password.";
        $message = 'Hi '.$user['name'].','."\n"
            .'<br/><br/>Someone recently requested a password change for your '.APP_NAME.' account. If this was you, you can set a new password here:'."\n"
            .'<br/><a href="'.baseUrl('recover.php?token='.$token).'">Reset password</a>'."\n"
            .'<br/><br/>If you didn\'t request this, just ignore and delete this message.'."\n"
            .'To keep your account secure, please don\'t forward this email to anyone.'."\n"
            .'<br/><br/>Thanks!'."\n"
            .''.APP_NAME.'<br/><br/>'."\n";

        $user_class->send_mail($to, $subject, $message);

        $recover['success'] = true;
    }
}

include('templates/recover.php');