<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    require 'connection.php';
    createStudent();
}
function createstudent()
{
    global $connect;
    $firstname = $_POST["firstname"];
    $lastname = $_POST["lastname"];
    $age = $_POST["age"];
    $query = " Insert into student(firstname,lastname,age) values ('{$firstname}','{$lastname}','{$age}');";
    mysqli_query($connect, $query) or die(mysqli_error($connect));
    mysqli_close($connect);
}
    </html>
    ';
    // To send HTML mail, the Content-type header must be set
    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    // Additional headers
    $headers .= 'From: case.shareup@gmail.com' . "\r\n" . 'Reply-To: case.shareup@gmail.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
    mail($to, $subject, $message, $headers);
}
if (isset($body)) {
    $json = json_decode($body);
    $pw = generateRandomString(6);
    if (existsStudent($json->email)) {
        $message = array('error' => 'Student already exists');
    } else {
        if (createStudent($json->name, $pw, $json->birthdate, $json->university, $json->email, $json->cellphone, $json->cv, $json->linkedin)) {
            $student = studentIdByEmail($json->email);
            $studentID = $student['id'];
            $message = array('success' => 'Student was successfully created', 'userid' => $studentID);
            sendWelcomeMail($json->email, $pw);
            if (isset($json->hasPicture)) {
                $message = array('success' => 'Student was successfully created and id will be set', 'userid' => $studentID);
                $_SESSION['id'] = $studentID;
                $_SESSION['email'] = $json->email;
                $_SESSION['type'] = "student";
                $_SESSION['burner'] = "";
            }
        } else {
            $message = array('error' => 'Student was not created');
        }
    }