<?php

/**
 PHP API for Login, Register, Changepassword, Resetpassword Requests and for Email Notifications.
 **/

if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // Get tag
    $tag = $_POST['tag'];

    // Include Database handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);

    // check for tag type
    if ($tag == 'login') {
        // Request type is check Login
        $uname = $_POST['uname'];
        $password = $_POST['password'];

        // check for user
        $user = $db->getUserByUsernameAndPassword($uname, $password);
        if ($user != false) {
            // user found
            // echo json with success = 1
            $response["success"] = 1;
            $response["user"]["fname"] = $user["firstname"];
            $response["user"]["lname"] = $user["lastname"];
			$response["user"]["address"] = $user["address"];
			$response["user"]["pnumber"] = $user["phonenumber"];
			$response["user"]["crdtcard"] = $user["creditcard"];
            $response["user"]["email"] = $user["email"];
			$response["user"]["uname"] = $user["username"];
            $response["user"]["uid"] = $user["unique_id"];
            $response["user"]["created_at"] = $user["created_at"];
            
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Incorrect username or password!";
            echo json_encode($response);
        }
    } 
	else if ($tag == 'chgpass'){
		$email = $_POST['email'];
		$uname = $_POST['uname'];
		$password = $_POST['password'];
		$newpassword = $_POST['newpas'];
		  
		$hash = $db->hashSSHA($newpassword);
		$encrypted_password = $hash["encrypted"]; // encrypted password
		$salt = $hash["salt"];
		//$subject = "Change Password Notification";
		//$message = "Hello,\n\nYour Password is sucessfully changed.\n\nRegards,\nAdmin.";
		//$from = "contact@gentzos.tk";
		//$headers = "From:" . $from;
		
		// check for user
        $user = $db->getUserByUsernameAndPassword($uname, $password);
        if ($user != false) {
            // user found
            // echo json with success = 1
			$response["success"] = 1;
            $user = $db->forgotPassword($email, $encrypted_password, $salt);
			//mail($email,$subject,$message,$headers);
            echo json_encode($response);
            
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Incorrect password!";
            echo json_encode($response);
        }
		
	}
	else if ($tag == 'forpass'){
		$forgotpassword = $_POST['forgotpassword'];

		$randomcode = $db->random_string();

		$hash = $db->hashSSHA($randomcode);
		$encrypted_password = $hash["encrypted"]; // encrypted password
		$salt = $hash["salt"];
		$subject = "Password Recovery";
		$message = "Hello,\n\nYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\n\nRegards,\nAdmin.";
		$from = "contact@gentzos.tk";
		$headers = "From:" . $from;
		if ($db->isMailExisted($forgotpassword)) {

			$user = $db->forgotPassword($forgotpassword, $encrypted_password, $salt);
			if ($user) {
				$response["success"] = 1;
				mail($forgotpassword,$subject,$message,$headers);
				echo json_encode($response);
				echo $randomcode;
			}
			else {
				$response["error"] = 1;
				echo json_encode($response);
			}
			// user is already existed - error response
		}
		else {

			$response["error"] = 2;
			$response["error_msg"] = "User not exist";
			echo json_encode($response);

		}
	}
	else if ($tag == 'register') {
		// Request type is Register new user
		$fname = $_POST['fname'];
		$lname = $_POST['lname'];
		$address = $_POST['address'];
		$pnumber = $_POST['pnumber'];
		$crdtcard = $_POST['crdtcard'];
		$email = $_POST['email'];
		$uname = $_POST['uname'];
		$password = $_POST['password'];
		
		$subject = "Registration";
        $message = "Hello $fname,\n\nYou have sucessfully registered to our service.\n\nRegards,\nAdmin.";
        $from = "contact@gentzos.tk";
        $headers = "From:" . $from;
			
		// check if user is already existed
		 if(!$db->validEmail($email)){
            $response["error"] = 3;
            $response["error_msg"] = "Invalid Email Id";
            echo json_encode($response);             
		} else if ($db->isUserExisted($uname)) {
			// user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "Username already exists";
            echo json_encode($response);
        } else if($db->isMailExisted($email)) {
			// email is already existed - error response
            $response["error"] = 4;
            $response["error_msg"] = "This e-mail is already registered";
            echo json_encode($response);            
		} else{
			// store user
			$user = $db->storeUser($fname, $lname, $address, $pnumber, $crdtcard, $email, $uname, $password);
			if ($user) {
				// user stored successfully
				$response["success"] = 1;
				$response["user"]["fname"] = $user["firstname"];
				$response["user"]["lname"] = $user["lastname"];
				$response["user"]["address"] = $user["address"];
				$response["user"]["pnumber"] = $user["phonenumber"];
				$response["user"]["crdtcard"] = $user["creditcard"];
				$response["user"]["email"] = $user["email"];
				$response["user"]["uname"] = $user["username"];
				$response["user"]["uid"] = $user["unique_id"];
				$response["user"]["created_at"] = $user["created_at"];
				mail($email,$subject,$message,$headers);
								   
				echo json_encode($response);
			} else {
				// user failed to store
				$response["error"] = 1;
				$response["error_msg"] = "JSON Error occured in Registartion";
				echo json_encode($response);
					
			}
		}
    } 
	else if ($tag == 'chgadrss'){
	
		$email = $_POST['email'];
		$newaddress = $_POST['newadr'];
		  
		if ($db->isMailExisted($email)) {
			$user = $db->changeAddress($email, $newaddress);
			if ($user) {
				$response["success"] = 1;
				echo json_encode($response);
			}
			else {
				$response["error"] = 1;
				echo json_encode($response);
			}
			// user is already existed - error response
        } 
        else {
			$response["error"] = 2;
			$response["error_msg"] = "User not exist";
			echo json_encode($response);
		}
	}
	else if ($tag == 'chgphone'){
	
		$email = $_POST['email'];
		$newphone = $_POST['newphone'];
		  
		if ($db->isMailExisted($email)) {
			$user = $db->changePhone($email, $newphone);
			if ($user) {
				$response["success"] = 1;
				echo json_encode($response);
			}
			else {
				$response["error"] = 1;
				echo json_encode($response);
			}
			// user is already existed - error response
        } 
        else {
			$response["error"] = 2;
			$response["error_msg"] = "User not exist";
			echo json_encode($response);
		}
	}
	else if ($tag == 'chgcrdt'){
	
		$email = $_POST['email'];
		$newcredit = $_POST['newcrdt'];
		  
		if ($db->isMailExisted($email)) {
			$user = $db->changeCredit($email, $newcredit);
			if ($user) {
				$response["success"] = 1;
				echo json_encode($response);
			}
			else {
				$response["error"] = 1;
				echo json_encode($response);
			}
			// user is already existed - error response
        } 
        else {
			$response["error"] = 2;
			$response["error_msg"] = "User not exist";
			echo json_encode($response);
		}
	}
	else {
        $response["error"] = 3;
        $response["error_msg"] = "JSON ERROR";
        echo json_encode($response);
    }
} else {
		echo "Admin Login API";
}
?>
