<?php

require_once '../../vendor/autoload.php';
require_once '../../include/DatabaseConn.php';

$db = new DatabaseConn();
$link = $db->connect();

$std = new stdClass();

$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
$email = filter_input(INPUT_GET, "value", FILTER_VALIDATE_EMAIL);

header("content-type: application/json");

if ($email == null || $email == FALSE) {
    $error = 'Email is not valid';
    $std->error = $error;
    echo (json_encode($std));
    die();
} else if (is_null($id)) {
    $error = 'Token missing in request body';
    $std->error = $error;
    echo (json_encode($std));
    die();
} else {
    $email = strtolower($email);
    $stmt = mysqli_prepare($link, "select email from users WHERE email = ? ");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows > 0) {
        $error = 'Email already exist!';
        $std->error = $error;
        echo (json_encode($std));
        die();
    }
    mysqli_query($link, "update `users` set `email` = '$email' where `id` = $id");
    if (mysqli_affected_rows($link) == 1) {
        $std->msg = "Operation was successful";
        echo (json_encode($std));
        die();
    } else {
        $error = 'Already updated';
        $std->error = $error;
        echo (json_encode($std));
        die();
    }
}

