<?php
/**
 * Created by PhpStorm.
 * User: brycemoral
 * Date: 6/21/16
 * Time: 11:26 AM
 */
include_once('../classes/database.class.php');
$email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST, 'password');
$action = filter_input(INPUT_POST, 'action');

switch($action){
    case 'login':
        $db = new database();
        $stmt = $db->db->prepare("SELECT *, count(id) as total FROM users WHERE email = :email AND password = :password");
   		 $stmt->execute(array(':email' => $email, ':password' => ($password)));
        $userDetails = $stmt->fetch(PDO::FETCH_OBJ);
       // print_r($userDetails);
        if($userDetails->total == 1){
        setcookie("id", $userDetails->id, time() + 3600, '/');
        setcookie("uid", $userDetails->uid, time() + 3600, '/');
        echo "valid";
    	}
        else{
            echo "invalid Login";
        }
        break;
    case 'register':
        $db = new database();
		$password = ($password);
        $stmt = $db->db->prepare("SELECT count(id) as number FROM users WHERE email  = :email");
        $stmt->execute(array(':email' => $email));
        $data = $stmt->fetch(PDO::FETCH_OBJ);
        if($data->number > 0){
        	echo "Email already exists.";
        }else {
			$stmt = $db->db->prepare("INSERT INTO users (uid, email, password) VALUES (:uid, :email, :password)");
			$uid = rand(10000, 100000);
			$email = filter_input(INPUT_POST, 'email');
			$password = filter_input(INPUT_POST, 'password');
			$password = ($password);
			$count = $stmt->execute(array(':uid' => $uid, ':email' => $email, ':password' => $password));
			if($count > 0){
				setcookie("id", $db->db->lastInsertId(), time() + 3600, '/');
				setcookie("uid", $uid, time() + 3600, '/');
				if(!file_exists($uid)){
					mkdir('../droply/demo/uploads/' . $uid, 0777);
					mkdir('../droply/demo/uploads/' . $uid . '/welcome', 0777);
				}
					echo "valid";
			}
			else {
				echo "Registration failed.";
			}
        }
        break;
    case 'forgot':
//     Does not work, doesn't have the password variable
        $db = new database();
        $id = filter_input(INPUT_POST, 'id');
        $stmt = $db->db->prepare("UPDATE users SET password = :password WHERE id = :id");
        $stmt->execute(array(':id' => $id));
        if($db->db->rowcount()){
            $stmt = $db->db->prepare("SELECT *  FROM users WHERE id = :id");
            $stmt->execute(array(':id' => $id));
            $data = $stmt->fetch(PDO::FETCH_OBJ);
            mail($data->email, "Password Recovery", "Your new requested password: " . $data->password);
        }
        break;

}



?>