<?php
    include($_SERVER['DOCUMENT_ROOT'] . '/logic/testinput.php');

    $data = json_decode(file_get_contents('php://input'));

    $username = testinput($data->email);
    $password = password_hash(testinput($data->password), PASSWORD_DEFAULT);
    $email = testinput($data->email);
    $phone = testinput($data->phone);
    $salutation = testinput($data->salutation);
    $firstname = testinput($data->firstname);
    $lastname = testinput($data->lastname);
    $street = testinput($data->street);
    $postalcode = testinput($data->postalcode);
    $city = testinput($data->city);
    $role = "customer";

    registerUser($username, $password, $email, $phone, $salutation, $firstname, $lastname, $street, $postalcode, $city, $role);

    function registerUser($username, $password, $email, $phone, $salutation, $firstname, $lastname, $street, $postalcode, $city, $role)
    {

        require($_SERVER['DOCUMENT_ROOT'] . '/config/setupDBAccess.php');
        
        $sql2 = "INSERT IGNORE INTO `cities` (`postalcode`, `name`) VALUES (?,?)";
        $sql = "INSERT INTO `user` (`username`, `password`, `email`, `phone`, `salutation`, `firstname`, `lastname`, `address`, `plz`, `role`) VALUES (?,?,?,?,?,?,?,?,?,?)";
        

        $stmtUser = $db->prepare($sql);
        $stmtCities = $db->prepare($sql2);

        $stmtUser->bind_param("ssssssssss", $username, $password, $email, $phone, $salutation, $firstname, $lastname, $street, $postalcode, $role);
        $stmtCities->bind_param("is", $postalcode, $city);

        if ($stmtCities->execute() && $stmtUser->execute()) {
            $response = "success";
        } else {
            $response = "failure";
        }
        $stmtUser->close();
        $stmtCities->close();
        $db->close();
        
        echo $response;

    }